remote-codex 0.11.35 → 0.11.37
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.
- package/README.md +195 -18
- package/apps/supervisor-api/dist/index.js +183 -45
- package/apps/supervisor-web/dist/assets/index-P0J5du_C.css +1 -0
- package/apps/supervisor-web/dist/assets/index-pkf-_mec.js +21 -0
- package/apps/supervisor-web/dist/assets/{thread-ui-CK1xSLOW.js → thread-ui-xWvswa2v.js} +57 -24
- package/apps/supervisor-web/dist/index.html +3 -3
- package/package.json +1 -1
- package/packages/codex/src/runtimeAdapter.test.ts +100 -1
- package/packages/codex/src/runtimeAdapter.ts +95 -28
- package/packages/codex/src/types.ts +8 -2
- package/packages/db/src/repositories.ts +16 -0
- package/apps/supervisor-web/dist/assets/index-C14vD5Hp.js +0 -21
- package/apps/supervisor-web/dist/assets/index-DYIjFImB.css +0 -1
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import{j as e,r as n,L as Ue,u as Ze,d as Lt,b as sn,e as Qs,f as Mo,N as os,B as Ho,h as an,i as je,O as _o,k as Bo,c as Wo}from"./react-vendor-Dfg_6BLf.js";import{u as Ut,a as rn,t as Fo,f as gr,T as qo,C as ea,b as Vo,c as zo,d as Go,e as Jo,g as Ko,L as Yo,P as Zo,A as Xo}from"./thread-ui-xWvswa2v.js";import{l as q}from"./ui-vendor-CuR8GHb0.js";import"./graph-vendor-DVQUpZ8C.js";import"./terminal-vendor-C5bTa-Ka.js";import"./markdown-vendor-RZk8L7-L.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const i of l.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function a(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(o){if(o.ep)return;o.ep=!0;const l=a(o);fetch(o.href,l)}})();var Qo=["codex","claude","opencode"],Ke="codex",vr={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 el(t){return typeof t=="string"&&Qo.includes(t)}function tl(t){return el(t)?t:null}var br=15;function sl(t){return t.replace(/\s+/g," ").trim()}function al(t){const s=sl(t);if(!s)return"";const a=Array.from(s);return a.length<=br?s:`${a.slice(0,br).join("")}...`}const rl=["codex","claude","opencode"],nn="codex",on={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"}},yr=15;function nl(t){return t.replace(/\s+/g," ").trim()}function ol(t){const s=nl(t);if(!s)return"";const a=Array.from(s);return a.length<=yr?s:`${a.slice(0,yr).join("")}...`}function Is(){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"})})}const ll=[{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."}],ln={hostConfigFiles:[],toolboxItems:[],hookCommandTemplates:[],providerConfigFormat:"none",mcpConfigFormat:"none",configArchives:!1,buildRestart:!1},il={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 Fs(t){const s=il[t];return{packageName:s.packageName,installed:t==="codex",installedVersion:null,latestVersion:null,installCommand:s.installCommand,updateCommand:s.updateCommand,busy:!1,lastError:null}}function dl(t,s){return{provider:t,displayName:s,description:`${s} backend descriptor is not available.`,enabled:!1,isDefault:t===nn,status:{state:"stopped",transport:on[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:ln,installation:Fs(t)}}function Rs(t){const s=t.installation??Fs(t.provider);return{...t,installation:{...Fs(t.provider),...s}}}const gt=[...rl.map(t=>dl(t,on[t].displayName))];function cl(t){var s;return((s=gt.find(a=>a.provider===t))==null?void 0:s.managementSchema)??ln}function ul(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 ml(t){const s=t.payload.details,a=typeof(s==null?void 0:s.stderr)=="string"&&s.stderr.trim()?s.stderr.trim():typeof(s==null?void 0:s.stdout)=="string"&&s.stdout.trim()?s.stdout.trim():null;return a?`${t.message}
|
|
2
|
+
${a}`:t.message}function Ct(t){return{path:t,exists:!1,originalContent:"",draftContent:"",loading:!1,saving:!1,error:null,saveMessage:null}}const hl=/^\/devices\/([^/]+)(?:\/|$)/,fl=/^(?:\/devices\/[^/]+)?\/threads\/([^/?#]+)(?:[/?#]|$)/;function dn(t){const s=hl.exec(t);return s?decodeURIComponent(s[1]??""):null}function Ye(){return typeof window>"u"?null:dn(window.location.pathname)}function pl(t){const s=fl.exec(t);return s?decodeURIComponent(s[1]??""):null}function xl(){return typeof window>"u"?null:pl(window.location.pathname)}function Dt(t,s){if(!s)return t;const a=t.startsWith("/")?t:`/${t}`;return`/devices/${encodeURIComponent(s)}${a}`}function wr(t){return Dt(t,Ye())}function qs(t,s){return Dt(`/threads/${encodeURIComponent(t)}`,s)}function $e(t){return qs(t,Ye())}function gl(t,s){const a=t?`?workspaceId=${encodeURIComponent(t)}`:"";return Dt(`/threads${a}`,s)}function Pt(t){return gl(t,Ye())}function vl(t,s){const a=t?`?workspaceId=${encodeURIComponent(t)}`:"";return Dt(`/threads/new${a}`,s)}function ls(t){return vl(t,Ye())}function Vs(t){return Dt("/workspaces",t)}function fs(){return Vs(Ye())}class ae extends Error{constructor(s,a){super(a.message),this.statusCode=s,this.payload=a}}const zs="remote-codex-auth-token",Gs="remote-codex-relay-token",Js="remote-codex-relay-admin-token",cn="remote-codex-relay-mode",Ks="remote-codex-relay-device-id",Ys="remote-codex-relay-thread-id",Zs="remote-codex:hosted-vm-wake";function jr(t){typeof window<"u"&&window.dispatchEvent(new CustomEvent(Zs,{detail:t}))}function bl(t,s){return new Promise((a,r)=>{const o=window.setTimeout(a,t);s==null||s.addEventListener("abort",()=>{window.clearTimeout(o),r(s.reason??new DOMException("Request aborted.","AbortError"))},{once:!0})})}function un(){return typeof window>"u"?null:window.localStorage.getItem(zs)}function yl(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(zs,t);return}window.localStorage.removeItem(zs)}}function mn(){return typeof window>"u"?null:window.localStorage.getItem(Gs)}function wl(){return typeof window>"u"?null:window.localStorage.getItem(Js)}function ta(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(Gs,t);return}window.localStorage.removeItem(Gs)}}function hn(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(Js,t);return}window.localStorage.removeItem(Js)}}function vt(){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.pathname.startsWith("/relay-account")||window.location.pathname.startsWith("/relay-devices")||window.location.pathname.startsWith("/relay-guide")||window.location.search.includes("relay=1")||window.localStorage.getItem(cn)==="true"}function qe(){typeof window>"u"||window.localStorage.setItem(cn,"true")}function at(){return vt()}function fn(){return typeof window>"u"?null:Ye()??window.localStorage.getItem(Ks)}function ss(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(Ks,t);return}window.localStorage.removeItem(Ks)}}function jl(){return typeof window>"u"?null:xl()??window.localStorage.getItem(Ys)}function as(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(Ys,t);return}window.localStorage.removeItem(Ys)}}function sa(t){if(!vt())return t;if(t.startsWith("/api/")){const s=fn();return s?`/relay/devices/${encodeURIComponent(s)}${t}`:`/relay${t}`}return t}function pn(t){return sa(t)}function Nl(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 kl(t,s){const a=s==null?void 0:s.trim(),r=a?`${t} ${a}`:`${t}`;return t===429?`Too many requests (${r}).`:t===503?`Upstream service unavailable (${r}).`:`Request failed (${r}).`}function ft(t,s,a){const r=typeof(s==null?void 0:s.message)=="string"&&s.message.trim()?s.message.trim():a,o=s!=null&&s.details&&typeof s.details=="object"?s.details:void 0;return{code:(s==null?void 0:s.code)??Nl(t.status),message:r,...o?{details:o}:{}}}async function xn(t){var o,l;const s=kl(t.status,t.statusText),a=((l=(o=t.headers)==null?void 0:o.get)==null?void 0:l.call(o,"content-type"))??"",r=async()=>ft(t,await t.json(),s);if(a.includes("application/json"))try{return await r()}catch{return ft(t,null,s)}try{if(typeof t.text!="function")try{return await r()}catch{return ft(t,null,s)}const i=(await t.text()).trim();if(i.startsWith("{"))try{return ft(t,JSON.parse(i),s)}catch{}return ft(t,i?{message:`${s}
|
|
3
|
+
${i}`}:null,s)}catch{try{return await r()}catch{return ft(t,null,s)}}}async function R(t,s,a={}){var i;const r=new Headers(s==null?void 0:s.headers);(s==null?void 0:s.body)!==void 0&&!(s.body instanceof FormData)&&!r.has("Content-Type")&&r.set("Content-Type","application/json");const o=vn({...s,headers:r},a.auth);let l=0;for(;;){const c=await fetch(sa(String(t)),o);if(c.ok)return l>0&&jr({state:"connected",attempt:l}),await c.json();const f=await xn(c);if(!(c.status===503&&((i=f.details)==null?void 0:i.reason)==="hosted_sandbox_starting")||l>=60)throw new ae(c.status,f);l+=1,jr({state:"starting",attempt:l}),await bl(1500,o.signal)}}function Sl(t){const s=String(t);return s.includes("/exports/pdf")?s.includes("format=html")?"remote-codex-transcript.html":"remote-codex-transcript.pdf":"download"}function Cl(t){var o;if(!t)return null;const s=t.match(/filename\*=UTF-8''([^;]+)/i);if(s!=null&&s[1])try{return decodeURIComponent(s[1].trim())}catch{return s[1].trim()}const a=t.match(/filename="([^"]+)"/i);if(a!=null&&a[1])return a[1].trim();const r=t.match(/filename=([^;]+)/i);return((o=r==null?void 0:r[1])==null?void 0:o.trim())??null}async function gn(t,s){const a=await fetch(sa(String(t)),vn(s));if(!a.ok){const o=await xn(a);throw new ae(a.status,o)}const r=Cl(a.headers.get("content-disposition"))??Sl(t);return{blob:await a.blob(),filename:r}}function vn(t={},s="default"){const a=new Headers(t.headers),r=vt();if(s!=="none"&&!a.has("Authorization"))if(s==="relay-admin"){const o=wl();o&&a.set("Authorization",`Bearer ${o}`)}else{const o=mn(),l=un();r&&o?a.set("Authorization",`Bearer ${o}`):!r&&l&&a.set("Authorization",`Bearer ${l}`)}return{...t,credentials:t.credentials??"same-origin",headers:a}}function Nr(t,s){const a=t.originalName.trim();if(a)return a;const r=t.file.name.trim();return r||(t.kind==="photo"?`photo-${s+1}.jpg`:`file-${s+1}`)}function Tl(){return R("/api/config/runtime")}function El(){return R("/api/auth/session",{cache:"no-store"})}async function Il(t){const s=await R("/api/auth/login",{method:"POST",body:JSON.stringify(t)});return yl(s.token??null),s}function bt(){return R("/relay/auth/session",{cache:"no-store"})}async function Rl(t){qe();const s=await R("/relay/auth/login",{method:"POST",body:JSON.stringify(t)},{auth:"none"});return ta(s.token),s}function bn(){return qe(),R("/relay/auth/session",{cache:"no-store"},{auth:"relay-admin"})}async function Al(t){qe();const s=await R("/relay/auth/login",{method:"POST",body:JSON.stringify({identifier:t.username,password:t.password})},{auth:"none"});return hn(s.token),s}async function Pl(){return hn(null),bn()}async function Ol(t){qe();const s=await R("/relay/auth/register",{method:"POST",body:JSON.stringify(t)},{auth:"none"});return ta(s.token??null),s}async function Ll(){const t=await R("/relay/auth/logout",{method:"POST"});return ta(null),ss(null),as(null),t}function yn(){return R("/relay/portal")}function Ul(t){const s=new URLSearchParams({deviceId:t.deviceId});return t.threadId&&s.set("threadId",t.threadId),t.workspaceId&&s.set("workspaceId",t.workspaceId),R(`/relay/access?${s.toString()}`)}function Dl(t){return R("/relay/devices",{method:"POST",body:JSON.stringify(t)})}function $l(t){return R(`/relay/devices/${encodeURIComponent(t)}`,{method:"DELETE"})}function Ml(t){return R("/relay/account",{method:"PATCH",body:JSON.stringify(t)})}function Hl(t){return R("/relay/account/password",{method:"PATCH",body:JSON.stringify(t)})}function _l(t){return R("/relay/shares",{method:"POST",body:JSON.stringify(t)})}function Bl(t,s){return R(`/relay/shares/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(s)})}function wn(t){return R(`/relay/shares/${encodeURIComponent(t)}`,{method:"DELETE"})}function Wl(t){return R("/relay/grants",{method:"POST",body:JSON.stringify(t)})}function Fl(t,s){return R(`/relay/grants/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(s)})}function ql(t){return R(`/relay/grants/${encodeURIComponent(t)}`,{method:"DELETE"})}function Vl(t){const s=t?`?days=${encodeURIComponent(String(t))}`:"";return R(`/relay/admin${s}`,void 0,{auth:"relay-admin"})}function zl(){return R("/relay/admin/hosted-sandboxes/capability",void 0,{auth:"relay-admin"})}function Gl(){return R("/relay/admin/hosted-sandboxes",void 0,{auth:"relay-admin"})}function Jl(){return R("/relay/admin/hosted-sandboxes/reconciliation",void 0,{auth:"relay-admin"})}function Kl(){return R("/relay/admin/hosted-sandboxes/reconciliation/run",{method:"POST"},{auth:"relay-admin"})}function Yl(t){return R(`/relay/admin/hosted-sandboxes/reconciliation/orphan-instances/${encodeURIComponent(t)}`,{method:"DELETE"},{auth:"relay-admin"})}function Zl(t){return R(`/relay/admin/hosted-sandboxes/reconciliation/orphan-credentials/${encodeURIComponent(t)}`,{method:"DELETE"},{auth:"relay-admin"})}function Xl(t){return R("/relay/admin/hosted-sandboxes",{method:"POST",body:JSON.stringify(t)},{auth:"relay-admin"})}function kr(t,s){return R(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}/members`,{method:"PUT",body:JSON.stringify({assignedUserIds:s})},{auth:"relay-admin"})}function Ql(t,s){return R(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}/settings`,{method:"PATCH",body:JSON.stringify(s)},{auth:"relay-admin"})}function Sr(t,s){return R(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}/${s}`,{method:"POST"},{auth:"relay-admin"})}function ei(t,s){return R(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}/snapshots`,{method:"POST",body:JSON.stringify({name:s})},{auth:"relay-admin"})}function ti(t){return R(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}/backends/codex/files`,void 0,{auth:"relay-admin"})}function si(t,s){return R(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}/backends/codex/files`,{method:"PUT",body:JSON.stringify(s)},{auth:"relay-admin"})}function ai(t){return R(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}`,{method:"DELETE"},{auth:"relay-admin"})}function ri(t){return R("/relay/admin/settings/registration",{method:"PATCH",body:JSON.stringify(t)},{auth:"relay-admin"})}function ni(t,s){return R(`/relay/admin/users/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({enabled:s})},{auth:"relay-admin"})}function oi(t){return R(`/relay/admin/users/${encodeURIComponent(t)}`,{method:"DELETE"},{auth:"relay-admin"})}function li(t,s){return R(`/relay/admin/users/${encodeURIComponent(t)}/reset-password`,{method:"POST",body:JSON.stringify({password:s})},{auth:"relay-admin"})}function ii(t){return R(`/relay/admin/registrations/${encodeURIComponent(t)}/approve`,{method:"POST"},{auth:"relay-admin"})}function di(t){return R(`/relay/admin/registrations/${encodeURIComponent(t)}/reject`,{method:"POST"},{auth:"relay-admin"})}function jn(){return R("/api/config/workspace-settings",{cache:"no-store"})}function ci(t){return R("/api/config/workspace-settings",{method:"PATCH",body:JSON.stringify(t)})}function is(){return R("/api/agent-runtimes",{cache:"no-store"})}function Nn(t){return R(`/api/agent-runtimes/${encodeURIComponent(t)}/status`,{cache:"no-store"})}function ui(t){return R(`/api/agent-runtimes/${encodeURIComponent(t)}/subscription-usage`,{cache:"no-store"})}function mi(t){return R(`/api/agent-runtimes/${encodeURIComponent(t)}/restart`,{method:"POST"})}function kn(t,s){return R(`/api/agent-runtimes/${encodeURIComponent(t)}/install`,{method:"POST",body:JSON.stringify({action:s})})}function rs(t){return R(`/api/agent-runtimes/${encodeURIComponent(t)}/models`,{cache:"no-store"})}function Sn(t,s){return R(`/api/config/providers/${encodeURIComponent(t)}/files/${encodeURIComponent(s)}`,{cache:"no-store"})}function Cn(t,s,a){return R(`/api/config/providers/${encodeURIComponent(t)}/files/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function hi(t){return R(`/api/config/providers/${encodeURIComponent(t)}/archives`,{cache:"no-store"})}function fi(t,s={}){return R(`/api/config/providers/${encodeURIComponent(t)}/archives`,{method:"POST",body:JSON.stringify(s)})}function pi(t,s,a){return R(`/api/config/providers/${encodeURIComponent(t)}/archives/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function xi(t,s){return R(`/api/config/providers/${encodeURIComponent(t)}/archives/${encodeURIComponent(s)}/apply`,{method:"POST"})}function gi(){return R("/api/service/build-restart",{method:"POST"})}function vi(){return R("/healthz",{cache:"no-store"})}function aa(){return R("/api/workspaces")}function bi(t,s={}){const a=new URLSearchParams;s.path&&a.set("path",s.path);const r=a.size>0?`?${a.toString()}`:"";return R(`/api/workspaces/${encodeURIComponent(t)}/files/tree${r}`,{cache:"no-store"})}function yi(t,s){const a=new URLSearchParams({path:s.path});return s.offset!==void 0&&a.set("offset",String(s.offset)),s.limit!==void 0&&a.set("limit",String(s.limit)),R(`/api/workspaces/${encodeURIComponent(t)}/files/preview?${a.toString()}`,{cache:"no-store"})}function wi(t,s){const a=new URLSearchParams({path:s.path});return pn(`/api/workspaces/${encodeURIComponent(t)}/files/raw?${a.toString()}`)}function ji(t,s){const a=new URLSearchParams({path:s.path});return pn(`/api/threads/${encodeURIComponent(t)}/assets/image?${a.toString()}`)}function Ni(t,s){const a=new URLSearchParams({path:s.path});return gn(`/api/workspaces/${encodeURIComponent(t)}/files/download?${a.toString()}`,{cache:"no-store"})}function ki(t,s){const a=new FormData;return a.append("file",s.file,s.file.name),R(`/api/workspaces/${encodeURIComponent(t)}/files/upload`,{method:"POST",body:a})}function Si(t,s){return R(`/api/workspaces/${encodeURIComponent(t)}/files`,{method:"PUT",body:JSON.stringify(s)})}function ra(){return R("/api/threads")}function Cr(t,s={}){const a=new URLSearchParams;return s.limit!==void 0&&a.set("limit",String(s.limit)),s.beforeTurnId&&a.set("beforeTurnId",s.beforeTurnId),R(`/api/threads/${t}${a.size>0?`?${a.toString()}`:""}`)}function Ci(t,s){return R(`/api/threads/${t}/items/${encodeURIComponent(s)}/detail`)}function Ti(){return R("/api/plugins",{cache:"no-store"})}function Ei(t){return R("/api/plugins/import",{method:"POST",body:JSON.stringify(t)})}function Ii(t,s){return R(`/api/plugins/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(s)})}function Ri(t){return R(`/api/plugins/${encodeURIComponent(t)}`,{method:"DELETE"})}function Ai(t){return R(`/api/threads/${t}/export-turns`,{cache:"no-store"})}function Pi(t,s){var r,o,l;const a=new URLSearchParams;return s.format!==void 0&&a.set("format",s.format),a.set("mode",s.mode),s.limit!==void 0&&a.set("limit",String(s.limit)),s.turnIds!==void 0&&a.set("turnIds",s.turnIds.join(",")),s.profile!==void 0&&a.set("profile",s.profile),((r=s.options)==null?void 0:r.includeTokenAndPrice)!==void 0&&a.set("includeTokenAndPrice",String(s.options.includeTokenAndPrice)),((o=s.options)==null?void 0:o.includeCommandOutput)!==void 0&&a.set("includeCommandOutput",String(s.options.includeCommandOutput)),((l=s.options)==null?void 0:l.includeAbsolutePaths)!==void 0&&a.set("includeAbsolutePaths",String(s.options.includeAbsolutePaths)),`/api/threads/${encodeURIComponent(t)}/exports/pdf?${a.toString()}`}function Oi(t,s){return gn(Pi(t,s),{cache:"no-store"})}function Li(t){return R(`/api/threads/${t}/shell`)}function Ui(t){return R("/api/threads/start",{method:"POST",body:JSON.stringify(t)})}function Di(t){return R("/api/threads/import",{method:"POST",body:JSON.stringify(typeof t=="string"?{sessionId:t}:t)})}function $i(t,s={}){return R(`/api/threads/${t}/shell`,{method:"POST",...Object.keys(s).length>0?{body:JSON.stringify(s)}:{}})}function Mi(t){return R(`/api/shells/${t}/terminate`,{method:"POST"})}function Hi(t,s){return R(`/api/shells/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function As(t,s={}){return R(`/api/threads/${t}/resume`,{method:"POST",...Object.keys(s).length>0?{body:JSON.stringify(s)}:{}})}function _i(t){return R(`/api/threads/${t}/disconnect`,{method:"POST"})}function Bi(t,s){const a=s.attachments??[];if(a.length===0)return R(`/api/threads/${t}/prompt`,{method:"POST",body:JSON.stringify(s)});const r=new FormData;r.append("prompt",s.prompt),s.clientRequestId!==void 0&&r.append("clientRequestId",s.clientRequestId),s.model!==void 0&&r.append("model",s.model),s.reasoningEffort!==void 0&&s.reasoningEffort!==null&&r.append("reasoningEffort",s.reasoningEffort),s.collaborationMode!==void 0&&r.append("collaborationMode",s.collaborationMode);const o=a.map((l,i)=>({clientId:l.clientId,kind:l.kind,originalName:Nr(l,i),placeholder:l.placeholder}));r.append("attachmentManifest",JSON.stringify(o));for(const[l,i]of a.entries())r.append("attachments",i.file,Nr(i,l));return R(`/api/threads/${t}/prompt`,{method:"POST",body:r})}function Tr(t,s={}){return R(`/api/threads/${t}/interrupt`,{method:"POST",body:JSON.stringify(s)})}function Tn(t,s){return R(`/api/threads/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function En(t){return R(`/api/threads/${t}`,{method:"DELETE"})}function Wi(t,s){return R(`/api/threads/${t}/pending-steers/${encodeURIComponent(s)}`,{method:"DELETE"})}function Fi(t,s){return R(`/api/threads/${t}/pending-steers/${encodeURIComponent(s)}/steer`,{method:"POST"})}function qi(t,s){return R(`/api/threads/${t}/settings`,{method:"PATCH",body:JSON.stringify(s)})}function Vi(t){return R(`/api/threads/${t}/compact`,{method:"POST"})}function zi(t){return R(`/api/threads/${t}/goal`,{cache:"no-store"})}function Gi(t,s){return R(`/api/threads/${t}/goal`,{method:"PATCH",body:JSON.stringify(s)})}function Ji(t){return R(`/api/threads/${t}/goal`,{method:"DELETE"})}function Ki(t){return R(`/api/threads/${t}/fork-turns`,{cache:"no-store"})}function Er(t,s){return R(`/api/threads/${t}/fork`,{method:"POST",body:JSON.stringify(s)})}function Yi(t){return R(`/api/threads/${t}/skills`,{cache:"no-store"})}function Zi(t){return R(`/api/threads/${t}/mcp-servers`,{cache:"no-store"})}function Xi(t){return R(`/api/threads/${t}/hooks`,{cache:"no-store"})}function Qi(t,s){return R(`/api/threads/${t}/hooks`,{method:"POST",body:JSON.stringify(s)})}function ed(t,s){return R(`/api/threads/${t}/hooks`,{method:"PUT",body:JSON.stringify(s)})}function td(t,s){return R(`/api/threads/${t}/hooks/trust`,{method:"POST",body:JSON.stringify(s)})}function sd(t,s){return R(`/api/threads/${t}/hooks/untrust`,{method:"POST",body:JSON.stringify(s)})}function ad(t,s,a){return R(`/api/threads/${t}/requests/${encodeURIComponent(s)}/respond`,{method:"POST",body:JSON.stringify(a)})}function rd(t){return R("/api/workspaces",{method:"POST",body:JSON.stringify(t)})}function nd(t,s){return R(`/api/workspaces/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function od(t,s){return R(`/api/workspaces/${t}`,{method:"DELETE",body:JSON.stringify(s)})}function ld(t,s){return R(`/api/workspaces/${t}/favorite`,{method:"POST",body:JSON.stringify(s)})}function In(t){const s=window.location.protocol==="https:"?"wss:":"ws:",a=new WebSocket(Rn(s));return a.addEventListener("message",r=>{try{const o=JSON.parse(r.data);dd(o)&&t(o)}catch{}}),a}function id(t={}){const s=window.location.protocol==="https:"?"wss:":"ws:",a=new WebSocket(Rn(s));return a.addEventListener("message",r=>{var o,l;try{const i=JSON.parse(r.data);if(i.type==="supervisor.connected"){(o=t.onConnected)==null||o.call(t,i);return}cd(i)&&((l=t.onShellEvent)==null||l.call(t,i))}catch{}}),{socket:a,send(r){a.send(JSON.stringify(r))}}}function Rn(t){const s=new URL(`${t}//${window.location.host}/ws`);if(vt()){const l=fn();s.pathname=l?`/relay/devices/${encodeURIComponent(l)}/ws`:"/relay/ws"}const a=un(),r=mn(),o=jl();return vt()&&r&&s.searchParams.set("relaySession",r),vt()&&o&&s.searchParams.set("threadId",o),a&&s.searchParams.set("token",a),s.toString()}function dd(t){return"threadId"in t&&t.type.startsWith("thread.")&&typeof t.payload=="object"&&t.payload!==null}function cd(t){return"shellId"in t&&t.type.startsWith("shell.")&&typeof t.payload=="object"&&t.payload!==null}function na({embedded:t=!1}={}){const s=Ut(),a=rn(),[r,o]=n.useState(""),[l,i]=n.useState({busy:!1,message:null,error:null}),[c,f]=n.useState(!1),[v,b]=n.useState(null),[g,S]=n.useState({}),y=v?g[v]:null,[m,p]=n.useState({busy:!1,message:null,error:null}),[L,M]=n.useState([]),[D,I]=n.useState(gt),[A,J]=n.useState({loading:!1,saving:!1,error:null,operatingProvider:null,operatingAction:null,message:null}),[Y,Z]=n.useState(null),[d,B]=n.useState({devHomeDraft:"",loading:!1,saving:!1,message:null,error:null}),[Q,_]=n.useState({loading:!1,creating:!1,applyingId:null,renamingId:null,renameDraft:"",message:null,error:null}),re=(s==null?void 0:s.themeMode)??"system",oe=t||!!(s!=null&&s.settingsOpen);async function ve(){const w=r.trim();if(!(!w||l.busy)){i({busy:!0,message:null,error:null});try{await a.importPluginManifest({manifestJson:w,enabled:!0}),o(""),i({busy:!1,message:"Plugin manifest imported.",error:null})}catch(E){i({busy:!1,message:null,error:E instanceof Error?E.message:"Unable to import plugin manifest."})}}}const ce=(s==null?void 0:s.effectiveTheme)??"dark",Ne=(s==null?void 0:s.autoCollapseCompletedTurns)??!0,be=(s==null?void 0:s.defaultBackend)??nn,ke=a.plugins.filter(w=>w.enabled).length,P=a.loading?"Loading...":`${ke}/${a.plugins.length} enabled`,W=D.find(w=>w.provider===be)??gt.find(w=>w.provider===be)??gt[0],te=W.managementSchema??cl(W.provider),O=te.hostConfigFiles;n.useEffect(()=>{if(!oe||t||!s||!te.configArchives)return;const w=s;function E(H){H.key==="Escape"&&w.closeSettings()}return window.addEventListener("keydown",E),()=>{window.removeEventListener("keydown",E)}},[te.configArchives,t,oe,s]),n.useEffect(()=>{if(!oe)return;let w=!1;return J(E=>({...E,loading:!0,error:null})),is().then(E=>{if(w)return;const H=[...E.map(Rs),...gt.filter(ee=>!E.some(pe=>pe.provider===ee.provider))];I(H),J(ee=>({...ee,loading:!1}))}).catch(E=>{w||(I(gt),J(H=>({...H,loading:!1,error:E instanceof ae?E.message:"Unable to load backend settings."})))}),()=>{w=!0}},[oe]),n.useEffect(()=>{if(!oe)return;let w=!1;return B(E=>({...E,loading:!0,message:null,error:null})),jn().then(E=>{w||(Z(E),B(H=>({...H,devHomeDraft:E.devHome,loading:!1})))}).catch(E=>{w||B(H=>({...H,loading:!1,error:E instanceof ae?E.message:"Unable to load workspace settings."}))}),()=>{w=!0}},[oe]),n.useEffect(()=>{if(!oe||!W.capabilities.management.hostConfigFiles)return;let w=!1;async function E(){S(ee=>{const pe={...ee};for(const Pe of O)pe[Pe.name]={...Ct(Pe.name),...ee[Pe.name],loading:!0,saving:!1,error:null,saveMessage:null};return pe});const H=await Promise.allSettled(O.map(async ee=>({name:ee.name,result:await Sn(W.provider,ee.name)})));w||S(ee=>{var Pe,rt;const pe={...ee};for(const nt of H){if(nt.status==="fulfilled"){const{name:$t,result:Xe}=nt.value;pe[$t]={path:Xe.path,exists:Xe.exists,originalContent:Xe.content,draftContent:Xe.content,loading:!1,saving:!1,error:null,saveMessage:null};continue}const xs=nt.reason instanceof ae?nt.reason.message:"Unable to load the file.",ct=((Pe=O[H.indexOf(nt)])==null?void 0:Pe.name)??((rt=O[0])==null?void 0:rt.name);ct&&(pe[ct]={...Ct(ct),...pe[ct],loading:!1,saving:!1,error:xs,saveMessage:null})}return pe})}return E(),()=>{w=!0}},[W.capabilities.management.hostConfigFiles,W.provider,O,oe]),n.useEffect(()=>{if(!oe)return;let w=!1;async function E(){_(H=>({...H,loading:!0,error:null,message:null}));try{const H=await hi(W.provider);if(w)return;M(H),_(ee=>({...ee,loading:!1}))}catch(H){if(w)return;_(ee=>({...ee,loading:!1,error:H instanceof ae?H.message:"Unable to load config archives."}))}}return E(),()=>{w=!0}},[W.provider,te.configArchives,oe]);async function K(){if(!(m.busy||A.saving)){p({busy:!0,message:null,error:null});try{const w=await mi(W.provider),E=Rs(w);p({busy:!1,message:E.status.state==="ready"?`${E.displayName} backend restarted.`:`${E.displayName} backend state: ${E.status.state}`,error:null}),I(H=>H.map(ee=>ee.provider===E.provider?E:ee))}catch(w){p({busy:!1,message:null,error:w instanceof ae?w.message:"Unable to restart the app server."})}}}async function k(w,E){if(m.busy||A.saving)return;const H=D.find(ee=>ee.provider===w);J(ee=>({...ee,saving:!0,operatingProvider:w,operatingAction:E,message:null,error:null}));try{const ee=await kn(w,E),pe=Rs(ee);I(Pe=>Pe.map(rt=>rt.provider===pe.provider?pe:rt)),J(Pe=>({...Pe,saving:!1,operatingProvider:null,operatingAction:null,message:pe.installation.lastError?`${pe.displayName} ${E==="install"?"installed":"updated"}, but requires attention:
|
|
4
|
+
${pe.installation.lastError}`:`${pe.displayName} ${E==="install"?"installed":"updated"}.`,error:null}))}catch(ee){J(pe=>({...pe,saving:!1,operatingProvider:null,operatingAction:null,message:null,error:ee instanceof ae?ml(ee):`Unable to ${E} ${(H==null?void 0:H.displayName)??w}.`}))}}async function G(){if(!(m.busy||A.saving)){p({busy:!0,message:null,error:null});try{await gi(),p({busy:!1,message:"Build and restart launched. The page may disconnect briefly.",error:null})}catch(w){p({busy:!1,message:null,error:w instanceof ae?w.message:"Unable to launch build and restart."})}}}async function ue(){const w=d.devHomeDraft.trim();if(!(!w||d.saving)){B(E=>({...E,saving:!0,message:null,error:null}));try{const E=await ci({devHome:w});Z(E),B(H=>({...H,devHomeDraft:E.devHome,saving:!1,message:"Workspace defaults saved."}))}catch(E){B(H=>({...H,saving:!1,error:E instanceof ae?E.message:"Unable to save workspace settings."}))}}}async function ge(w){const E=g[w];if(!(!E||E.saving)){S(H=>({...H,[w]:{...Ct(w),...H[w],saving:!0,error:null,saveMessage:null}}));try{const H=await Cn(W.provider,w,{content:E.draftContent});S(ee=>({...ee,[w]:{path:H.path,exists:H.exists,originalContent:H.content,draftContent:H.content,loading:!1,saving:!1,error:null,saveMessage:"Saved"}}))}catch(H){S(ee=>({...ee,[w]:{...Ct(w),...ee[w],saving:!1,error:H instanceof ae?H.message:"Unable to save the file.",saveMessage:null}}))}}}async function fe(){if(!Q.creating){_(w=>({...w,creating:!0,message:null,error:null}));try{const w=await fi(W.provider);M(E=>[w,...E]),_(E=>({...E,creating:!1,message:"Backup created."}))}catch(w){_(E=>({...E,creating:!1,error:w instanceof ae?w.message:"Unable to create a config backup."}))}}}async function u(w){if(!Q.applyingId){_(E=>({...E,applyingId:w.id,message:null,error:null}));try{const E=await xi(W.provider,w.id);_(H=>({...H,applyingId:null,message:E.status.state==="ready"?`Applied "${E.archive.label}" and restarted ${W.displayName}.`:`Applied "${E.archive.label}". ${W.displayName} state: ${E.status.state}.`}))}catch(E){_(H=>({...H,applyingId:null,error:E instanceof ae?E.message:"Unable to apply the config archive."}))}}}async function N(w){const E=Q.renameDraft.trim();if(!(!E||Q.renamingId!==w.id)){_(H=>({...H,message:null,error:null}));try{const H=await pi(W.provider,w.id,{label:E});M(ee=>ee.map(pe=>pe.id===w.id?H:pe)),_(ee=>({...ee,renamingId:null,renameDraft:"",message:"Backup renamed."}))}catch(H){_(ee=>({...ee,error:H instanceof ae?H.message:"Unable to rename the config backup."}))}}}if(!oe)return null;const X=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-3 grid gap-2",children:[a.plugins.map(w=>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:w.name}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-[var(--theme-fg-muted)]",children:w.description}),e.jsx("span",{className:"mt-2 block text-[10px] uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:[...w.capabilities.artifactTypes.map(E=>E.type),...w.capabilities.threadPanels.map(E=>E.kind??E.id)].join(", ")||"utility"}),e.jsx("span",{className:"mt-1 block text-[10px] uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:w.source==="imported"?"Imported manifest":"Built-in module"})]}),e.jsx("input",{type:"checkbox",checked:w.enabled,onChange:E=>void a.setPluginEnabled(w.id,E.currentTarget.checked),className:"mt-1 h-4 w-4 shrink-0 accent-[var(--theme-accent-solid)]"})]},w.id)),a.plugins.length===0&&e.jsx("p",{className:"rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-xs text-[var(--theme-fg-muted)]",children:"No plugins are registered."})]}),e.jsxs("div",{className:"mt-3 border-t border-[var(--theme-border)] pt-3",children:[e.jsx("label",{className:"block text-xs font-medium text-[var(--theme-fg)]",children:"Import manifest JSON"}),e.jsx("textarea",{value:r,onChange:w=>{o(w.currentTarget.value),(l.message||l.error)&&i({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 ve(),disabled:!r.trim()||l.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:l.busy?"Importing...":"Import"})]}),l.error&&e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:l.error}),l.message&&e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:l.message})]}),a.error&&e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:a.error})]}),Ce=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(Is,{})})]})}),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:"," ",ce,"."]})]})}),e.jsx("div",{className:"mt-3 grid gap-2 sm:grid-cols-3",children:ll.map(w=>{const E=re===w.value;return e.jsxs("button",{type:"button",onClick:()=>s==null?void 0:s.setThemeMode(w.value),className:`block rounded-[1rem] border px-3 py-2.5 text-left transition ${E?"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:w.label}),E?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:w.description})]},w.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:Ne,onChange:w=>{var E;return(E=s.setAutoCollapseCompletedTurns)==null?void 0:E.call(s,w.currentTarget.checked)},className:"h-4 w-4 accent-[var(--theme-accent-solid)]"}),e.jsx("span",{children:"Auto collapse"})]})]})}):null,e.jsxs("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Plugins"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Enable renderers and thread extensions loaded by this supervisor."})]}),e.jsx("button",{type:"button",onClick:()=>void a.refresh(),disabled:a.loading,className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:text-[var(--theme-fg-muted)]",children:a.loading?"Loading...":"Refresh"})]}),t?e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-2 rounded-[0.95rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2",children:[e.jsx("span",{className:"text-xs text-[var(--theme-fg-muted)]",children:P}),e.jsx("button",{type:"button",onClick:()=>f(!0),className:"rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-panel)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",children:"Manage"})]}):X]}),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:(Y==null?void 0:Y.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:d.loading&&!Y?"Loading...":(Y==null?void 0:Y.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:d.devHomeDraft,onChange:w=>B(E=>({...E,devHomeDraft:w.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 ue(),disabled:d.loading||d.saving||!d.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:d.saving?"Saving...":"Save"})]})]})]}),d.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:d.error}):d.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:d.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 K(),disabled:m.busy||A.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:m.busy?"Restarting...":"Restart"}),e.jsx("button",{type:"button",onClick:()=>void G(),disabled:m.busy||A.saving,className:"rounded-full border border-[var(--status-warning-border)] bg-[var(--status-warning-bg)] px-3 py-1.5 text-xs font-medium text-[var(--status-warning-fg)] 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:m.busy?"Working...":"Build and restart"})]})]}),e.jsx("div",{className:"mt-3 grid gap-2",children:D.map(w=>{const E=w.installation,H=!E.installed&&!!E.installCommand,ee=E.installed&&!!E.updateCommand,pe=A.saving&&A.operatingProvider===w.provider,Pe=H?"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:w.displayName}),e.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${w.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:w.enabled?"Ready":E.installed?w.status.state:"Not installed"})]}),e.jsxs("p",{className:"mt-1 truncate text-xs text-[var(--theme-fg-muted)]",children:["Version:"," ",E.installedVersion??(E.installed?"Installed":"Unavailable"),E.latestVersion?` · Latest: ${E.latestVersion}`:""]}),E.lastError?e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-rose-300",children:E.lastError}):null]}),H||ee?e.jsx("button",{type:"button","aria-label":`${H?"Install":"Update"} ${w.displayName}`,onClick:()=>void k(w.provider,H?"install":"update"),disabled:m.busy||A.saving||!H&&!ee,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:pe?A.operatingAction==="install"?"Installing...":"Updating...":Pe}):null]},w.provider)})}),m.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:m.error}):m.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:m.message}):A.message?e.jsx("p",{className:`mt-2 whitespace-pre-line text-xs ${A.message.includes("requires attention")?"text-[var(--status-warning-fg)]":"text-emerald-300"}`,children:A.message}):A.error?e.jsx("p",{className:"mt-2 whitespace-pre-line text-xs text-rose-300",children:A.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:[W.displayName," exposes these editable files through its backend schema."]})]})}),e.jsxs("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[O.map(w=>{const E=g[w.name]??{path:w.name,exists:!1,originalContent:"",draftContent:"",loading:!1},H=E.draftContent!==E.originalContent;return e.jsx("button",{type:"button",onClick:()=>b(w.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:w.label}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:w.description})]}),e.jsx("div",{className:"shrink-0",children:E.loading?e.jsx("span",{className:"text-[11px] uppercase tracking-[0.2em] text-[var(--theme-fg-muted)]",children:"Loading"}):H?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"}):E.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"})})]})},w.name)}),O.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 fe(),disabled:Q.creating,className:"shrink-0 rounded-full border border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] px-3 py-1.5 text-xs font-medium text-[var(--theme-accent-strong)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:border-[var(--theme-border)] disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:Q.creating?"Creating...":"Create backup"})]}),Q.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:Q.error}):Q.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:Q.message}):null,e.jsx("div",{className:"mt-3 space-y-2",children:Q.loading?e.jsx("p",{className:"rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-xs text-[var(--theme-fg-muted)]",children:"Loading backups..."}):L.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."}):L.map(w=>{const E=Q.renamingId===w.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:[E?e.jsxs("div",{className:"flex max-w-xl gap-2",children:[e.jsx("input",{"aria-label":`Rename ${w.label}`,value:Q.renameDraft,onChange:H=>_(ee=>({...ee,renameDraft:H.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 ${w.label}`,onClick:()=>void N(w),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:()=>_(H=>({...H,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:w.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 ",ul(w.createdAt)]}),O.map(H=>{var ee;return e.jsxs("span",{className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-2 py-0.5 font-mono",children:[H.name,":"," ",(ee=w.files[H.name])!=null&&ee.exists?"saved":"missing"]},H.name)})]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:()=>_(H=>({...H,renamingId:w.id,renameDraft:w.label,message:null,error:null})),disabled:E,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 u(w),disabled:Q.applyingId!==null,className:"rounded-full border border-emerald-400/35 bg-emerald-400/10 px-3 py-1.5 text-xs font-medium text-emerald-600 transition hover:bg-emerald-400/16 disabled:cursor-not-allowed disabled:border-[var(--theme-border)] disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)] dark:text-emerald-100",children:Q.applyingId===w.id?"Applying...":"Apply"})]})]})},w.id)})})]}):null]})})]});return t?e.jsxs("div",{className:"flex min-h-0 flex-col overflow-hidden",children:[Ce,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:()=>f(!1),className:"ui-overlay-scrim absolute inset-0 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-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] shadow-[var(--theme-shadow)]",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:P})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>void a.refresh(),disabled:a.loading,className:"rounded-md border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:text-[var(--theme-fg-muted)]",children:a.loading?"Loading...":"Refresh"}),e.jsx("button",{type:"button","aria-label":"Close plugins panel",onClick:()=>f(!1),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-surface-strong)] text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",children:e.jsx(Is,{})})]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-4",children:X})]})]}):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-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] shadow-[var(--theme-shadow)]",children:Ce}),v&&y?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-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] shadow-[var(--theme-shadow)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-[var(--theme-border)] px-4 py-3 sm:px-5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:v}),e.jsx("p",{className:"mt-1 break-all font-mono text-xs text-[var(--theme-fg-muted)]",children:y.path})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[y.error?e.jsx("span",{className:"text-xs text-rose-300",children:y.error}):y.saveMessage?e.jsx("span",{className:"text-xs text-emerald-300",children:y.saveMessage}):null,e.jsx("button",{type:"button","aria-label":`Save ${v}`,onClick:()=>void ge(v),disabled:y.loading||y.saving||y.draftContent===y.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:y.saving?"Saving...":"Save"}),e.jsx("button",{type:"button","aria-label":"Close File Editor",onClick:()=>b(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(Is,{})})]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-4 sm:p-5",children:e.jsx("textarea",{"aria-label":`Edit ${v}`,value:y.draftContent,onChange:w=>S(E=>({...E,[v]:{...Ct(v),...E[v],draftContent:w.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:y.loading?"Loading...":`Edit ${v} here`})})]})}):null]})}function An({eyebrow:t="Supervisor Access",description:s="Use the admin credentials configured on this Remote Codex server.",onLogin:a}){const[r,o]=n.useState(""),[l,i]=n.useState(""),[c,f]=n.useState(null),[v,b]=n.useState(!1);async function g(S){S.preventDefault(),f(null),b(!0);try{await a({username:r,password:l})}catch(y){y instanceof ae?f(y.payload.message):f("Unable to sign in.")}finally{b(!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-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-[var(--theme-shadow)] 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-fg-muted)]",children:t}),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-fg-muted)]",children:s})]}),e.jsxs("form",{onSubmit:g,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-lg 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:v,name:"username",onChange:S=>o(S.target.value),value:r})]}),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-lg 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:v,name:"password",onChange:S=>i(S.target.value),type:"password",value:l})]}),c&&e.jsx("p",{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:c}),e.jsx("button",{className:"h-11 w-full rounded-lg 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:v||!r.trim()||!l,type:"submit",children:v?"Signing in...":"Sign in"})]})]})})}function Ps(t,s){return t instanceof ae?t.payload.message:t instanceof Error?t.message:s}function Pn({className:t=""}){var Q;const[s,a]=n.useState(null),[r,o]=n.useState(""),[l,i]=n.useState(""),[c,f]=n.useState(""),[v,b]=n.useState(""),[g,S]=n.useState(!0),[y,m]=n.useState(!1),[p,L]=n.useState(!1),[M,D]=n.useState(null),[I,A]=n.useState(null),[J,Y]=n.useState(!1);async function Z(){var _;S(!0),A(null);try{qe();const re=await bt();a(re),o(((_=re.user)==null?void 0:_.username)??"")}catch(re){A(Ps(re,"Unable to load account."))}finally{S(!1)}}n.useEffect(()=>{Z()},[]);async function d(_){_.preventDefault(),m(!0),A(null),D(null);try{const re=await Ml({username:r});a(oe=>oe!=null&&oe.authenticated?{...oe,user:re}:oe),o(re.username),D("Account updated.")}catch(re){A(Ps(re,"Unable to update account."))}finally{m(!1)}}async function B(_){_.preventDefault(),L(!0),A(null),D(null);try{if(c!==v){A("New passwords do not match.");return}await Hl({currentPassword:l,newPassword:c}),i(""),f(""),b(""),D("Password changed.")}catch(re){A(Ps(re,"Unable to change password."))}finally{L(!1)}}return e.jsx("div",{className:`space-y-5 ${t}`.trim(),children:g?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..."}):s!=null&&s.authenticated?e.jsxs(e.Fragment,{children:[I?e.jsx(Ir,{tone:"danger",children:I}):null,M?e.jsx(Ir,{tone:"success",children:M}):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:d,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:((Q=s.user)==null?void 0:Q.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:_=>o(_.target.value),value:r})]}),e.jsxs("button",{className:"relay-button-primary inline-flex h-10 items-center justify-center gap-2",disabled:y||!r.trim(),type:"submit",children:[e.jsx(q.Save,{className:"h-4 w-4"}),"Save"]})]}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:()=>Y(!0),type:"button",children:[J?e.jsx(q.CheckCircle2,{className:"h-4 w-4"}):e.jsx(q.MailCheck,{className:"h-4 w-4"}),J?"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:B,children:[e.jsx(Os,{label:"Current password",value:l,onChange:i}),e.jsx(Os,{label:"New password",value:c,onChange:f}),e.jsx(Os,{label:"Confirm password",value:v,onChange:b}),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:p||!l||c.length<8||!v,type:"submit",children:[e.jsx(q.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 ud(){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(Ue,{className:"text-sm text-[var(--theme-accent-strong)]",to:"/relay-devices",children:"Back to relay portal"}),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"})]}),e.jsx(Pn,{})]})})}function Os({label:t,value:s,onChange:a}){return e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:[t,e.jsx("input",{autoComplete:"new-password",className:"relay-input mt-2 w-full",onChange:r=>a(r.target.value),type:"password",value:s})]})}function Ir({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 We(t){return t instanceof ae?t.payload.message:t instanceof Error?t.message:"Unable to update relay admin state."}function md(){const[t,s]=n.useState(null),[a,r]=n.useState(!0),[o,l]=n.useState(null),[i,c]=n.useState(!1),[f,v]=n.useState(null),[b,g]=n.useState("overview"),[S,y]=n.useState(7),[m,p]=n.useState(null),[L,M]=n.useState(null),[D,I]=n.useState([]),[A,J]=n.useState(null),[Y,Z]=n.useState(!1),[d,B]=n.useState(null),[Q,_]=n.useState(null);async function re(O=S,K={}){K.showLoading!==!1&&r(!0),l(null);try{qe();const k=await Vl(O);s(k),p(k.settings),y(k.conversationWindowDays),c(!1)}catch(k){k instanceof ae&&(k.statusCode===401||k.statusCode===403)?(s(null),c(!0),l(null)):l(We(k))}finally{r(!1)}}n.useEffect(()=>{re()},[]);async function oe(O={}){O.showLoading!==!1&&Z(!0),B(null);const[K,k,G]=await Promise.allSettled([zl(),Gl(),Jl()]);K.status==="fulfilled"?M(K.value):(M(null),B(We(K.reason))),k.status==="fulfilled"?I(k.value.sandboxes):B(ue=>ue??We(k.reason)),G.status==="fulfilled"?J(G.value):(J(null),B(ue=>ue??We(G.reason))),O.showLoading!==!1&&Z(!1)}n.useEffect(()=>{b==="hosted"&&oe()},[b]),n.useEffect(()=>{if(b!=="hosted")return;const O=D.some(k=>["requested","creating","starting","provisioning","stopping","deleting"].includes(k.status)),K=window.setInterval(()=>void oe({showLoading:!1}),O?2e3:15e3);return()=>window.clearInterval(K)},[b,D]);async function ve(O,K){_(O),B(null);try{await K(),await oe(),window.setTimeout(()=>void oe(),750)}catch(k){B(We(k))}finally{_(null)}}const ce=n.useMemo(()=>{const O=(t==null?void 0:t.users)??[],K=(t==null?void 0:t.devices)??[];return{users:O.length,enabledUsers:O.filter(k=>k.enabled).length,devices:K.length,onlineDevices:K.filter(k=>k.connected).length,conversations:O.reduce((k,G)=>k+G.conversationCount,0),shares:(t==null?void 0:t.shares.filter(k=>!k.revokedAt).length)??0}},[t]);async function Ne(O,K){v(O),l(null);try{const k=await ni(O,K);s(G=>Ar(G,k))}catch(k){l(We(k))}finally{v(null)}}async function be(O){v(`delete:${O}`),l(null);try{await oi(O),await re(S,{showLoading:!1})}catch(K){l(We(K))}finally{v(null)}}async function ke(O,K){v(`reset:${O}`),l(null);try{const k=await li(O,K);s(G=>Ar(G,k))}catch(k){l(We(k))}finally{v(null)}}async function P(O){if(O.preventDefault(),!!m){v("settings"),l(null);try{const K=await ri(m);s(k=>k&&{...k,registrationEnabled:K.registrationEnabled,settings:K.settings}),p(K.settings)}catch(K){l(We(K))}finally{v(null)}}}async function W(O,K){v(`${K}:${O}`),l(null);try{K==="approve"?await ii(O):await di(O),await re(S,{showLoading:!1})}catch(k){l(We(k))}finally{v(null)}}async function te(O){await Al(O),await re(S)}return i?e.jsx(An,{description:"Use the relay admin credentials for this server. This does not replace your normal relay account.",eyebrow:"Relay Admin",onLogin:te}):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(yd,{onLogout:()=>{s(null),c(!0)}}),e.jsxs("div",{className:"mx-auto flex w-full max-w-7xl flex-col gap-5",children:[e.jsxs("header",{className:"flex flex-col gap-4 border-b border-[var(--theme-border)] pb-5 lg:flex-row lg:items-end lg: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:"Operations panel"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-[var(--theme-fg-muted)]",children:"Accounts, devices, usage, registration policy, and shared thread access."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm text-[var(--theme-fg-muted)]",children:["Usage window",e.jsxs("select",{className:"relay-input h-10 w-24",onChange:O=>void re(Number(O.target.value)),value:S,children:[e.jsx("option",{value:1,children:"1 day"}),e.jsx("option",{value:7,children:"7 days"}),e.jsx("option",{value:30,children:"30 days"}),e.jsx("option",{value:90,children:"90 days"})]})]}),e.jsx(Ue,{className:"relay-button-secondary",to:"/",children:"Relay home"}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:()=>void re(S),type:"button",children:[e.jsx(q.RefreshCw,{className:"h-4 w-4"}),"Refresh"]})]})]}),o?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:o}):null,a?e.jsx("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4 text-sm text-[var(--theme-fg-muted)]",children:"Loading relay admin..."}):t?e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsx(Zt,{icon:e.jsx(q.Users,{className:"h-5 w-5"}),label:"Users",value:ce.users,detail:`${ce.enabledUsers} enabled`}),e.jsx(Zt,{icon:e.jsx(q.Database,{className:"h-5 w-5"}),label:"Devices",value:ce.devices,detail:`${ce.onlineDevices} online`}),e.jsx(Zt,{icon:e.jsx(q.Clock3,{className:"h-5 w-5"}),label:`Conversations, ${t.conversationWindowDays}d`,value:ce.conversations,detail:"Relay prompt/start events"}),e.jsx(Zt,{icon:e.jsx(q.Share2,{className:"h-5 w-5"}),label:"Active shares",value:ce.shares,detail:`${t.pendingRegistrations.length} pending registrations`})]}),e.jsx("nav",{className:"flex gap-2 overflow-x-auto border-b border-[var(--theme-border)] pb-2",children:["overview","users","devices","hosted","shares","settings"].map(O=>e.jsx("button",{className:`rounded-md px-3 py-2 text-sm font-medium ${b===O?"bg-[var(--theme-accent-soft)] text-[var(--theme-fg)]":"text-[var(--theme-fg-muted)] hover:bg-[var(--theme-hover)] hover:text-[var(--theme-fg)]"}`,onClick:()=>g(O),type:"button",children:Pd(O)},O))}),b==="overview"?e.jsx(wd,{summary:t}):null,b==="users"?e.jsx(jd,{busyKey:f,onDeleteUser:be,onResetPassword:ke,onUpdateUser:Ne,users:t.users}):null,b==="devices"?e.jsx(Nd,{devices:t.devices,users:t.users}):null,b==="hosted"?e.jsx(hd,{busyKey:Q,capability:L,error:d,loading:Y,onAction:ve,onRefresh:oe,sandboxes:D,reconciliation:A,users:t.users}):null,b==="shares"?e.jsx(kd,{shares:t.shares}):null,b==="settings"&&m?e.jsx(Sd,{busy:f==="settings",draft:m,onChange:p,onReviewRegistration:W,onSave:P,pending:t.pendingRegistrations,reviewBusyKey:f}):null]}):null]})]})}function hd({busyKey:t,capability:s,error:a,loading:r,onAction:o,onRefresh:l,reconciliation:i,sandboxes:c,users:f}){var Z;const v=f.filter(d=>d.role==="user"&&d.enabled),[b,g]=n.useState([]),[S,y]=n.useState("Hosted Codex"),[m,p]=n.useState("standard"),[L,M]=n.useState(`model_provider = "OpenAI"
|
|
5
|
+
model = "gpt-5.6-sol"
|
|
6
|
+
review_model = "gpt-5.6-sol"
|
|
7
|
+
model_reasoning_effort = "low"
|
|
8
|
+
disable_response_storage = true
|
|
9
|
+
network_access = "enabled"
|
|
10
|
+
|
|
11
|
+
[model_providers.OpenAI]
|
|
12
|
+
name = "OpenAI"
|
|
13
|
+
base_url = "https://sub.lnz-study.com"
|
|
14
|
+
wire_api = "responses"
|
|
15
|
+
requires_openai_auth = true
|
|
16
|
+
|
|
17
|
+
[features]
|
|
18
|
+
goals = true
|
|
19
|
+
`),[D,I]=n.useState(""),A=(s==null?void 0:s.available)===!0&&b.length>0;async function J(d){if(d.preventDefault(),!A)return;const B=m==="large"?{cpuCount:2,memoryMiB:2048,diskGiB:12}:{cpuCount:1,memoryMiB:1536,diskGiB:10};await o("hosted:create",()=>Xl({assignedUserIds:b,deviceName:S,imageVersion:"ubuntu-24.04-v5",resources:B,backends:["codex"],codexFiles:{configToml:L,authJson:D}})),I("")}const Y=s!=null&&s.available?"success":s!=null&&s.configured?"warning":"neutral";return e.jsxs("section",{className:"space-y-4","aria-label":"Hosted supervisor VMs",children:[e.jsxs("div",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)]",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[e.jsx("span",{className:"rounded-lg bg-[var(--theme-surface)] p-2 text-[var(--theme-fg-soft)]",children:e.jsx(q.Server,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Hosted supervisor VMs"}),e.jsx(Rt,{tone:Y,children:s!=null&&s.available?"Available":s!=null&&s.configured?"Unavailable":"Disabled"})]}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm text-[var(--theme-fg-muted)]",children:(s==null?void 0:s.reason)??"Incus VMs run one isolated relay supervisor per assigned user."}),s!=null&&s.capacity&&s.limits?e.jsxs("p",{className:"mt-1 text-xs text-[var(--theme-fg-soft)]",children:[s.capacity.runningInstances,"/",s.limits.maxRunningInstances," running ·"," ",s.capacity.totalInstances,"/",s.limits.maxInstances," total"]}):null,s!=null&&s.metrics?e.jsxs("p",{className:"mt-1 text-xs text-[var(--theme-fg-soft)]",children:[s.metrics.cpuCount," CPU · load"," ",s.metrics.load1.toFixed(2)," ·"," ",Math.round(s.metrics.memoryAvailableMiB/1024)," GiB RAM free · ",s.metrics.diskAvailableGiB.toFixed(1)," ","GiB disk free"]}):null,(Z=s==null?void 0:s.alerts)==null?void 0:Z.map(d=>e.jsx("p",{className:"mt-1 text-xs text-amber-700 dark:text-amber-300",role:"alert",children:d.message},d.code))]})]}),e.jsxs("button",{className:"relay-button-secondary inline-flex min-h-11 items-center justify-center gap-2",disabled:r,onClick:()=>void l(),type:"button",children:[e.jsx(q.RefreshCw,{className:`h-4 w-4 ${r?"animate-spin":""}`}),"Check host"]})]}),a?e.jsx("div",{className:"border-t border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] px-4 py-3 text-sm text-[var(--status-danger-fg)]",role:"alert",children:a}):null,e.jsx(fd,{busyKey:t,onAction:o,reconciliation:i}),e.jsxs("details",{className:"border-t border-[var(--theme-border)]",open:c.length===0,children:[e.jsxs("summary",{className:"flex min-h-12 cursor-pointer list-none items-center gap-2 px-4 py-3 text-sm font-medium text-[var(--theme-fg)] hover:bg-[var(--theme-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--theme-accent-ring)]",children:[e.jsx(q.Plus,{className:"h-4 w-4"}),"Create hosted VM"]}),e.jsxs("form",{className:"grid gap-4 border-t border-[var(--theme-border)] p-4 lg:grid-cols-2",onSubmit:J,children:[e.jsxs("fieldset",{className:"text-sm text-[var(--theme-fg-soft)]",children:[e.jsx("legend",{children:"Assigned users"}),e.jsx("div",{className:"mt-2 max-h-48 overflow-y-auto rounded-md border border-[var(--theme-border)] bg-[var(--theme-surface)]",children:v.length?v.map(d=>e.jsxs("label",{className:"flex min-h-11 cursor-pointer items-center gap-3 border-b border-[var(--theme-border)] px-3 last:border-b-0 hover:bg-[var(--theme-hover)]",children:[e.jsx("input",{"aria-label":`Assign ${d.username} (${d.email})`,checked:b.includes(d.id),disabled:!(s!=null&&s.available),onChange:B=>g(Q=>B.target.checked?[...Q,d.id]:Q.filter(_=>_!==d.id)),type:"checkbox"}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-medium text-[var(--theme-fg)]",children:d.username}),e.jsx("span",{className:"block truncate text-xs text-[var(--theme-fg-muted)]",children:d.email})]})]},d.id)):e.jsx("p",{className:"px-3 py-3 text-xs text-[var(--theme-fg-muted)]",children:"Create and enable a user account before assigning a VM."})}),e.jsxs("span",{className:"mt-1 block text-xs text-[var(--theme-fg-muted)]",children:[b.length," selected · all receive full VM access"]})]}),e.jsxs("label",{className:"text-sm text-[var(--theme-fg-soft)]",children:["Device name",e.jsx("input",{className:"relay-input mt-2 w-full",maxLength:120,onChange:d=>y(d.target.value),required:!0,value:S})]}),e.jsxs("label",{className:"text-sm text-[var(--theme-fg-soft)]",children:["Resources",e.jsxs("select",{className:"relay-input mt-2 w-full",onChange:d=>p(d.target.value),value:m,children:[e.jsx("option",{value:"standard",children:"Standard, 1 CPU · 1.5 GiB · 10 GiB"}),e.jsx("option",{value:"large",children:"Large, 2 CPU · 2 GiB · 12 GiB"})]})]}),e.jsxs("label",{className:"text-sm text-[var(--theme-fg-soft)]",children:["Backends",e.jsxs("select",{className:"relay-input mt-2 w-full",value:"codex",onChange:()=>{},children:[e.jsx("option",{value:"codex",children:"Codex"}),e.jsx("option",{disabled:!0,children:"Claude Code (coming soon)"}),e.jsx("option",{disabled:!0,children:"OpenCode (coming soon)"})]})]}),e.jsxs("details",{className:"rounded-md border border-[var(--theme-border)] lg:col-span-2",open:!0,children:[e.jsx("summary",{className:"cursor-pointer px-3 py-2 text-sm font-medium text-[var(--theme-fg)]",children:"Codex files"}),e.jsxs("div",{className:"space-y-4 border-t border-[var(--theme-border)] p-3",children:[e.jsx(ds,{filename:"config.toml",language:"TOML",onChange:M,value:L}),e.jsx(ds,{filename:"auth.json",language:"JSON",onChange:I,value:D})]})]}),e.jsxs("div",{className:"flex flex-col gap-2 lg:col-span-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("p",{className:"flex items-center gap-2 text-xs text-[var(--theme-fg-muted)]",children:[e.jsx(q.ShieldCheck,{className:"h-4 w-4"}),"The relay stores only an opaque credential reference."]}),e.jsxs("button",{className:"relay-button-primary inline-flex min-h-11 items-center justify-center gap-2",disabled:!A||!L.trim()||!D.trim()||t==="hosted:create",type:"submit",children:[e.jsx(q.Plus,{className:"h-4 w-4"}),t==="hosted:create"?"Creating…":"Create hosted VM"]})]})]})]})]}),e.jsxs("div",{className:"overflow-hidden rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)]",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",{children:[e.jsx("h3",{className:"text-sm font-semibold text-[var(--theme-fg)]",children:"Managed VMs"}),e.jsx("p",{className:"text-xs text-[var(--theme-fg-muted)]",children:"Turn-aware idle stop is 30 minutes after the last terminal activity."})]}),e.jsx("span",{className:"text-sm tabular-nums text-[var(--theme-fg-muted)]",children:c.length})]}),r&&c.length===0?e.jsxs("div",{className:"space-y-3 p-4","aria-label":"Loading hosted VMs",children:[e.jsx("div",{className:"h-14 animate-pulse rounded-md bg-[var(--theme-muted)]"}),e.jsx("div",{className:"h-14 animate-pulse rounded-md bg-[var(--theme-muted)]"})]}):c.length?e.jsx("div",{className:"divide-y divide-[var(--theme-border)]",children:c.map(d=>e.jsx(pd,{busyKey:t,onAction:o,sandbox:d,users:v},d.id))}):e.jsx("div",{className:"p-6 text-center text-sm text-[var(--theme-fg-muted)]",children:"No hosted VMs yet. Open “Create hosted VM” to assign the first one."})]})]})}function fd({busyKey:t,onAction:s,reconciliation:a}){const r=a?a.missingInstanceSandboxIds.length+a.missingCredentialSandboxIds.length+a.orphanInstances.length+a.orphanCredentials.length:0,o=(a==null?void 0:a.status)==="healthy"?"success":(a==null?void 0:a.status)==="issues"||(a==null?void 0:a.status)==="unavailable"?"warning":"neutral",l=(a==null?void 0:a.status)==="healthy"?"Inventory healthy":(a==null?void 0:a.status)==="issues"?`${r} inventory issue${r===1?"":"s"}`:(a==null?void 0:a.status)==="unavailable"?"Inventory unavailable":"Inventory not checked";return e.jsxs("div",{className:"border-t border-[var(--theme-border)] px-4 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{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:"Relay ↔ Incus inventory"}),e.jsx(Rt,{tone:o,children:l})]}),e.jsx("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:"Audit only; resources are deleted only after an explicit admin action and a fresh orphan check."})]}),e.jsxs("button",{className:"relay-button-secondary inline-flex min-h-10 items-center justify-center gap-2",disabled:t==="hosted:reconcile",onClick:()=>void s("hosted:reconcile",Kl),type:"button",children:[e.jsx(q.RefreshCw,{className:`h-4 w-4 ${t==="hosted:reconcile"?"animate-spin":""}`}),"Run inventory audit"]})]}),a==null?void 0:a.missingInstanceSandboxIds.map(i=>e.jsxs("p",{className:"mt-2 text-xs text-amber-700 dark:text-amber-300",children:["Missing Incus instance for relay sandbox ",i]},`missing-instance-${i}`)),a==null?void 0:a.missingCredentialSandboxIds.map(i=>e.jsxs("p",{className:"mt-2 text-xs text-amber-700 dark:text-amber-300",children:["Missing credential for relay sandbox ",i]},`missing-credential-${i}`)),a==null?void 0:a.orphanInstances.map(i=>e.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-between gap-2 rounded-md bg-[var(--theme-surface)] px-3 py-2",children:[e.jsxs("span",{className:"text-xs text-[var(--theme-fg-soft)]",children:["Orphan VM ",i.id," · ",i.status," ·"," ",i.snapshots.length," snapshots"]}),e.jsx("button",{className:"relay-button-danger min-h-9",disabled:t===`hosted:orphan-instance:${i.id}`,onClick:()=>void s(`hosted:orphan-instance:${i.id}`,()=>Yl(i.id)),type:"button",children:"Delete orphan VM"})]},i.id)),a==null?void 0:a.orphanCredentials.map(i=>e.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-between gap-2 rounded-md bg-[var(--theme-surface)] px-3 py-2",children:[e.jsxs("span",{className:"text-xs text-[var(--theme-fg-soft)]",children:["Orphan credential ",i.credentialRef]}),e.jsx("button",{className:"relay-button-danger min-h-9",disabled:t===`hosted:orphan-credential:${i.credentialRef}`,onClick:()=>void s(`hosted:orphan-credential:${i.credentialRef}`,()=>Zl(i.credentialRef)),type:"button",children:"Delete orphan credential"})]},i.credentialRef))]})}function pd({busyKey:t,onAction:s,sandbox:a,users:r}){const[o,l]=n.useState(!1),[i,c]=n.useState(!1),[f,v]=n.useState(""),[b,g]=n.useState(!1),[S,y]=n.useState(()=>Date.now()),m=(t==null?void 0:t.endsWith(a.id))??!1,p=gd(a.status),L=a.assignedUsers.map(I=>I.userId),M=f.trim().toLowerCase(),D=r.filter(I=>!L.includes(I.id)).filter(I=>M?[I.id,I.username,I.email].some(A=>A.toLowerCase().includes(M)):!1).slice(0,6);return n.useEffect(()=>{if(!a.runningSince)return;const I=window.setInterval(()=>y(Date.now()),3e4);return()=>window.clearInterval(I)},[a.runningSince]),n.useEffect(()=>{if(!b)return;const I=A=>{A.key==="Escape"&&g(!1)};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[b]),e.jsxs("article",{className:"px-4 py-4",children:[e.jsxs("div",{className:"flex flex-col gap-4 xl:flex-row xl:items-start xl: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("h4",{className:"truncate text-sm font-semibold text-[var(--theme-fg)]",children:a.deviceName}),e.jsx(Rt,{tone:p,children:vd(a.status)}),a.activeTurnCount>0?e.jsxs(Rt,{tone:"warning",children:[a.activeTurnCount," active turn",a.activeTurnCount===1?"":"s"]}):null,a.workspaceIsolationEnabled?e.jsx(Rt,{tone:"success",children:"Private workspaces"}):null]}),e.jsxs("p",{className:"mt-1 text-sm text-[var(--theme-fg-soft)]",children:[a.assignedUsers.map(I=>I.username).join(", "),e.jsx("span",{className:"mx-2 text-[var(--theme-fg-muted)]",children:"·"}),a.resources.cpuCount," CPU ·"," ",bd(a.resources.memoryMiB)," ·"," ",a.resources.diskGiB," GiB"]}),e.jsxs("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:["Updated ",Fe(a.updatedAt),a.runningSince?` · running for ${Ud(a.runningSince,S)}`:"",a.idleDeadlineAt?` · idle stop ${Fe(a.idleDeadlineAt)}`:""]}),a.lastErrorMessage?e.jsx("p",{className:"mt-2 text-sm text-[var(--status-danger-fg)]",role:"status",children:a.lastErrorMessage}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.status==="stopped"||a.status==="error"?e.jsxs("button",{className:"relay-button-secondary inline-flex min-h-11 items-center gap-2",disabled:m,onClick:()=>void s(`start:${a.id}`,()=>Sr(a.id,a.status==="error"?"retry":"start")),type:"button",children:[a.status==="error"?e.jsx(q.RotateCcw,{className:"h-4 w-4"}):e.jsx(q.Play,{className:"h-4 w-4"}),a.status==="error"?"Retry":"Start"]}):e.jsxs("button",{className:"relay-button-secondary inline-flex min-h-11 items-center gap-2",disabled:m||a.activeTurnCount>0||a.status!=="online",onClick:()=>void s(`stop:${a.id}`,()=>Sr(a.id,"stop")),title:a.activeTurnCount>0?"An active turn prevents stopping.":void 0,type:"button",children:[e.jsx(q.Square,{className:"h-4 w-4"}),"Stop"]}),e.jsxs("button",{className:"relay-button-secondary inline-flex min-h-11 items-center gap-2",disabled:m||a.status!=="online"||a.activeTurnCount>0,onClick:()=>void s(`snapshot:${a.id}`,()=>ei(a.id,`manual-${Date.now()}`)),type:"button",children:[e.jsx(q.Camera,{className:"h-4 w-4"}),"Snapshot"]}),e.jsxs("button",{className:"relay-button-secondary inline-flex min-h-11 items-center gap-2",disabled:m,onClick:()=>g(!0),type:"button",children:[e.jsx(q.Settings,{className:"h-4 w-4"}),"Manage"]}),o?e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-md bg-[var(--status-danger-bg)] p-1",children:[e.jsx("button",{className:"min-h-9 rounded-md px-3 text-sm font-medium text-[var(--status-danger-fg)] hover:bg-[var(--theme-hover)]",disabled:m,onClick:()=>void s(`delete:${a.id}`,()=>ai(a.id)),type:"button",children:"Confirm delete"}),e.jsx("button",{className:"min-h-9 rounded-md px-2 text-sm text-[var(--theme-fg-muted)] hover:bg-[var(--theme-hover)]",onClick:()=>l(!1),type:"button",children:"Cancel"})]}):e.jsx("button",{className:"relay-button-secondary min-h-11 text-[var(--status-danger-fg)]",disabled:m||a.activeTurnCount>0,onClick:()=>l(!0),type:"button",children:"Delete"})]})]}),b?e.jsxs("div",{className:"fixed inset-0 z-50 flex justify-end",role:"presentation",children:[e.jsx("button",{"aria-label":"Close VM management",className:"absolute inset-0 bg-[var(--overlay-scrim)]",onClick:()=>g(!1),type:"button"}),e.jsxs("section",{"aria-label":`Manage ${a.deviceName}`,"aria-modal":"true",className:"relative flex h-full w-full max-w-2xl flex-col border-l border-[var(--theme-border)] bg-[var(--theme-panel)] shadow-2xl shadow-[var(--theme-shadow)]",role:"dialog",children:[e.jsxs("header",{className:"flex min-h-16 items-center justify-between gap-4 border-b border-[var(--theme-border)] px-5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h3",{className:"truncate text-base font-semibold text-[var(--theme-fg)]",children:["Manage ",a.deviceName]}),e.jsx("p",{className:"mt-0.5 text-xs text-[var(--theme-fg-muted)]",children:"Access, isolation, credentials, and recovery settings"})]}),e.jsx("button",{"aria-label":"Close VM management",className:"relay-button-secondary inline-flex h-10 w-10 items-center justify-center p-0",onClick:()=>g(!1),type:"button",children:e.jsx(q.X,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-5",children:[e.jsx("div",{className:"max-w-2xl rounded-md border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:e.jsxs("label",{className:"flex cursor-pointer items-start justify-between gap-4",children:[e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-medium text-[var(--theme-fg)]",children:"Isolate user workspaces"}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Each authorized user sees only their own workspaces. Their first visit creates a private workspace and an initial Codex thread."})]}),e.jsx("input",{"aria-label":`Isolate user workspaces for ${a.deviceName}`,checked:a.workspaceIsolationEnabled,className:"mt-1 h-4 w-4 shrink-0 accent-[var(--theme-accent-strong)]",disabled:m,onChange:I=>void s(`settings:${a.id}`,()=>Ql(a.id,{workspaceIsolationEnabled:I.target.checked})),type:"checkbox"})]})}),e.jsxs("details",{className:"mt-4",open:!0,children:[e.jsxs("summary",{className:"cursor-pointer text-xs font-medium text-[var(--theme-fg-muted)] hover:text-[var(--theme-fg)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--theme-accent-ring)]",children:["Access · ",a.assignedUsers.length," user",a.assignedUsers.length===1?"":"s"]}),e.jsxs("div",{className:"mt-3 max-w-2xl overflow-hidden rounded-md border border-[var(--theme-border)]",children:[e.jsxs("div",{className:"flex min-h-11 items-center justify-between gap-3 bg-[var(--theme-surface)] px-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[var(--theme-fg)]",children:"Authorized users"}),e.jsx("p",{className:"text-[11px] text-[var(--theme-fg-muted)]",children:"Full workspace, thread, and VM control"})]}),e.jsx("button",{"aria-expanded":i,"aria-label":"Add authorized user",className:"relay-button-secondary inline-flex h-9 w-9 items-center justify-center p-0",disabled:m,onClick:()=>{c(I=>!I),v("")},type:"button",children:e.jsx(q.Plus,{className:"h-4 w-4"})})]}),i?e.jsxs("div",{className:"border-t border-[var(--theme-border)] p-3",children:[e.jsx("label",{className:"text-xs font-medium text-[var(--theme-fg-soft)]",htmlFor:`invite-user-${a.id}`,children:"Find an account"}),e.jsx("input",{autoFocus:!0,className:"relay-input mt-2 min-h-11 w-full",id:`invite-user-${a.id}`,onChange:I=>v(I.target.value),placeholder:"Account ID, username, or email",value:f}),M?e.jsx("div",{className:"mt-2 overflow-hidden rounded-md border border-[var(--theme-border)]",children:D.length?D.map(I=>e.jsxs("button",{className:"flex min-h-11 w-full items-center justify-between gap-3 border-b border-[var(--theme-border)] px-3 text-left last:border-b-0 hover:bg-[var(--theme-hover)]",disabled:m,onClick:()=>void s(`members:${a.id}`,async()=>{await kr(a.id,[...L,I.id]),c(!1),v("")}),type:"button",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium text-[var(--theme-fg)]",children:I.username}),e.jsxs("span",{className:"block truncate text-xs text-[var(--theme-fg-muted)]",children:[I.email," · ",I.id]})]}),e.jsx("span",{className:"text-xs font-medium text-[var(--theme-accent-strong)]",children:"Add"})]},I.id)):e.jsx("p",{className:"px-3 py-3 text-xs text-[var(--theme-fg-muted)]",children:"No unassigned account matches that search."})}):null]}):null,e.jsx("ul",{className:"divide-y divide-[var(--theme-border)] border-t border-[var(--theme-border)]",children:a.assignedUsers.map(I=>e.jsxs("li",{className:"flex min-h-12 items-center justify-between gap-3 px-3",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium text-[var(--theme-fg)]",children:I.username}),e.jsx("span",{className:"block truncate text-xs text-[var(--theme-fg-muted)]",children:I.email})]}),e.jsx("button",{"aria-label":`Remove ${I.username} access`,className:"min-h-9 rounded-md px-3 text-xs font-medium text-[var(--status-danger-fg)] hover:bg-[var(--status-danger-bg)]",disabled:m||L.length===1,onClick:()=>void s(`members:${a.id}`,()=>kr(a.id,L.filter(A=>A!==I.userId))),title:L.length===1?"A hosted VM must keep at least one authorized user.":void 0,type:"button",children:"Remove"})]},I.userId))})]})]}),e.jsxs("div",{className:"mt-4 rounded-md border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3 text-xs leading-5 text-[var(--theme-fg-muted)]",children:[e.jsx("span",{className:"font-medium text-[var(--theme-fg)]",children:"Snapshots"})," ","capture the VM disk as a local Incus restore point before risky changes. They are not off-host backups and are not restored automatically."]}),e.jsx(xd,{busy:m,onAction:s,sandbox:a})]})]})]}):null]})}function xd({busy:t,onAction:s,sandbox:a}){const[r,o]=n.useState(!1),[l,i]=n.useState(!1),[c,f]=n.useState(null),[v,b]=n.useState(""),[g,S]=n.useState("");async function y(){i(!0),f(null);try{const m=await ti(a.id);b(m.configToml),S(m.authJson)}catch(m){f(We(m))}finally{i(!1)}}return e.jsxs("details",{className:"mt-3",onToggle:m=>{const p=m.currentTarget.open;o(p),p&&!v&&!l&&a.status==="online"&&y()},children:[e.jsx("summary",{className:"cursor-pointer text-xs font-medium text-[var(--theme-fg-muted)] hover:text-[var(--theme-fg)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--theme-accent-ring)]",children:"Backend credentials"}),r?e.jsxs("div",{className:"mt-3 max-w-3xl overflow-hidden rounded-md border border-[var(--theme-border)]",children:[e.jsxs("div",{className:"grid gap-3 bg-[var(--theme-surface)] p-3 sm:grid-cols-[12rem_1fr] sm:items-end",children:[e.jsxs("label",{className:"text-xs font-medium text-[var(--theme-fg-soft)]",children:["Backend",e.jsxs("select",{className:"relay-input mt-2 min-h-11 w-full",onChange:()=>{},value:"codex",children:[e.jsx("option",{value:"codex",children:"Codex"}),e.jsx("option",{disabled:!0,children:"Claude Code (coming soon)"}),e.jsx("option",{disabled:!0,children:"OpenCode (coming soon)"})]})]}),e.jsx("p",{className:"text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Files are read from and written directly to this VM. The VM must be online."})]}),a.status!=="online"?e.jsx("p",{className:"border-t border-[var(--theme-border)] px-3 py-3 text-sm text-[var(--status-warning-fg)]",children:"Start the VM before editing backend files."}):l?e.jsx("p",{className:"border-t border-[var(--theme-border)] px-3 py-4 text-sm text-[var(--theme-fg-muted)]",children:"Loading Codex files from the VM…"}):e.jsxs("div",{className:"space-y-4 border-t border-[var(--theme-border)] p-3",children:[c?e.jsx("p",{className:"rounded-md border border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] px-3 py-2 text-sm text-[var(--status-danger-fg)]",children:c}):null,e.jsx(ds,{filename:"~/.codex/config.toml",language:"TOML",onChange:b,value:v}),e.jsx(ds,{filename:"~/.codex/auth.json",language:"JSON",onChange:S,value:g}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx("button",{className:"relay-button-secondary min-h-11",disabled:t||l,onClick:()=>void y(),type:"button",children:"Reload"}),e.jsx("button",{className:"relay-button-primary min-h-11",disabled:t||!v.trim()||!g.trim(),onClick:()=>void s(`backend:${a.id}`,()=>si(a.id,{configToml:v,authJson:g})),type:"button",children:"Save to VM"})]})]})]}):null]})}function ds({filename:t,language:s,onChange:a,value:r}){return e.jsxs("div",{children:[e.jsxs("div",{className:"flex min-h-9 items-center justify-between gap-3",children:[e.jsx("label",{className:"text-xs font-semibold text-[var(--theme-fg)]",htmlFor:t,children:t}),e.jsxs("label",{className:"relay-button-secondary inline-flex min-h-9 cursor-pointer items-center px-3 text-xs",children:["Upload ",s,e.jsx("input",{accept:s==="JSON"?".json,application/json":".toml,text/plain",className:"sr-only",onChange:o=>{var i;const l=(i=o.target.files)==null?void 0:i[0];l&&l.text().then(a),o.target.value=""},type:"file"})]})]}),e.jsx("textarea",{className:"relay-input mt-2 min-h-40 w-full resize-y font-mono text-xs leading-5",id:t,onChange:o=>a(o.target.value),spellCheck:!1,value:r})]})}function Rt({children:t,tone:s}){const a={success:"border-[var(--status-success-border)] bg-[var(--status-success-bg)] text-[var(--status-success-fg)]",warning:"border-[var(--status-warning-border)] bg-[var(--status-warning-bg)] text-[var(--status-warning-fg)]",danger:"border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] text-[var(--status-danger-fg)]",neutral:"border-[var(--theme-border)] bg-[var(--theme-surface)] text-[var(--theme-fg-muted)]"}[s];return e.jsx("span",{className:`rounded-full border px-2 py-0.5 text-xs font-medium ${a}`,children:t})}function gd(t){return t==="online"?"success":t==="error"?"danger":["creating","starting","provisioning","stopping","deleting"].includes(t)?"warning":"neutral"}function vd(t){return t.replace("_"," ").replace(/^./,s=>s.toUpperCase())}function bd(t){return t%1024===0?`${t/1024} GiB`:`${(t/1024).toFixed(1)} GiB`}function Zt({icon:t,label:s,value:a,detail:r}){return e.jsx("article",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-2 text-[var(--theme-accent-strong)]",children:t}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.14em] text-[var(--theme-fg-muted)]",children:s}),e.jsx("p",{className:"mt-1 text-2xl font-semibold text-[var(--theme-fg)]",children:a.toLocaleString()}),e.jsx("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:r})]})]})})}function yd({onLogout:t}){const[s,a]=n.useState(null),[r,o]=n.useState(!1);n.useEffect(()=>{let c=!1;return bn().then(f=>{c||a(f.authenticated?f:null)}).catch(()=>{c||a(null)}),()=>{c=!0}},[]);const l=(s==null?void 0:s.user)??null;if(!l)return null;async function i(){await Pl(),a(null),o(!1),t()}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":r,"aria-haspopup":"menu","aria-label":`Relay admin menu for ${l.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(c=>!c),type:"button",children:Dd(l.username)}),r?e.jsxs("div",{className:"absolute right-0 mt-2 w-64 overflow-hidden rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-1 shadow-[var(--theme-shadow)]",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:l.username}),e.jsx("p",{className:"truncate text-xs text-[var(--theme-fg-muted)]",children:l.email}),e.jsx("p",{className:"mt-1 text-[11px] uppercase tracking-[0.14em] text-[var(--theme-fg-muted)]",children:"Admin session"})]}),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 i(),role:"menuitem",type:"button",children:[e.jsx(q.LogOut,{className:"h-4 w-4"}),"Logout admin"]})]}):null]})}function wd({summary:t}){const s=[...t.users].sort(Ld("lastSeenAt")).slice(0,6),a=t.devices.filter(r=>r.connected);return e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_minmax(22rem,0.7fr)]",children:[e.jsx(dt,{title:"Recent users",detail:"Last authenticated relay activity.",children:e.jsx("div",{className:"divide-y divide-[var(--theme-border)]",children:s.map(r=>e.jsxs("div",{className:"flex items-center justify-between gap-3 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:r.username}),e.jsx("p",{className:"truncate text-xs text-[var(--theme-fg-muted)]",children:r.email})]}),e.jsxs("div",{className:"text-right text-xs text-[var(--theme-fg-muted)]",children:[e.jsx("p",{children:Fe(r.lastSeenAt)}),e.jsxs("p",{children:[r.conversationCount," conversations"]})]})]},r.id))})}),e.jsx(dt,{title:"Online devices",detail:"Devices with an active supervisor tunnel.",children:a.length?e.jsx("div",{className:"space-y-3",children:a.map(r=>e.jsx(Cd,{device:r},r.id))}):e.jsx(ps,{children:"No supervisors are connected."})})]})}function jd({busyKey:t,onDeleteUser:s,onResetPassword:a,onUpdateUser:r,users:o}){const[l,i]=n.useState(""),[c,f]=n.useState({key:"lastSeenAt",direction:"desc"}),[v,b]=n.useState(null),[g,S]=n.useState(null),y=n.useMemo(()=>{const p=Rr(l);return o.filter(L=>p?Rr(`${L.username} ${L.email}`).includes(p):!0).sort((L,M)=>Id(L,M,c))},[l,c,o]);function m(p){f(L=>({key:p,direction:L.key===p&&L.direction==="desc"?"asc":"desc"}))}return e.jsxs(e.Fragment,{children:[e.jsxs(dt,{title:"Users",detail:"Registered relay accounts. Admin accounts are excluded from workspace and device operations.",children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[e.jsxs("label",{className:"relative block min-w-0 flex-1",children:[e.jsx(q.Search,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--theme-fg-muted)]"}),e.jsx("input",{className:"relay-input w-full pl-9",onChange:p=>i(p.target.value),placeholder:"Search username or email",value:l})]}),e.jsxs("p",{className:"text-sm text-[var(--theme-fg-muted)]",children:[y.length.toLocaleString()," of"," ",o.length.toLocaleString()," users"]})]}),e.jsxs(oa,{minWidth:"68rem",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx(Tt,{active:c.key==="username",direction:c.direction,onClick:()=>m("username"),children:"User"}),e.jsx(Tt,{active:c.key==="enabled",direction:c.direction,onClick:()=>m("enabled"),children:"Status"}),e.jsx(Tt,{active:c.key==="lastSeenAt",direction:c.direction,onClick:()=>m("lastSeenAt"),children:"Last used"}),e.jsx(Tt,{active:c.key==="conversationCount",direction:c.direction,onClick:()=>m("conversationCount"),children:"Conversations"}),e.jsx(Tt,{active:c.key==="deviceCount",direction:c.direction,onClick:()=>m("deviceCount"),children:"Devices"}),e.jsx(Ae,{children:"Role"}),e.jsx(Ae,{children:"Actions"})]})}),e.jsx("tbody",{children:y.map(p=>e.jsxs("tr",{children:[e.jsxs(Se,{strong:!0,children:[p.username,e.jsx("div",{className:"text-xs font-normal text-[var(--theme-fg-muted)]",children:p.email})]}),e.jsx(Se,{children:e.jsx(On,{active:p.enabled,children:p.enabled?"Enabled":"Disabled"})}),e.jsx(Se,{children:Fe(p.lastSeenAt)}),e.jsx(Se,{children:p.conversationCount.toLocaleString()}),e.jsx(Se,{children:p.deviceCount.toLocaleString()}),e.jsx(Se,{children:p.role}),e.jsx(Se,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{className:"relay-button-secondary",disabled:t===p.id||p.role==="admin",onClick:()=>r(p.id,!p.enabled),type:"button",children:p.enabled?"Disable":"Enable"}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",disabled:t===`reset:${p.id}`||p.role==="admin",onClick:()=>b(p),type:"button",children:[e.jsx(q.KeyRound,{className:"h-4 w-4"}),"Reset"]}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2 text-[var(--status-danger-fg)]",disabled:t===`delete:${p.id}`||p.role==="admin",onClick:()=>S(p),type:"button",children:[e.jsx(q.Trash2,{className:"h-4 w-4"}),"Delete"]})]})})]},p.id))})]}),y.length?null:e.jsx(ps,{children:"No users match the current search."})]}),v?e.jsx(Td,{busy:t===`reset:${v.id}`,onClose:()=>b(null),onSubmit:async p=>{await a(v.id,p),b(null)},user:v}):null,g?e.jsx(Ed,{busy:t===`delete:${g.id}`,confirmLabel:"Delete user",description:`Delete ${g.username}, their devices, shares, and access history. This cannot be undone.`,onClose:()=>S(null),onConfirm:async()=>{await s(g.id),S(null)},title:"Delete relay user"}):null]})}function Nd({devices:t,users:s}){const[a,r]=n.useState("all"),[o,l]=n.useState("all"),[i,c]=n.useState("all"),[f,v]=n.useState("lastActivity"),[b,g]=n.useState("desc"),S=n.useMemo(()=>s.filter(m=>t.some(p=>p.ownerUserId===m.id)),[t,s]),y=n.useMemo(()=>t.filter(m=>a==="all"||m.ownerUserId===a).filter(m=>o==="all"||(o==="online"?m.connected:!m.connected)).filter(m=>i==="all"||Ad(us(m),i)).sort((m,p)=>Rd(m,p,f,b)),[i,t,b,a,f,o]);return e.jsxs(dt,{title:"Devices",detail:"Supervisor devices grouped by owner, connection state, activity, and loaded workspace metadata.",children:[e.jsxs("div",{className:"mb-4 grid gap-3 md:grid-cols-2 xl:grid-cols-5",children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Owner",e.jsxs("select",{className:"relay-input mt-2 w-full",onChange:m=>r(m.target.value),value:a,children:[e.jsx("option",{value:"all",children:"All users"}),S.map(m=>e.jsx("option",{value:m.id,children:m.username},m.id))]})]}),e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Status",e.jsxs("select",{className:"relay-input mt-2 w-full",onChange:m=>l(m.target.value),value:o,children:[e.jsx("option",{value:"all",children:"All devices"}),e.jsx("option",{value:"online",children:"Online"}),e.jsx("option",{value:"offline",children:"Offline"})]})]}),e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Last activity",e.jsxs("select",{className:"relay-input mt-2 w-full",onChange:m=>c(m.target.value),value:i,children:[e.jsx("option",{value:"all",children:"Any time"}),e.jsx("option",{value:"24h",children:"Last 24 hours"}),e.jsx("option",{value:"7d",children:"Last 7 days"}),e.jsx("option",{value:"30d",children:"Last 30 days"})]})]}),e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Sort by",e.jsxs("select",{className:"relay-input mt-2 w-full",onChange:m=>v(m.target.value),value:f,children:[e.jsx("option",{value:"lastActivity",children:"Last activity"}),e.jsx("option",{value:"name",children:"Device name"}),e.jsx("option",{value:"ownerUsername",children:"Owner"}),e.jsx("option",{value:"connected",children:"Connection"}),e.jsx("option",{value:"createdAt",children:"Created"}),e.jsx("option",{value:"workspaceCount",children:"Workspaces"}),e.jsx("option",{value:"threadCount",children:"Threads"})]})]}),e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Direction",e.jsxs("select",{className:"relay-input mt-2 w-full",onChange:m=>g(m.target.value),value:b,children:[e.jsx("option",{value:"desc",children:"Descending"}),e.jsx("option",{value:"asc",children:"Ascending"})]})]})]}),e.jsxs(oa,{minWidth:"74rem",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx(Ae,{children:"Device"}),e.jsx(Ae,{children:"Owner"}),e.jsx(Ae,{children:"Status"}),e.jsx(Ae,{children:"Last activity"}),e.jsx(Ae,{children:"Inventory"}),e.jsx(Ae,{children:"Network"})]})}),e.jsx("tbody",{children:y.map(m=>{var p,L;return e.jsxs("tr",{children:[e.jsxs(Se,{strong:!0,children:[m.name,e.jsx("div",{className:"text-xs font-normal text-[var(--theme-fg-muted)]",children:m.tokenPreview})]}),e.jsxs(Se,{children:[e.jsx("span",{className:"font-medium text-[var(--theme-fg-soft)]",children:m.ownerUsername}),e.jsx("div",{className:"text-xs text-[var(--theme-fg-muted)]",children:m.ownerEmail})]}),e.jsx(Se,{children:e.jsx(On,{active:m.connected,children:m.connected?"Online":"Offline"})}),e.jsxs(Se,{children:[Fe(us(m)),e.jsxs("div",{className:"text-xs text-[var(--theme-fg-muted)]",children:["created ",Fe(m.createdAt)]})]}),e.jsxs(Se,{children:[e.jsxs("span",{children:[m.workspaces.length.toLocaleString()," workspaces"]}),e.jsx("span",{className:"mx-2 text-[var(--theme-fg-muted)]",children:"·"}),e.jsxs("span",{children:[m.threads.length.toLocaleString()," threads"]}),e.jsx("div",{className:"mt-1 truncate text-xs text-[var(--theme-fg-muted)]",children:((p=m.workspaces[0])==null?void 0:p.label)??"No workspace metadata"}),e.jsx("div",{className:"truncate text-xs text-[var(--theme-fg-muted)]",children:((L=m.threads[0])==null?void 0:L.title)??"No thread metadata"})]}),e.jsxs(Se,{children:[m.ipAddress??"IP unavailable",e.jsxs("div",{className:"text-xs text-[var(--theme-fg-muted)]",children:["heartbeat ",Fe(m.lastHeartbeatAt)]})]})]},m.id)})})]}),y.length?null:e.jsx(ps,{children:"No devices match the selected filters."})]})}function kd({shares:t}){return e.jsx(dt,{title:"Share relationships",detail:"Thread grants between relay users. Revoked grants remain visible for audit.",children:e.jsxs(oa,{minWidth:"62rem",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx(Ae,{children:"Owner"}),e.jsx(Ae,{children:"Target"}),e.jsx(Ae,{children:"Thread"}),e.jsx(Ae,{children:"Device"}),e.jsx(Ae,{children:"Permissions"}),e.jsx(Ae,{children:"Last access"}),e.jsx(Ae,{children:"Status"})]})}),e.jsx("tbody",{children:t.map(s=>e.jsxs("tr",{children:[e.jsx(Se,{strong:!0,children:s.ownerUsername}),e.jsx(Se,{children:s.targetUsername}),e.jsxs(Se,{children:[e.jsx("span",{className:"font-medium text-[var(--theme-fg)]",children:s.threadTitle??s.label??"Thread unavailable"}),e.jsx("div",{className:"text-xs text-[var(--theme-fg-muted)]",children:s.workspaceLabel??"Workspace unavailable"})]}),e.jsx(Se,{children:s.deviceName}),e.jsxs(Se,{children:[s.threadAccess," /"," ",Od(s.workspaceAccess)]}),e.jsx(Se,{children:Fe(s.lastAccessedAt)}),e.jsx(Se,{children:s.revokedAt?"Revoked":s.expiresAt&&s.expiresAt<=new Date().toISOString()?"Expired":"Active"})]},s.id))})]})})}function Sd({busy:t,draft:s,onChange:a,onReviewRegistration:r,onSave:o,pending:l,reviewBusyKey:i}){return e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[e.jsx(dt,{title:"Registration settings",detail:"Stored in the relay database. Environment password seeds this once if empty.",children:e.jsxs("form",{className:"space-y-4",onSubmit:o,children:[e.jsx(Et,{checked:s.enabled,label:"Open registration",onChange:c=>a({...s,enabled:c})}),e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Registration password",e.jsx("input",{className:"relay-input mt-2 w-full",onChange:c=>a({...s,registrationPassword:c.target.value}),placeholder:"Leave empty for no invite password",value:s.registrationPassword??""})]}),e.jsx(Et,{checked:s.approvalRequired,label:"Require admin approval",onChange:c=>a({...s,approvalRequired:c})}),e.jsxs("div",{className:"space-y-3 border-t border-[var(--theme-border)] pt-4",children:[e.jsx(Et,{checked:s.googleAuthEnabled,disabled:!s.googleAuthAvailable,label:"Enable Google authentication",onChange:c=>a({...s,googleAuthEnabled:c})}),e.jsx(Et,{checked:s.githubAuthEnabled,disabled:!s.githubAuthAvailable,label:"Enable GitHub authentication",onChange:c=>a({...s,githubAuthEnabled:c})}),e.jsx(Et,{checked:s.emailVerificationEnabled,disabled:!s.emailVerificationAvailable,label:"Enable email verification",onChange:c=>a({...s,emailVerificationEnabled:c})}),s.emailVerificationAvailable?null:e.jsx("p",{className:"text-xs text-[var(--theme-fg-muted)]",children:"Configure the email provider and verification secret to enable this option."})]}),e.jsxs("button",{className:"relay-button-primary inline-flex items-center gap-2",disabled:t,type:"submit",children:[e.jsx(q.Settings,{className:"h-4 w-4"}),"Save settings"]})]})}),e.jsx(dt,{title:"Pending registrations",detail:"Approve creates the user. Reject keeps an audit trail.",children:l.length?e.jsx("div",{className:"divide-y divide-[var(--theme-border)]",children:l.map(c=>e.jsxs("div",{className:"flex flex-col gap-3 py-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:c.username}),e.jsxs("p",{className:"truncate text-xs text-[var(--theme-fg-muted)]",children:[c.email," · ",Fe(c.createdAt)]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("button",{className:"relay-button-primary inline-flex items-center gap-2",disabled:i===`approve:${c.id}`,onClick:()=>r(c.id,"approve"),type:"button",children:[e.jsx(q.Check,{className:"h-4 w-4"}),"Approve"]}),e.jsx("button",{className:"relay-button-secondary",disabled:i===`reject:${c.id}`,onClick:()=>r(c.id,"reject"),type:"button",children:"Reject"})]})]},c.id))}):e.jsx(ps,{children:"No pending applications."})})]})}function Cd({device:t}){return e.jsxs("div",{className:"grid gap-2 text-xs text-[var(--theme-fg-muted)] sm:grid-cols-2",children:[e.jsxs("p",{children:["Owner:"," ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children:t.ownerEmail})]}),e.jsxs("p",{children:["IP:"," ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children:t.ipAddress??"unavailable"})]}),e.jsxs("p",{children:["Connected:"," ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children:Fe(t.connectedAt)})]}),e.jsxs("p",{children:["Heartbeat:"," ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children:Fe(t.lastHeartbeatAt)})]})]})}function dt({aside:t,children:s,detail:a,title:r}){return e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4 flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:r}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:a})]}),t]}),s]})}function oa({children:t,minWidth:s}){return e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:"w-full border-collapse text-left text-sm",style:{minWidth:s},children:t})})}function Ae({children:t}){return e.jsx("th",{className:"border-b border-[var(--theme-border)] py-2 pr-3 text-xs font-semibold uppercase tracking-[0.14em] text-[var(--theme-fg-muted)]",children:t})}function Tt({active:t,children:s,direction:a,onClick:r}){const o=t?a==="asc"?q.ArrowUp:q.ArrowDown:q.ArrowUpDown;return e.jsx("th",{className:"border-b border-[var(--theme-border)] py-2 pr-3 text-left text-xs font-semibold uppercase tracking-[0.14em] text-[var(--theme-fg-muted)]",children:e.jsxs("button",{className:`inline-flex items-center gap-1.5 rounded-md px-1.5 py-1 transition hover:bg-[var(--theme-hover)] hover:text-[var(--theme-fg)] ${t?"text-[var(--theme-fg)]":""}`,onClick:r,type:"button",children:[s,e.jsx(o,{className:"h-3.5 w-3.5"})]})})}function Se({children:t,strong:s=!1}){return e.jsx("td",{className:`border-b border-[var(--theme-border)] py-3 pr-3 ${s?"font-medium text-[var(--theme-fg)]":"text-[var(--theme-fg-muted)]"}`,children:t})}function Et({checked:t,disabled:s=!1,label:a,onChange:r}){return e.jsxs("label",{className:`flex items-center gap-3 text-sm ${s?"text-[var(--theme-fg-muted)] opacity-60":"text-[var(--theme-fg-soft)]"}`,children:[e.jsx("input",{checked:t,disabled:s,className:"h-4 w-4 accent-[var(--theme-accent)]",onChange:o=>r(o.target.checked),type:"checkbox"}),a]})}function On({active:t,children:s}){return e.jsx("span",{className:`rounded-full border px-2 py-0.5 text-xs ${t?"border-[var(--status-success-border)] bg-[var(--status-success-bg)] text-[var(--status-success-fg)]":"border-[var(--theme-border)] bg-[var(--theme-surface)] text-[var(--theme-fg-muted)]"}`,children:s})}function ps({children:t}){return e.jsx("p",{className:"rounded-lg border border-dashed border-[var(--theme-border)] bg-[var(--theme-surface)] p-4 text-sm text-[var(--theme-fg-muted)]",children:t})}function Td({busy:t,onClose:s,onSubmit:a,user:r}){const[o,l]=n.useState(""),[i,c]=n.useState(null);async function f(v){if(v.preventDefault(),c(null),o.length<8){c("Password must be at least 8 characters.");return}await a(o)}return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-[color-mix(in_oklch,var(--app-bg)_82%,transparent)] px-4 py-8",children:e.jsxs("section",{className:"w-full max-w-md rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-2xl shadow-[color-mix(in_oklch,var(--app-fg)_18%,transparent)]",children:[e.jsx("h2",{className:"text-lg font-semibold text-[var(--theme-fg)]",children:"Reset password"}),e.jsxs("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:["Set a new relay password for ",r.username,"."]}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:f,children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["New password",e.jsx("input",{autoFocus:!0,className:"relay-input mt-2 w-full",onChange:v=>l(v.target.value),type:"password",value:o})]}),i?e.jsx("p",{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:i}):null,e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx("button",{className:"relay-button-secondary",onClick:s,type:"button",children:"Cancel"}),e.jsxs("button",{className:"relay-button-primary inline-flex items-center gap-2",disabled:t,type:"submit",children:[e.jsx(q.KeyRound,{className:"h-4 w-4"}),"Save password"]})]})]})]})})}function Ed({busy:t,confirmLabel:s,description:a,onClose:r,onConfirm:o,title:l}){return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-[color-mix(in_oklch,var(--app-bg)_82%,transparent)] px-4 py-8",children:e.jsxs("section",{className:"w-full max-w-md rounded-lg border border-[var(--status-danger-border)] bg-[var(--theme-panel)] p-5 shadow-2xl shadow-[color-mix(in_oklch,var(--app-fg)_18%,transparent)]",children:[e.jsx("h2",{className:"text-lg font-semibold text-[var(--theme-fg)]",children:l}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--theme-fg-muted)]",children:a}),e.jsxs("div",{className:"mt-5 flex justify-end gap-2",children:[e.jsx("button",{className:"relay-button-secondary",onClick:r,type:"button",children:"Cancel"}),e.jsxs("button",{className:"inline-flex h-10 items-center gap-2 rounded-md bg-[var(--action-danger-bg)] px-4 text-sm font-semibold text-[var(--action-danger-fg)] transition hover:bg-[var(--action-danger-bg-hover)] disabled:cursor-not-allowed disabled:opacity-60",disabled:t,onClick:o,type:"button",children:[e.jsx(q.Trash2,{className:"h-4 w-4"}),s]})]})]})})}function Rr(t){return t.trim().toLowerCase()}function Id(t,s,a){const r=a.direction==="asc"?1:-1;let o=0;return a.key==="username"?o=t.username.localeCompare(s.username):a.key==="enabled"?o=Number(t.enabled)-Number(s.enabled):a.key==="lastSeenAt"?o=cs(t.lastSeenAt,s.lastSeenAt):a.key==="conversationCount"?o=t.conversationCount-s.conversationCount:a.key==="deviceCount"?o=t.deviceCount-s.deviceCount:o=cs(t.createdAt,s.createdAt),o*r||t.username.localeCompare(s.username)}function Rd(t,s,a,r){const o=r==="asc"?1:-1;let l=0;return a==="name"?l=t.name.localeCompare(s.name):a==="ownerUsername"?l=t.ownerUsername.localeCompare(s.ownerUsername):a==="connected"?l=Number(t.connected)-Number(s.connected):a==="lastActivity"?l=cs(us(t),us(s)):a==="createdAt"?l=cs(t.createdAt,s.createdAt):a==="workspaceCount"?l=t.workspaces.length-s.workspaces.length:l=t.threads.length-s.threads.length,l*o||t.name.localeCompare(s.name)}function cs(t,s){const a=Date.parse(t??""),r=Date.parse(s??""),o=Number.isFinite(a)?a:-1/0,l=Number.isFinite(r)?r:-1/0;return o-l}function us(t){return t.lastHeartbeatAt??t.connectedAt??t.createdAt}function Ad(t,s){const a=Date.parse(t??"");if(!Number.isFinite(a))return!1;const r=s==="24h"?24:s==="7d"?168:720;return a>=Date.now()-r*60*60*1e3}function Ar(t,s){return t&&{...t,users:t.users.map(a=>a.id===s.id?{...a,...s}:a)}}function Pd(t){switch(t){case"overview":return"Overview";case"users":return"Users";case"devices":return"Devices";case"hosted":return"Hosted VMs";case"shares":return"Shares";case"settings":return"Settings"}}function Od(t){switch(t){case"write":return"workspace write";case"read":return"workspace read";case"none":default:return"no workspace"}}function Ld(t){return(s,a)=>Date.parse(a[t]??"")-Date.parse(s[t]??"")}function Fe(t){return t?new Date(t).toLocaleString():"never"}function Ud(t,s){const a=Date.parse(t);if(!Number.isFinite(a))return"unknown";const r=Math.max(0,Math.floor((s-a)/6e4)),o=Math.floor(r/1440),l=Math.floor(r%1440/60),i=r%60;return o>0?`${o}d ${l}h`:l>0?`${l}h ${i}m`:`${i}m`}function Dd(t){const s=(t==null?void 0:t.trim())??"";return s?Array.from(s).slice(0,2).join("").toUpperCase():"??"}function $d(t){const s=(t==null?void 0:t.trim())??"";return s?Array.from(s).slice(0,2).join("").toUpperCase():"??"}function la({className:t="",menuAlign:s="left"}){const a=Ze(),r=Lt(),[o,l]=n.useState(null),[i,c]=n.useState(!1),[f,v]=n.useState(!1);n.useEffect(()=>{if(!at())return;let m=!1;return bt().then(p=>{m||l(p.authenticated?p:null)}).catch(()=>{m||l(null)}),()=>{m=!0}},[r.pathname]),n.useEffect(()=>{c(!1),v(!1)},[r.pathname]);const b=(o==null?void 0:o.user)??null,g=n.useMemo(()=>$d(b==null?void 0:b.username),[b==null?void 0:b.username]),S=f&&typeof document<"u"?sn.createPortal(e.jsx("div",{"aria-modal":"true",className:"fixed inset-0 z-[1000] flex items-start justify-center overflow-y-auto bg-black/55 px-4 py-6 backdrop-blur-sm sm:py-10",role:"dialog",children:e.jsxs("section",{className:"w-full max-w-3xl rounded-xl border border-[var(--theme-border)] bg-[var(--theme-panel)] shadow-[var(--theme-shadow)]",children:[e.jsxs("header",{className:"flex items-start justify-between gap-4 border-b border-[var(--theme-border)] px-5 py-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Account"}),e.jsx("h2",{className:"mt-1 text-xl font-semibold text-[var(--theme-fg)]",children:"Account settings"})]}),e.jsx("button",{"aria-label":"Close account settings",className:"inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full border border-[var(--theme-border)] bg-[var(--theme-surface)] text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--theme-accent-ring)]",onClick:()=>v(!1),type:"button",children:e.jsx(q.X,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"max-h-[min(78vh,48rem)] overflow-y-auto p-5",children:e.jsx(Pn,{})})]})}),document.body):null;if(!at()||!b)return null;async function y(){await Ll(),l(null),a("/relay-portal")}return e.jsxs("div",{className:`relative z-50 inline-flex shrink-0 ${t}`.trim(),children:[e.jsx("button",{"aria-expanded":i,"aria-haspopup":"menu","aria-label":`Relay account menu for ${b.username}`,className:"inline-flex h-9 w-9 items-center justify-center rounded-full border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] text-sm font-semibold text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--theme-accent-ring)]",onClick:()=>c(m=>!m),type:"button",children:g}),i?e.jsxs("div",{className:`absolute mt-2 w-64 overflow-hidden rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-1 shadow-[var(--theme-shadow)] ${s==="right"?"right-0":"left-0"}`,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:b.username}),e.jsx("p",{className:"truncate text-xs text-[var(--theme-fg-muted)]",children:b.email})]}),e.jsxs("button",{className:"flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",onClick:()=>{c(!1),v(!0)},role:"menuitem",type:"button",children:[e.jsx(q.Settings,{className:"h-4 w-4"}),"Account settings"]}),e.jsxs(Ue,{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(q.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 y(),role:"menuitem",type:"button",children:[e.jsx(q.LogOut,{className:"h-4 w-4"}),"Logout"]})]}):null,S]})}const Md=3e3;function tt(t,s){return t instanceof ae?t.payload.message:t instanceof Error?t.message:s}function Hd(t,s){return t?{...s,sharedWithMe:Pr(t.sharedWithMe,s.sharedWithMe),sharedByMe:Pr(t.sharedByMe,s.sharedByMe),sharedDevicesWithMe:Ls(t.sharedDevicesWithMe??[],s.sharedDevicesWithMe??[]),sharedThreadsWithMe:Ls(t.sharedThreadsWithMe??[],s.sharedThreadsWithMe??[]),grantsByMe:Ls(t.grantsByMe??[],s.grantsByMe??[])}:_d(s)}function _d(t){return{...t,sharedWithMe:t.sharedWithMe.map(Xs),sharedByMe:t.sharedByMe.map(Xs),sharedDevicesWithMe:(t.sharedDevicesWithMe??[]).map(ns),sharedThreadsWithMe:(t.sharedThreadsWithMe??[]).map(ns),grantsByMe:(t.grantsByMe??[]).map(ns)}}function Pr(t,s){const a=new Map(t.map(r=>[r.id,r]));return s.map(r=>{const o=a.get(r.id);if(!o)return Xs(r);const l=ms(r),i=ms(o);return{...r,threadTitle:l??i,workspaceLabel:r.workspaceLabel??o.workspaceLabel}})}function Xs(t){return{...t,threadTitle:ms(t)}}function Ls(t,s){const a=new Map(t.map(r=>[r.id,r]));return s.map(r=>{var c;const o=a.get(r.id);if(!o)return ns(r);const l=Ot(r),i=Ot(o);return{...r,threadTitle:l??i,workspaceLabel:r.workspaceLabel??o.workspaceLabel,deviceName:((c=r.deviceName)==null?void 0:c.trim())||o.deviceName}})}function ns(t){return{...t,threadTitle:Ot(t)}}function Bd(){const t=Ze(),[s,a]=Qs(),[r,o]=n.useState(null),[l,i]=n.useState(""),[c,f]=n.useState(null),[v,b]=n.useState(null),[g,S]=n.useState(!0),[y,m]=n.useState(null),[p,L]=n.useState(null),[M,D]=n.useState(null),[I,A]=n.useState(null),[J,Y]=n.useState(null),[Z,d]=n.useState(null),[B,Q]=n.useState(null),[_,re]=n.useState(!1),oe=n.useRef(!1),ve=n.useRef(null),ce=n.useCallback(async u=>{const N=(u==null?void 0:u.showLoading)??!0,X=(u==null?void 0:u.clearError)??!0;N&&S(!0),X&&L(null);try{qe();const Ce=await yn();oe.current=!0,o(w=>Hd(w,Ce))}catch(Ce){(N||!oe.current)&&L(tt(Ce,"Unable to load devices."))}finally{N&&S(!1)}},[]);n.useEffect(()=>{ce();const u=window.setInterval(()=>{ce({showLoading:!1,clearError:!1})},Md);return()=>{window.clearInterval(u)}},[ce]),n.useEffect(()=>{const u=s.get("shareDevice");if(!u||!r||ve.current===u)return;const N=r.devices.find(Ce=>Ce.id===u);if(!N)return;ve.current=u,Q(N);const X=new URLSearchParams(s);X.delete("shareDevice"),a(X,{replace:!0})},[r,s,a]);async function Ne(u){u.preventDefault(),m("create"),L(null);try{const N=await Dl({name:l});f(N),i(""),re(!1),await ce({showLoading:!1})}catch(N){L(tt(N,"Unable to create device."))}finally{m(null)}}async function be(u){if(window.confirm(`Delete relay device "${u.name}"?`)){m(u.id),L(null);try{await $l(u.id),(c==null?void 0:c.device.id)===u.id&&f(null),await ce({showLoading:!1})}catch(N){L(tt(N,"Unable to delete device."))}finally{m(null)}}}function ke(u){ss(u.id),as(null),t(Vs(u.id))}function P(u){ss(u.deviceId),as(u.threadId),t(qs(u.threadId,u.deviceId))}function W(u){if(ss(u.deviceId),as(u.threadId),u.threadId){t(qs(u.threadId,u.deviceId));return}t(Vs(u.deviceId))}async function te(u,N){m(`grant:create:${u.id}`),L(null);try{await Wl({...N,deviceId:u.id,scope:"device",workspaceScope:"all",workspaceIds:[]}),Q(null),await ce({showLoading:!1})}catch(X){L(tt(X,"Unable to share device."))}finally{m(null)}}async function O(u,N){m(`grant:${u.id}`),L(null);try{await Fl(u.id,{...N,workspaceId:u.workspaceId,workspaceScope:u.workspaceScope,workspaceIds:u.workspaceIds}),d(null),await ce({showLoading:!1})}catch(X){L(tt(X,"Unable to update shared access."))}finally{m(null)}}async function K(u){if(window.confirm(`Remove sharing access for "${da(u)}"?`)){m(`grant:${u.id}`),L(null);try{await ql(u.id),A(N=>N===u.id?null:N),await ce({showLoading:!1})}catch(N){L(tt(N,"Unable to remove shared access."))}finally{m(null)}}}async function k(u,N){m(`share:${u.id}`),L(null);try{await Bl(u.id,{...N,workspaceId:u.workspaceId}),Y(null),await ce({showLoading:!1})}catch(X){L(tt(X,"Unable to update shared thread."))}finally{m(null)}}async function G(u){if(window.confirm(`Remove sharing access for "${ia(u)}"?`)){m(`share:${u.id}`),L(null);try{await wn(u.id),D(N=>N===u.id?null:N),await ce({showLoading:!1})}catch(N){L(tt(N,"Unable to remove shared thread access."))}finally{m(null)}}}async function ue(u){var X;const N=u.token;if(!N){L("This device token is not available. Create a new device token for devices created before token storage was enabled.");return}try{await((X=navigator.clipboard)==null?void 0:X.writeText(Ln(N))),b(u.id),window.setTimeout(()=>{b(Ce=>Ce===u.id?null:Ce)},1600)}catch{}}const ge=(r==null?void 0:r.sharedDevicesWithMe)??[],fe=(r==null?void 0:r.grantsByMe)??[];return e.jsxs("main",{className:"min-h-screen bg-[var(--app-bg)] px-4 pb-6 text-[var(--app-fg)] sm:px-6",children:[e.jsxs("div",{className:"mx-auto w-full max-w-[1600px] space-y-5",children:[e.jsx("header",{className:"host-topbar sticky top-[env(safe-area-inset-top)] z-30 -mx-4 border-b px-2.5 py-2 backdrop-blur sm:mx-0 sm:rounded-lg sm:border sm:px-4",children:e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 sm:gap-2",children:[e.jsx(la,{}),e.jsx(Ue,{className:"host-info-pill inline-flex h-8 shrink-0 items-center rounded-md border px-2.5 text-[11px] font-medium uppercase tracking-[0.14em] transition sm:px-3 sm:text-xs sm:tracking-[0.18em]",to:"/",children:"Relay home"}),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:"Relay portal"})})]})}),e.jsxs("section",{className:"border-b border-[var(--theme-border)] pb-4",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-1 text-2xl font-semibold text-[var(--theme-fg)]",children:"Devices and shared sessions"})]}),p?e.jsx(Jd,{tone:"danger",children:p}):null,c?e.jsx(Gd,{result:c}):null,e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(42rem,0.9fr)_minmax(0,1.1fr)]",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-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.jsxs("button",{className:"relay-button-secondary inline-flex h-9 shrink-0 items-center gap-2 px-3",onClick:()=>re(!0),type:"button",children:[e.jsx(q.Plus,{className:"h-4 w-4"}),"Add"]})]}),g?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..."}):r!=null&&r.devices.length?e.jsx("div",{className:"space-y-3",children:r.devices.map(u=>e.jsx(zd,{busy:y===u.id,copiedSetup:v===u.id,device:u,onConnect:()=>ke(u),onCopySetup:()=>void ue(u),onDelete:()=>void be(u),onShare:()=>Q(u),setupTokenAvailable:!!u.token},u.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."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Or,{count:(r==null?void 0:r.sharedWithMe.length)??0,emptyText:"No sessions have been shared with this account yet.",loading:g,loadingText:"Loading shared sessions...",shares:(r==null?void 0:r.sharedWithMe)??[],title:"Shared with me",subtitle:"Sessions another relay user has shared with this account.",renderShare:u=>e.jsx(Ur,{mode:"incoming",share:u,onOpen:()=>P(u)},u.id)}),e.jsx(Lr,{count:ge.length,emptyText:"No devices have been shared with this account yet.",grants:ge,loading:g,loadingText:"Loading shared devices...",title:"Shared devices",subtitle:"Devices another relay user has shared with this account.",renderGrant:u=>e.jsx(Dr,{grant:u,mode:"incoming",onOpen:()=>W(u)},u.id)}),e.jsx(Lr,{count:fe.length,emptyText:"No devices have been shared by this account yet.",grants:fe,loading:g,loadingText:"Loading shared devices...",title:"Shared devices by me",subtitle:"Devices this relay account has shared with other users.",renderGrant:u=>e.jsx(Dr,{busy:y===`grant:${u.id}`,expanded:I===u.id,grant:u,mode:"outgoing",onOpen:()=>W(u),onEdit:()=>d(u),onRevoke:()=>void K(u),onToggleAccess:()=>{A(N=>N===u.id?null:u.id)}},u.id)}),e.jsx(Or,{count:(r==null?void 0:r.sharedByMe.length)??0,emptyText:"No threads have been shared by this account yet.",loading:g,loadingText:"Loading shared threads...",shares:(r==null?void 0:r.sharedByMe)??[],title:"Shared threads by me",subtitle:"Threads this relay account has shared with other users.",renderShare:u=>e.jsx(Ur,{busy:y===`share:${u.id}`,expanded:M===u.id,mode:"outgoing",share:u,onOpen:()=>P(u),onEdit:()=>Y(u),onRevoke:()=>void G(u),onToggleAccess:()=>{D(N=>N===u.id?null:u.id)}},u.id)})]})]})]}),_?e.jsx(Wd,{busy:y==="create",deviceName:l,onChangeDeviceName:i,onClose:()=>re(!1),onSubmit:Ne}):null,J?e.jsx(Fd,{busy:y===`share:${J.id}`,share:J,onClose:()=>Y(null),onSave:u=>void k(J,u)}):null,Z?e.jsx(Vd,{busy:y===`grant:${Z.id}`,grant:Z,onClose:()=>d(null),onSave:u=>void O(Z,u)}):null,B?e.jsx(qd,{busy:y===`grant:create:${B.id}`,device:B,onClose:()=>Q(null),onShare:u=>void te(B,u)}):null]})}function Wd({busy:t,deviceName:s,onChangeDeviceName:a,onClose:r,onSubmit:o}){return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-[color-mix(in_oklch,var(--app-bg)_82%,transparent)] px-4 py-6",children:e.jsxs("form",{className:"w-full max-w-md rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-2xl",onSubmit:o,children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay device"}),e.jsx("h2",{className:"mt-1 text-lg 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.jsx("button",{"aria-label":"Close add device dialog",className:"inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] text-[var(--theme-fg-muted)] transition hover:bg-[var(--theme-hover)] hover:text-[var(--theme-fg)]",onClick:r,type:"button",children:e.jsx(q.X,{className:"h-4 w-4"})})]}),e.jsxs("label",{className:"mt-5 block text-sm text-[var(--theme-fg-soft)]",children:["Device name",e.jsx("input",{autoFocus:!0,className:"relay-input mt-2 w-full",onChange:l=>a(l.target.value),placeholder:"MacBook Pro",value:s})]}),e.jsxs("div",{className:"mt-5 flex justify-end gap-2",children:[e.jsx("button",{className:"relay-button-secondary",disabled:t,onClick:r,type:"button",children:"Cancel"}),e.jsxs("button",{className:"relay-button-primary inline-flex items-center gap-2",disabled:t||!s.trim(),type:"submit",children:[e.jsx(q.MonitorSmartphone,{className:"h-4 w-4"}),"Create device token"]})]})]})})}function Or({count:t,emptyText:s,loading:a,loadingText:r,renderShare:o,shares:l,subtitle:i,title:c}){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 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:c}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:i})]}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5 text-xs text-[var(--theme-fg-muted)]",children:t})]}),a?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:r}):l.length?e.jsx("div",{className:"grid gap-3",children:l.map(f=>o(f))}):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:s})]})}function Lr({count:t,emptyText:s,grants:a,loading:r,loadingText:o,renderGrant:l,subtitle:i,title:c}){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 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:c}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:i})]}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5 text-xs text-[var(--theme-fg-muted)]",children:t})]}),r?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:o}):a.length?e.jsx("div",{className:"grid gap-3",children:a.map(f=>l(f))}):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:s})]})}function Ur({busy:t=!1,expanded:s=!1,mode:a,onEdit:r,onRevoke:o,onToggleAccess:l,share:i,onOpen:c}){var y,m;const f=ia(i),v=f,b=((y=i.label)==null?void 0:y.trim())||null,g=((m=i.workspaceLabel)==null?void 0:m.trim())||"Workspace unavailable",S=i.lastAccessedAt?`${i.lastAccessedByUsername??"unknown"} at ${yt(i.lastAccessedAt)}`:"Not accessed yet";return e.jsxs("article",{className:"relative 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 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:f}),e.jsxs("div",{className:"mt-1 space-y-0.5 text-xs text-[var(--theme-fg-muted)]",children:[e.jsxs("p",{className:"truncate",children:["Workspace:"," ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children:g})]}),e.jsxs("p",{className:"truncate",children:["Thread:"," ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children:v})]}),b?e.jsxs("p",{className:"truncate",children:["Label:"," ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children:b})]}):null,e.jsx("p",{className:"truncate",children:a==="incoming"?`From ${i.ownerUsername}`:`To ${i.targetUsername}`}),e.jsxs("p",{className:"truncate",children:["Device: ",i.deviceName]})]}),a==="outgoing"?e.jsxs("p",{className:"mt-1 text-xs text-[var(--theme-fg-soft)]",children:["Last access: ",S]}):null,e.jsxs("p",{className:"mt-2 flex flex-wrap gap-1.5 text-[11px] text-[var(--theme-fg-muted)]",children:[e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5",children:i.threadAccess==="read"?"View only":"Collaborator"}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5",children:$n(i.workspaceAccess)})]})]}),a==="incoming"?e.jsx("button",{className:"relay-button-primary inline-flex items-center gap-2",onClick:c,type:"button",children:"Open"}):e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{className:"relay-button-primary inline-flex items-center gap-2",onClick:c,type:"button",children:"Open"}),e.jsx("button",{className:"relay-button-secondary inline-flex items-center gap-2",disabled:t,onClick:r,type:"button",children:"Permissions"}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:l,type:"button",children:["Access",e.jsx(q.ChevronDown,{className:`h-4 w-4 transition-transform ${s?"rotate-180":""}`})]}),e.jsx("button",{className:"relay-button-secondary inline-flex items-center gap-2 text-[var(--status-danger-fg)]",disabled:t,onClick:o,type:"button",children:"Revoke"})]})]}),a==="outgoing"&&s?e.jsx("div",{className:"absolute right-3 top-[calc(100%-0.5rem)] z-20 w-[min(24rem,calc(100vw-3rem))] rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-3 shadow-xl",children:i.accessEvents.length?e.jsx("ul",{className:"space-y-2 text-xs text-[var(--theme-fg-muted)]",children:i.accessEvents.map(p=>e.jsxs("li",{className:"flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate font-medium text-[var(--theme-fg)]",children:Mn(p.kind)}),e.jsx("span",{className:"block truncate",children:p.username})]}),e.jsx("span",{children:yt(p.accessedAt)})]},p.id))}):e.jsx("p",{className:"text-xs text-[var(--theme-fg-muted)]",children:"This shared thread has not been accessed yet."})}):null]})}function Dr({busy:t=!1,expanded:s=!1,grant:a,mode:r,onEdit:o,onOpen:l,onRevoke:i,onToggleAccess:c}){var m,p;const f=da(a),v=Zd(a),b=((m=a.workspaceLabel)==null?void 0:m.trim())||(a.scope==="device"?"All workspaces":"Workspace unavailable"),g=a.scope==="thread"?Ot(a)??"Thread unavailable":a.scope==="workspace"?"Workspace access":"Whole device",S=((p=a.label)==null?void 0:p.trim())||null,y=a.lastAccessedAt?`${a.lastAccessedByUsername??"unknown"} at ${yt(a.lastAccessedAt)}`:"Not accessed yet";return e.jsxs("article",{className:"relative 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 flex-1",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:f}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5 text-[11px] uppercase tracking-[0.12em] text-[var(--theme-fg-muted)]",children:v})]}),e.jsxs("div",{className:"mt-1 space-y-0.5 text-xs text-[var(--theme-fg-muted)]",children:[e.jsxs("p",{className:"truncate",children:["Workspace:"," ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children:b})]}),e.jsxs("p",{className:"truncate",children:[a.scope==="thread"?"Thread":"Access",":"," ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children:g})]}),S?e.jsxs("p",{className:"truncate",children:["Label:"," ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children:S})]}):null,e.jsx("p",{className:"truncate",children:r==="incoming"?`From ${a.ownerUsername}`:`To ${a.targetUsername}`}),e.jsxs("p",{className:"truncate",children:["Device: ",a.deviceName]})]}),r==="outgoing"?e.jsxs("p",{className:"mt-1 text-xs text-[var(--theme-fg-soft)]",children:["Last access: ",y]}):null,e.jsxs("p",{className:"mt-2 flex flex-wrap gap-1.5 text-[11px] text-[var(--theme-fg-muted)]",children:[e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5",children:a.threadAccess==="read"?"View only":"Collaborator"}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5",children:$n(a.workspaceAccess)}),a.canCreateThreads?e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5",children:"Can create threads"}):null]})]}),r==="incoming"?e.jsx("button",{className:"relay-button-primary inline-flex items-center gap-2",onClick:l,type:"button",children:"Open"}):e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{className:"relay-button-primary inline-flex items-center gap-2",onClick:l,type:"button",children:"Open"}),e.jsx("button",{className:"relay-button-secondary inline-flex items-center gap-2",disabled:t,onClick:o,type:"button",children:"Permissions"}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:c,type:"button",children:["Access",e.jsx(q.ChevronDown,{className:`h-4 w-4 transition-transform ${s?"rotate-180":""}`})]}),e.jsx("button",{className:"relay-button-secondary inline-flex items-center gap-2 text-[var(--status-danger-fg)]",disabled:t,onClick:i,type:"button",children:"Revoke"})]})]}),r==="outgoing"&&s?e.jsx("div",{className:"absolute right-3 top-[calc(100%-0.5rem)] z-20 w-[min(24rem,calc(100vw-3rem))] rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-3 shadow-xl",children:a.accessEvents.length?e.jsx("ul",{className:"space-y-2 text-xs text-[var(--theme-fg-muted)]",children:a.accessEvents.map(L=>e.jsxs("li",{className:"flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate font-medium text-[var(--theme-fg)]",children:Mn(L.kind)}),e.jsx("span",{className:"block truncate",children:L.username})]}),e.jsx("span",{children:yt(L.accessedAt)})]},L.id))}):e.jsx("p",{className:"text-xs text-[var(--theme-fg-muted)]",children:"This shared access has not been used yet."})}):null]})}function Fd({busy:t,onClose:s,onSave:a,share:r}){const[o,l]=n.useState(r.label??""),[i,c]=n.useState(r.threadAccess),[f,v]=n.useState(r.workspaceAccess),[b,g]=n.useState(Un(r.expiresAt)),S=!r.workspaceId;function y(m){m.preventDefault(),a({label:o.trim()||null,threadAccess:i,workspaceAccess:S?"none":f,expiresAt:Dn(b)})}return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-[color-mix(in_oklch,var(--app-bg)_82%,transparent)] px-4 py-6",children:e.jsxs("form",{className:"max-h-[min(42rem,calc(100vh-3rem))] w-full max-w-lg overflow-auto rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-2xl",onSubmit:y,children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Shared thread permissions"}),e.jsxs("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:[r.targetUsername," can access ",ia(r),"."]})]}),e.jsxs("div",{className:"mt-5 space-y-4",children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Label",e.jsx("input",{className:"relay-input mt-2 w-full",onChange:m=>l(m.target.value),placeholder:"Optional shared thread label",value:o})]}),e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Thread access",e.jsxs("select",{className:"relay-input mt-2 w-full",onChange:m=>c(m.target.value),value:i,children:[e.jsx("option",{value:"read",children:"View only"}),e.jsx("option",{value:"control",children:"Collaborator"})]})]}),e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Workspace access",e.jsxs("select",{className:"relay-input mt-2 w-full",disabled:S,onChange:m=>v(m.target.value),value:S?"none":f,children:[e.jsx("option",{value:"none",children:"No workspace"}),e.jsx("option",{value:"read",children:"Workspace read"}),e.jsx("option",{value:"write",children:"Workspace write"})]})]}),S?e.jsx("p",{className:"rounded-md border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-2 text-xs text-[var(--theme-fg-muted)]",children:"This share was created without a workspace scope, so only thread access can be changed."}):null,e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Expiration",e.jsx("input",{"aria-label":"Expiration",className:"relay-input mt-2 w-full",onChange:m=>g(m.target.value),type:"datetime-local",value:b}),e.jsx("span",{className:"mt-1 block text-xs text-[var(--theme-fg-muted)]",children:"Leave empty for no expiration."})]})]}),e.jsxs("div",{className:"mt-5 flex justify-end gap-2",children:[e.jsx("button",{className:"relay-button-secondary",disabled:t,onClick:s,type:"button",children:"Cancel"}),e.jsx("button",{className:"relay-button-primary",disabled:t,type:"submit",children:"Save permissions"})]})]})})}function qd({busy:t,device:s,onClose:a,onShare:r}){const[o,l]=n.useState(""),[i,c]=n.useState(""),[f,v]=n.useState("read"),[b,g]=n.useState("read"),[S,y]=n.useState(!1);function m(p){p.preventDefault(),r({targetIdentifier:o.trim(),label:i.trim()||null,threadAccess:f,workspaceAccess:b,canCreateThreads:S})}return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-[color-mix(in_oklch,var(--app-bg)_82%,transparent)] px-4 py-6",children:e.jsxs("form",{className:"max-h-[min(42rem,calc(100vh-3rem))] w-full max-w-lg overflow-auto rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-2xl",onSubmit:m,children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay device"}),e.jsxs("h2",{className:"mt-1 text-lg font-semibold text-[var(--theme-fg)]",children:["Share ",s.name]}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Give another relay account access to this device and its workspaces."})]}),e.jsx("button",{"aria-label":"Close share device dialog",className:"inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] text-[var(--theme-fg-muted)] transition hover:bg-[var(--theme-hover)] hover:text-[var(--theme-fg)]",onClick:a,type:"button",children:e.jsx(q.X,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-5 space-y-4",children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Relay account",e.jsx("input",{autoFocus:!0,className:"relay-input mt-2 w-full",onChange:p=>l(p.target.value),placeholder:"username or email",value:o})]}),e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Label",e.jsx("input",{className:"relay-input mt-2 w-full",onChange:p=>c(p.target.value),placeholder:"Optional note shown in Shared devices by me",value:i})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Thread access",e.jsxs("select",{className:"relay-input mt-2 w-full",onChange:p=>v(p.target.value),value:f,children:[e.jsx("option",{value:"read",children:"View only"}),e.jsx("option",{value:"control",children:"Collaborator"})]})]}),e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Workspace access",e.jsxs("select",{className:"relay-input mt-2 w-full",onChange:p=>g(p.target.value),value:b,children:[e.jsx("option",{value:"none",children:"No workspace"}),e.jsx("option",{value:"read",children:"Workspace read"}),e.jsx("option",{value:"write",children:"Workspace write"})]})]})]}),e.jsxs("label",{className:"flex items-center justify-between gap-3 rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-2 text-sm text-[var(--theme-fg-soft)]",children:["Can create new threads",e.jsx("input",{checked:S,className:"h-4 w-4 accent-[var(--theme-accent)]",onChange:p=>y(p.target.checked),type:"checkbox"})]})]}),e.jsxs("div",{className:"mt-5 flex justify-end gap-2",children:[e.jsx("button",{className:"relay-button-secondary",disabled:t,onClick:a,type:"button",children:"Cancel"}),e.jsxs("button",{className:"relay-button-primary inline-flex items-center gap-2",disabled:t||!o.trim(),type:"submit",children:[e.jsx(q.Share2,{className:"h-4 w-4"}),"Share device"]})]})]})})}function Vd({busy:t,grant:s,onClose:a,onSave:r}){const[o,l]=n.useState(s.label??""),[i,c]=n.useState(s.threadAccess),[f,v]=n.useState(s.workspaceAccess),[b,g]=n.useState(s.canCreateThreads),[S,y]=n.useState(Un(s.expiresAt)),m=s.scope!=="thread",p=s.scope==="thread"&&!s.workspaceId;function L(M){M.preventDefault(),r({label:o.trim()||null,threadAccess:i,workspaceAccess:p?"none":f,canCreateThreads:m?b:!1,expiresAt:Dn(S)})}return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-[color-mix(in_oklch,var(--app-bg)_82%,transparent)] px-4 py-6",children:e.jsxs("form",{className:"max-h-[min(42rem,calc(100vh-3rem))] w-full max-w-lg overflow-auto rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-2xl",onSubmit:L,children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Shared access permissions"}),e.jsxs("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:[s.targetUsername," can access ",da(s),"."]})]}),e.jsxs("div",{className:"mt-5 space-y-4",children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Label",e.jsx("input",{className:"relay-input mt-2 w-full",onChange:M=>l(M.target.value),placeholder:"Optional shared access label",value:o})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Thread access",e.jsxs("select",{className:"relay-input mt-2 w-full",onChange:M=>c(M.target.value),value:i,children:[e.jsx("option",{value:"read",children:"View only"}),e.jsx("option",{value:"control",children:"Collaborator"})]})]}),e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Workspace access",e.jsxs("select",{className:"relay-input mt-2 w-full",disabled:p,onChange:M=>v(M.target.value),value:p?"none":f,children:[e.jsx("option",{value:"none",children:"No workspace"}),e.jsx("option",{value:"read",children:"Workspace read"}),e.jsx("option",{value:"write",children:"Workspace write"})]})]})]}),m?e.jsxs("label",{className:"flex items-center justify-between gap-3 rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-2 text-sm text-[var(--theme-fg-soft)]",children:["Can create new threads",e.jsx("input",{checked:b,className:"h-4 w-4 accent-[var(--theme-accent)]",onChange:M=>g(M.target.checked),type:"checkbox"})]}):null,e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Expiration",e.jsx("input",{"aria-label":"Expiration",className:"relay-input mt-2 w-full",onChange:M=>y(M.target.value),type:"datetime-local",value:S}),e.jsx("span",{className:"mt-1 block text-xs text-[var(--theme-fg-muted)]",children:"Leave empty for no expiration."})]})]}),e.jsxs("div",{className:"mt-5 flex justify-end gap-2",children:[e.jsx("button",{className:"relay-button-secondary",disabled:t,onClick:a,type:"button",children:"Cancel"}),e.jsx("button",{className:"relay-button-primary",disabled:t,type:"submit",children:"Save permissions"})]})]})})}function zd({device:t,busy:s,copiedSetup:a,onConnect:r,onCopySetup:o,onDelete:l,onShare:i,setupTokenAvailable:c}){const f=t.hostedStatus??null,v=t.connected||f==="stopped",b=f?Yd(f):t.connected?"Online":"Offline";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 flex-1",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}),f?e.jsxs("span",{className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-2 py-0.5 text-[10px] font-medium text-[var(--theme-fg-muted)]",children:["Hosted · ",b]}):null]}),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:f==="stopped"?"Stopped. Connect to wake this VM.":f&&f!=="online"?`${b}. The hosted supervisor is not ready yet.`:t.connected?`Online since ${yt(t.connectedAt)}`:`Offline. Last heartbeat: ${yt(t.lastHeartbeatAt)}`})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-2 sm:flex-nowrap",children:[e.jsxs("button",{className:"relay-button-secondary inline-flex h-10 items-center gap-2 whitespace-nowrap",onClick:o,title:c?"Copy relay supervisor setup command":"Device token is not available. Create a new device token for devices created before token storage was enabled.",disabled:!c||!!f,type:"button",children:[e.jsx(q.Copy,{className:"h-4 w-4"}),a?"Copied":"Copy setup"]}),e.jsxs("button",{className:"relay-button-primary inline-flex h-10 items-center gap-2 whitespace-nowrap",disabled:!v,onClick:r,type:"button",children:[e.jsx(q.Plug,{className:"h-4 w-4"}),f==="stopped"?"Start & connect":"Connect"]}),e.jsxs("button",{className:"relay-button-secondary inline-flex h-10 items-center gap-2 whitespace-nowrap",onClick:i,type:"button",children:[e.jsx(q.Share2,{className:"h-4 w-4"}),"Share"]}),e.jsx("button",{"aria-label":`Delete ${t.name}`,className:"relay-button-secondary inline-flex h-10 w-10 items-center justify-center px-0",disabled:s||!!f,onClick:l,title:f?"Hosted VMs are managed by a relay admin.":`Delete ${t.name}`,type:"button",children:e.jsx(q.Trash2,{className:"h-4 w-4"})})]})]}),c?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 Gd({result:t}){const s=Ln(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($r,{label:"Device token",value:t.token}),e.jsx($r,{label:"Supervisor command",value:s})]})}function $r({label:t,value:s}){async function a(){var r;try{await((r=navigator.clipboard)==null?void 0:r.writeText(s))}catch{}}return e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.14em] text-[var(--theme-fg-muted)]",children:t}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-1 px-2 py-1 text-xs",onClick:()=>void a(),type:"button",children:[e.jsx(q.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 Jd({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 Ln(t){const s=Kd();return[`REMOTE_CODEX_RELAY_SERVER_URL=${Mr(s)} \\`,`REMOTE_CODEX_RELAY_AGENT_TOKEN=${Mr(t)} \\`,"REMOTE_CODEX_RELAY_SUPERVISOR_PORT=45679 \\","remote-codex relay-supervisor"].join(`
|
|
20
|
+
`)}function Mr(t){return/^[A-Za-z0-9_./:@%+=,~-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function Kd(){return typeof window>"u"?"wss://relay.example.com":window.location.origin.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://")}function yt(t){return t?new Date(t).toLocaleString():"never"}function Yd(t){return t.replace("_"," ").replace(/^./,s=>s.toUpperCase())}function Un(t){if(!t)return"";const s=new Date(t);if(Number.isNaN(s.getTime()))return"";const a=r=>String(r).padStart(2,"0");return[s.getFullYear(),"-",a(s.getMonth()+1),"-",a(s.getDate()),"T",a(s.getHours()),":",a(s.getMinutes())].join("")}function Dn(t){const s=t.trim();if(!s)return null;const a=new Date(s);return Number.isNaN(a.getTime())?null:a.toISOString()}function ia(t){return ms(t)??"Thread unavailable"}function ms(t){var r,o;const s=(r=t.threadTitle)==null?void 0:r.trim();if(!s)return null;const a=(o=t.label)==null?void 0:o.trim();return a&&s===a?null:s}function da(t){var s,a,r;return t.scope==="device"?((s=t.deviceName)==null?void 0:s.trim())||"Shared device":t.scope==="workspace"?((a=t.workspaceLabel)==null?void 0:a.trim())||((r=t.deviceName)==null?void 0:r.trim())||"Shared workspace":Ot(t)??"Thread unavailable"}function Ot(t){var r,o,l;if(t.scope!=="thread")return((r=t.threadTitle)==null?void 0:r.trim())||null;const s=(o=t.threadTitle)==null?void 0:o.trim();if(!s)return null;const a=(l=t.label)==null?void 0:l.trim();return a&&s===a?null:s}function Zd(t){switch(t.scope){case"device":return"Device";case"workspace":return"Workspace";case"thread":default:return"Thread"}}function $n(t){switch(t){case"write":return"Workspace write";case"read":return"Workspace read";case"none":default:return"No workspace"}}function Mn(t){switch(t){case"open_device":return"Opened device";case"open_thread":return"Opened thread";case"create_thread":return"Created thread";case"send_prompt":return"Sent prompt";case"read_workspace_file":return"Read workspace";case"write_workspace_file":return"Wrote workspace";case"access":default:return"Access"}}const Xd=["REMOTE_CODEX_RELAY_SERVER_URL=wss://remote-codex.example.com \\","REMOTE_CODEX_RELAY_AGENT_TOKEN=rcd_... \\","REMOTE_CODEX_RELAY_SUPERVISOR_PORT=45679 \\","remote-codex relay-supervisor"].join(`
|
|
21
|
+
`);function Qd(){return n.useEffect(()=>{qe()},[]),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("article",{className:"mx-auto w-full max-w-5xl space-y-6",children:[e.jsxs("header",{className:"border-b border-[var(--theme-border)] pb-5",children:[e.jsxs(Ue,{className:"relay-button-secondary mb-5 inline-flex items-center gap-2",to:"/",children:[e.jsx(q.ArrowLeft,{className:"h-4 w-4"}),"Back"]}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Setup guide"}),e.jsx("h1",{className:"mt-2 text-3xl font-semibold tracking-normal text-[var(--theme-fg)]",children:"Remote Codex connection modes and relay setup"}),e.jsx("p",{className:"mt-3 max-w-3xl text-sm leading-6 text-[var(--theme-fg-soft)]",children:"Choose the connection mode first, then follow the relay flow when you need public web or mobile access to a private supervisor machine."})]}),e.jsxs("section",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(Us,{title:"Local mode",detail:"Use this on the same machine, emulator, LAN, or Tailscale network. It is simplest and has no relay account."}),e.jsx(Us,{title:"Server mode",detail:"Use this when you directly expose a supervisor with its own server login. Good for a trusted private server."}),e.jsx(Us,{title:"Relay mode",detail:"Use this when the backend machine should not accept inbound connections. The supervisor connects out to the relay."})]}),e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsx("h2",{className:"text-lg font-semibold text-[var(--theme-fg)]",children:"Relay setup flow"}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsx(pt,{icon:e.jsx(q.KeyRound,{className:"h-4 w-4"}),title:"1. Register or sign in",detail:"Open the relay home page, click Sign in, then create or enter your relay account."}),e.jsx(pt,{icon:e.jsx(q.MonitorSmartphone,{className:"h-4 w-4"}),title:"2. Create a device",detail:"Go to Devices, choose a readable device name, and create a one-time token for that private supervisor."}),e.jsx(pt,{icon:e.jsx(q.Copy,{className:"h-4 w-4"}),title:"3. Copy the setup command",detail:"Use Copy setup. The command includes the relay URL, device token, and a less common supervisor port."}),e.jsx(pt,{icon:e.jsx(q.Play,{className:"h-4 w-4"}),title:"4. Start supervisor on the private machine",detail:"Run the copied command in the workspace host terminal. If tmux is installed, remote-codex keeps it detached by default."}),e.jsx(pt,{icon:e.jsx(q.RadioTower,{className:"h-4 w-4"}),title:"5. Connect and work",detail:"Return to Devices, wait for Online, then Connect. Workspaces and threads are scoped through that selected device."}),e.jsx(pt,{icon:e.jsx(q.Share2,{className:"h-4 w-4"}),title:"6. Share a thread when needed",detail:"Inside a thread, open the export/share panel, enter another relay username, and choose thread plus workspace permissions."})]})]}),e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(18rem,0.8fr)]",children:[e.jsxs("div",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsx("h2",{className:"text-lg font-semibold text-[var(--theme-fg)]",children:"Example supervisor command"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"The real command is generated by the relay portal. Keep the token private."}),e.jsx("pre",{className:"mt-4 overflow-x-auto rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] p-3 text-xs leading-5 text-[var(--theme-fg)]",children:e.jsx("code",{children:Xd})})]}),e.jsxs("div",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsx("h2",{className:"text-lg font-semibold text-[var(--theme-fg)]",children:"After setup"}),e.jsxs("ul",{className:"mt-3 space-y-3 text-sm leading-6 text-[var(--theme-fg-muted)]",children:[e.jsxs("li",{className:"flex gap-2",children:[e.jsx(q.CheckCircle2,{className:"mt-1 h-4 w-4 shrink-0 text-[var(--theme-accent-strong)]"}),"Use Devices to switch backend machines."]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(q.CheckCircle2,{className:"mt-1 h-4 w-4 shrink-0 text-[var(--theme-accent-strong)]"}),"Use Shared with me to open sessions others shared."]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(q.CheckCircle2,{className:"mt-1 h-4 w-4 shrink-0 text-[var(--theme-accent-strong)]"}),"Use Shared by me to review access history, edit permissions, or revoke access."]})]})]})]})]})})}function Us({detail:t,title:s}){return e.jsxs("article",{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:s}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--theme-fg-muted)]",children:t})]})}function pt({detail:t,icon:s,title:a}){return e.jsxs("div",{className:"grid gap-3 rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3 sm:grid-cols-[2rem_minmax(0,1fr)]",children:[e.jsx("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] text-[var(--theme-accent-strong)]",children:s}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-[var(--theme-fg)]",children:a}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-[var(--theme-fg-muted)]",children:t})]})]})}function ec(){const[t,s]=n.useState(null),[a,r]=n.useState(!0);n.useEffect(()=>{let l=!1;return qe(),bt().then(i=>{l||s(i)}).catch(()=>{l||s(null)}).finally(()=>{l||r(!1)}),()=>{l=!0}},[]);const o=(t==null?void 0:t.authenticated)===!0;return e.jsx("main",{className:"min-h-screen bg-[var(--app-bg)] px-4 py-6 text-[var(--app-fg)] sm:px-6",children:e.jsxs("div",{className:"mx-auto flex w-full max-w-6xl flex-col gap-5",children:[e.jsxs("header",{className:"flex items-center justify-between gap-4 border-b border-[var(--theme-border)] pb-5",children:[e.jsxs(Ue,{to:"/",className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] text-sm font-semibold text-[var(--theme-fg)]",children:"RC"}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-semibold text-[var(--theme-fg)]",children:"Remote Codex Relay"}),e.jsx("span",{className:"block text-xs text-[var(--theme-fg-muted)]",children:"Private supervisor access"})]})]}),e.jsxs("nav",{className:"flex shrink-0 items-center gap-2",children:[e.jsxs(Ue,{className:"relay-button-secondary inline-flex items-center gap-2",to:"/relay-guide",children:[e.jsx(q.BookOpen,{className:"h-4 w-4"}),"Guide"]}),e.jsxs(Ue,{className:"relay-button-primary inline-flex items-center gap-2",to:o?"/relay-devices":"/relay-portal",children:[a?"Checking...":o?"Open devices":"Sign in",e.jsx(q.ArrowRight,{className:"h-4 w-4"})]})]})]}),e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[minmax(0,1.05fr)_minmax(20rem,0.95fr)]",children:[e.jsxs("div",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4 shadow-[var(--theme-shadow)] sm:p-5",children:[e.jsxs("div",{className:"flex flex-col gap-5 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay console"}),e.jsx("h1",{className:"mt-2 max-w-2xl text-2xl font-semibold tracking-normal text-[var(--theme-fg)] sm:text-3xl",children:"Connect a private Codex supervisor."}),e.jsx("p",{className:"mt-3 max-w-2xl text-sm leading-6 text-[var(--theme-fg-soft)]",children:"Register a device, keep the supervisor connected over an outbound tunnel, then open workspaces through web or mobile clients."})]}),e.jsxs("span",{className:`inline-flex shrink-0 items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-medium ${o?"border-[var(--status-success-border)] bg-[var(--status-success-bg)] text-[var(--status-success-fg)]":"border-[var(--theme-border-strong)] bg-[var(--theme-muted)] text-[var(--theme-fg-soft)]"}`,children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current"}),a?"Checking session":o?"Signed in":"Signed out"]})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap gap-2",children:[e.jsxs(Ue,{className:"relay-button-primary inline-flex h-11 items-center gap-2 px-4",to:o?"/relay-devices":"/relay-portal",children:[o?"Open devices":"Sign in",e.jsx(q.ArrowRight,{className:"h-4 w-4"})]}),e.jsx(Ue,{className:"relay-button-secondary inline-flex h-11 items-center gap-2 px-4",to:"/relay-guide",children:"Setup guide"})]}),e.jsxs("div",{className:"mt-5 grid gap-2 sm:grid-cols-3",children:[e.jsx(Ms,{label:"Mode",value:"Relay"}),e.jsx(Ms,{label:"Client",value:"Web, Android, iOS"}),e.jsx(Ms,{label:"Tunnel",value:"Supervisor outbound"})]})]}),e.jsxs("div",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4 shadow-[var(--theme-shadow)]",children:[e.jsxs("div",{className:"mb-4 flex items-center gap-3",children:[e.jsx("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] text-[var(--theme-fg)]",children:e.jsx(q.RadioTower,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-semibold text-[var(--theme-fg)]",children:"Connection path"}),e.jsx("p",{className:"text-xs text-[var(--theme-fg-muted)]",children:"Everything starts from a selected device."})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx(Ds,{icon:e.jsx(q.MonitorSmartphone,{className:"h-4 w-4"}),title:"Create a device token",detail:"Register each workstation once from the relay portal."}),e.jsx(Ds,{icon:e.jsx(q.Workflow,{className:"h-4 w-4"}),title:"Start relay-supervisor",detail:"The private machine keeps an outbound WebSocket open."}),e.jsx(Ds,{icon:e.jsx(q.ShieldCheck,{className:"h-4 w-4"}),title:"Open workspaces",detail:"Web, Android, and iOS connect through the selected device."})]})]})]}),e.jsxs("section",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx($s,{title:"Local stays local",detail:"Workspace files and agent execution remain on the supervisor device."}),e.jsx($s,{title:"Shared sessions",detail:"Share a thread as view-only or collaborator access, with workspace permissions."}),e.jsx($s,{title:"Mobile first",detail:"Resume threads, monitor long turns, and open shared sessions from Android or iOS."})]})]})})}function Ds({detail:t,icon:s,title:a}){return e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3",children:[e.jsx("span",{className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-[var(--theme-border-strong)] bg-[var(--theme-surface-strong)] text-[var(--theme-fg-soft)]",children:s}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold text-[var(--theme-fg)]",children:a}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:t})]})]})}function $s({detail:t,title:s}){return e.jsxs("article",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-4",children:[e.jsx(q.CheckCircle2,{className:"h-4 w-4 text-[var(--status-success-fg)]"}),e.jsx("h2",{className:"mt-3 text-base font-semibold text-[var(--theme-fg)]",children:s}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-[var(--theme-fg-muted)]",children:t})]})}function Ms({label:t,value:s}){return e.jsxs("div",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-2",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--theme-fg-muted)]",children:t}),e.jsx("p",{className:"mt-1 truncate text-sm font-medium text-[var(--theme-fg-soft)]",children:s})]})}function Hn(t,s){return t instanceof ae?t.payload.message:t instanceof Error?t.message:s}function tc(){const t=Ze(),s=Lt(),[a,r]=n.useState(null),[o,l]=n.useState(!0),[i,c]=n.useState(null);async function f(){var b;l(!0),c(null);try{qe();const g=await bt();if(r(g),g.authenticated){if(((b=g.user)==null?void 0:b.role)==="admin"){t("/relay-admin",{replace:!0});return}t("/relay-devices",{replace:!0});return}}catch(g){c(Hn(g,"Unable to load relay portal."))}finally{l(!1)}}n.useEffect(()=>{f()},[]);async function v(){var g;if(qe(),((g=(await bt()).user)==null?void 0:g.role)==="admin"){t("/relay-admin",{replace:!0});return}t("/relay-devices",{replace:!0})}return o?e.jsx(Hs,{children:"Checking relay session..."}):a!=null&&a.authenticated?e.jsx(Hs,{children:"Opening relay devices..."}):e.jsx(Hs,{children:e.jsx(sc,{registrationEnabled:(a==null?void 0:a.registrationEnabled)??!0,settings:a==null?void 0:a.registrationSettings,oauthNotice:new URLSearchParams(s.search).has("oauthPending")?"OAuth registration received. An admin must approve it before you can sign in.":null,oauthError:new URLSearchParams(s.search).get("oauthError"),initialError:i,onAuthenticated:v})})}function sc({registrationEnabled:t,settings:s,oauthNotice:a,oauthError:r,initialError:o,onAuthenticated:l}){const[i,c]=n.useState("login"),[f,v]=n.useState(""),[b,g]=n.useState(""),[S,y]=n.useState(""),[m,p]=n.useState(""),[L,M]=n.useState(""),[D,I]=n.useState(o??r),[A,J]=n.useState(a),[Y,Z]=n.useState(!1);async function d(B){B.preventDefault(),Z(!0),I(null),J(null);try{if(i==="login")await Rl({identifier:f,password:m});else{if(m.length<8){I("Password must be at least 8 characters.");return}if(S.trim().length<3){I("Username must be at least 3 characters.");return}if((await Ol({email:b,username:S,password:m,registrationPassword:L})).pendingApproval){J("Registration request sent. An admin must approve it before you can sign in."),c("login");return}}await l()}catch(Q){I(Hn(Q,"Unable to authenticate with relay."))}finally{Z(!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-[var(--theme-shadow)]",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:i==="login"?"Sign in":"Create account"}),s!=null&&s.googleAuthEnabled||s!=null&&s.githubAuthEnabled?e.jsxs("div",{className:"mt-5 grid gap-2",children:[s.googleAuthEnabled?e.jsx("a",{className:"relay-button-secondary flex h-11 items-center justify-center",href:"/relay/auth/oauth/google/start",children:"Continue with Google"}):null,s.githubAuthEnabled?e.jsx("a",{className:"relay-button-secondary flex h-11 items-center justify-center",href:"/relay/auth/oauth/github/start",children:"Continue with GitHub"}):null,e.jsxs("div",{className:"flex items-center gap-3 py-1 text-xs text-[var(--theme-fg-muted)]",children:[e.jsx("span",{className:"h-px flex-1 bg-[var(--theme-border)]"}),e.jsx("span",{children:"or use password"}),e.jsx("span",{className:"h-px flex-1 bg-[var(--theme-border)]"})]})]}):null,e.jsxs("form",{className:"mt-4 space-y-4",onSubmit:d,children:[i==="login"?e.jsx(It,{autoComplete:"username",label:"Email or username",onChange:v,value:f}):e.jsxs(e.Fragment,{children:[e.jsx(It,{autoComplete:"email",label:"Email",onChange:g,required:!0,type:"email",value:b}),e.jsx(It,{autoComplete:"username",label:"Username",minLength:3,onChange:y,required:!0,value:S}),e.jsx(It,{autoComplete:"one-time-code",label:"Registration password",onChange:M,required:!0,type:"password",value:L})]}),e.jsx(It,{autoComplete:i==="login"?"current-password":"new-password",label:"Password",onChange:p,required:!0,type:"password",value:m,...i==="register"?{description:"Use at least 8 characters.",minLength:8}:{}}),D?e.jsx(Hr,{tone:"danger",children:D}):null,A?e.jsx(Hr,{tone:"accent",children:A}):null,e.jsx("button",{className:"relay-button-primary h-11 w-full",disabled:Y,type:"submit",children:Y?"Working...":i==="login"?"Sign in":"Register"})]}),e.jsx("button",{className:"mt-4 text-sm text-[var(--theme-accent-strong)] disabled:text-[var(--theme-fg-muted)]",disabled:i==="login"?!t:!1,onClick:()=>c(i==="login"?"register":"login"),type:"button",children:i==="login"?t?"Create relay account":"Registration is disabled":"Use an existing account"})]})}function Hs({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(la,{}),e.jsx("div",{className:"flex min-h-[calc(100vh-3rem)] items-center justify-center",children:t})]})}function It({label:t,value:s,onChange:a,type:r="text",autoComplete:o,description:l,minLength:i,required:c=!1}){return e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:[t,e.jsx("input",{autoComplete:o,className:"relay-input mt-2 w-full",minLength:i,onChange:f=>a(f.target.value),required:c,type:r,value:s}),l?e.jsx("span",{className:"mt-1.5 block text-xs text-[var(--theme-fg-muted)]",children:l}):null]})}function Hr({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 ac(t,s){const a=new Set(s.map(r=>r.id));return[...s,...t.filter(r=>!a.has(r.id))]}function Je(t,s){const a=new Set(s.map(o=>o.id)),r=s.filter(o=>o.items.some(l=>l.kind==="userMessage"));return[...t.filter(o=>{var c;if(a.has(o.id))return!1;if(o.status!=="inProgress")return!0;const l=(c=o.items.find(f=>f.kind==="userMessage"))==null?void 0:c.text.trim(),i=o.startedAt?Date.parse(o.startedAt):Number.NaN;return!l||!Number.isFinite(i)?!0:!r.some(f=>{var g;const v=(g=f.items.find(S=>S.kind==="userMessage"))==null?void 0:g.text.trim(),b=f.startedAt?Date.parse(f.startedAt):Number.NaN;return v===l&&Number.isFinite(b)&&Math.abs(b-i)<=15e3})}),...s]}function rc(t,s){return!s||s.items.length===0?t:t.map(a=>{if(a.id!==s.turnId)return a;const r=s.items.filter(f=>f.kind==="agentMessage"&&f.createdAt);if(r.length===0)return a;const o=new Map(r.map(f=>[f.id,f])),l=new Set;let i=!1;const c=a.items.map(f=>{if(f.kind!=="agentMessage"||f.createdAt&&f.createdAt!==a.startedAt)return f;let v=o.get(f.id);return v||(v=r.find(b=>!l.has(b.id)&&b.text.trim().length>=8&&f.text.trim().includes(b.text.trim()))),!(v!=null&&v.createdAt)||v.createdAt===a.startedAt?f:(l.add(v.id),i=!0,{...f,createdAt:v.createdAt})});return i?{...a,items:c}:a})}function nc(t,s){return{...t,pendingRequests:[...t.pendingRequests.filter(a=>a.id!==s.id),s]}}function oc(t,s){const a=t.pendingRequests.filter(r=>r.id!==s);return a.length===t.pendingRequests.length?t:{...t,pendingRequests:a}}function _r(t,s,a){const r=s.filter(c=>!a.has(c.id)),o=t.filter(c=>!a.has(c.id));if(o.length===0)return r;const l=new Map(r.map(c=>[c.id,c]));return[...o.map(c=>l.get(c.id)??c),...r.filter(c=>!o.some(f=>f.id===c.id))].sort((c,f)=>c.createdAt.localeCompare(f.createdAt))}function lc(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 _n(t,s){var l,i;if(!t||t.kind!==s.kind)return s;const a=c=>{let f=c;const v=typeof s.sequence=="number"&&Number.isFinite(s.sequence)?s.sequence:typeof t.sequence=="number"&&Number.isFinite(t.sequence)?t.sequence:null;v!==null&&f.sequence!==v&&(f={...f,sequence:v});const b=typeof s.transcriptOrder=="number"&&Number.isFinite(s.transcriptOrder)?s.transcriptOrder:typeof t.transcriptOrder=="number"&&Number.isFinite(t.transcriptOrder)?t.transcriptOrder:null;return b!==null&&f.transcriptOrder!==b&&(f={...f,transcriptOrder:b}),f};if(t.kind==="agentMessage"&&s.kind==="agentMessage")return a(t.text.length>s.text.length?{...s,text:t.text,sequence:s.sequence??t.sequence??null}:s);const r=((l=t.detailText)==null?void 0:l.trim())||t.text.trim(),o=((i=s.detailText)==null?void 0:i.trim())||s.text.trim();return a(r.length>o.length?t:s)}function ic(t,s,a){if(!t||s&&s.turnId!==t.turnId)return s;const r=a.find(g=>g.id===t.turnId),o=new Map((r==null?void 0:r.items.map(g=>[g.id,g]))??[]),l=(r==null?void 0:r.items.filter(g=>g.kind==="agentMessage").map(g=>g.text.trim()).filter(Boolean))??[],i=g=>g.kind==="agentMessage"&&g.text.trim().length>0&&l.some(S=>S.includes(g.text.trim()));if(!s){const g=t.items.filter(S=>{const y=o.get(S.id);return y?y.kind!==S.kind||typeof S.sequence=="number"&&Number.isFinite(S.sequence)&&y.sequence!==S.sequence:!i(S)});return g.length===0?null:{...t,items:g}}const c=new Map(t.items.map(g=>[g.id,g])),f=new Map(s.items.map(g=>[g.id,g])),b=[...t.items.map(g=>g.id),...s.items.map(g=>g.id).filter(g=>!c.has(g))].map(g=>{const S=f.get(g),y=c.get(g);if(!S){const m=o.get(g);return!m&&y&&i(y)||m&&m.kind===(y==null?void 0:y.kind)&&!(y&&typeof y.sequence=="number"&&Number.isFinite(y.sequence)&&m.sequence!==y.sequence)?null:y??null}return _n(y,S)}).filter(g=>!!g);return b.length===0?null:{turnId:s.turnId,items:b,updatedAt:s.updatedAt.localeCompare(t.updatedAt)>=0?s.updatedAt:t.updatedAt}}function At(t,s){const a=t.filter(r=>r.id!==s.id);return[s,...a]}function dc(t){return`${t.threadId}:${t.objective}:${t.createdAt}`}function cc(t,s){const a=Date.parse(t.updatedAt)||0,o=(Date.parse(s.updatedAt)||0)>=a?s:t,l=o===s?t:s;return{...o,localGoalId:o.localGoalId??l.localGoalId??null}}function Bn(t){const s=new Map;for(const a of t){const r=dc(a),o=s.get(r);s.set(r,o?cc(o,a):a)}return[...s.values()].sort((a,r)=>Date.parse(r.updatedAt)-Date.parse(a.updatedAt))}function hs(t,s){return Bn([s,...t])}function _s(t,s){if(!s)return null;const a=t.find(r=>r.model===s);return a?a.supportedReasoningEfforts.length>1:null}function uc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`client-${Date.now()}-${Math.random().toString(16).slice(2,10)}`}function ca(t,s){return(t==null?void 0:t.items.some(a=>a.kind==="userMessage"&&a.text.trim()===s.trim()))??!1}const mc=/\s*\[(?:PHOTO\s+[^\]]+|localImage)\]\s*/g;function ua(t){return/\[(?:PHOTO\s+[^\]]+|localImage)\]/.test(t)}function Br(t){return t.replace(mc," ").replace(/\s+/g," ").trim()}function Wn(t,s){const a=Br(s);return a?(t==null?void 0:t.items.some(r=>r.kind==="userMessage"&&Br(r.text)===a))??!1:!1}function Fn(t){return(t==null?void 0:t.items.some(s=>s.kind==="userMessage"&&/\[(?:PHOTO\s+\.\/\.temp\/threads\/[^\]]+|localImage)\]/.test(s.text)))??!1}function hc(t,s){return t.find(a=>ca(a,s))??(ua(s)?t.find(a=>Wn(a,s))??null:null)}function fc(t,s){return t.find(a=>(s.serverTurnId!==null&&a.id===s.serverTurnId||a.id===s.id)&&a.items.some(o=>o.kind==="userMessage")?!0:ca(a,s.prompt)||ua(s.prompt)&&(Wn(a,s.prompt)||Fn(a)))??null}function pc(t,s,a,r){let o=!1;const l=t.map(i=>i.id!==s?i:(o=!0,{...i,tokenUsage:a,priceEstimate:r}));return o?l:t}function xc({activeView:t,composerHostRef:s,threadId:a}){const[r,o]=n.useState(!1),[l,i]=n.useState(0),[c,f]=n.useState(0),[v,b]=n.useState(0),[g,S]=n.useState(!1);n.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const D=window.matchMedia("(max-width: 639px)"),I=()=>o(D.matches);return I(),D.addEventListener("change",I),()=>{D.removeEventListener("change",I)}},[]),n.useEffect(()=>{var I,A;if(typeof window>"u")return;const D=()=>{const J=window.visualViewport,Y=J?Math.max(0,Math.round(window.innerHeight-J.height-J.offsetTop)):0;b(Y),document.documentElement.style.setProperty("--thread-detail-keyboard-inset",`${Y}px`)};return D(),(I=window.visualViewport)==null||I.addEventListener("resize",D),(A=window.visualViewport)==null||A.addEventListener("scroll",D),window.addEventListener("resize",D),()=>{var J,Y;(J=window.visualViewport)==null||J.removeEventListener("resize",D),(Y=window.visualViewport)==null||Y.removeEventListener("scroll",D),window.removeEventListener("resize",D),document.documentElement.style.removeProperty("--thread-detail-keyboard-inset")}},[]),n.useEffect(()=>{if(typeof document>"u")return;const D=()=>{const I=document.activeElement,A=s.current,J=A==null?void 0:A.querySelector('[aria-label="Prompt"]');S(!!(I&&J&&(I===J||J.contains(I))))};return D(),document.addEventListener("focusin",D),document.addEventListener("focusout",D),()=>{document.removeEventListener("focusin",D),document.removeEventListener("focusout",D)}},[t,s,r,a]),n.useEffect(()=>{const D=s.current;if(!D||typeof ResizeObserver>"u")return;const I=D.querySelector("form")??D,A=()=>{i(Math.max(D.getBoundingClientRect().height,I.getBoundingClientRect().height))};A();const J=new ResizeObserver(()=>{A()});return J.observe(I),()=>{J.disconnect()}},[t,s,r]),n.useEffect(()=>{var J,Y;const D=s.current;if(!D||!r||t!=="chat"){f(0);return}const I=()=>{const Z=D.getBoundingClientRect();f(Math.max(0,Math.ceil(window.innerHeight-Z.top)))};I(),window.addEventListener("resize",I),(J=window.visualViewport)==null||J.addEventListener("resize",I),(Y=window.visualViewport)==null||Y.addEventListener("scroll",I);let A=null;return typeof ResizeObserver<"u"&&(A=new ResizeObserver(I),A.observe(D)),()=>{var Z,d;window.removeEventListener("resize",I),(Z=window.visualViewport)==null||Z.removeEventListener("resize",I),(d=window.visualViewport)==null||d.removeEventListener("scroll",I),A==null||A.disconnect()}},[t,s,r,v,g,a]);const y=r&&t==="chat",m=y&&g?v:0,p=Math.max(l,144),L=Math.max(c,p+m),M=y?L+12:0;return{floatingMobileComposerBottomOffset:m,timelineBottomSpacer:M,useFloatingMobileComposer:y}}const He=()=>({status:"idle",data:null,error:null});function gc({detailRef:t,id:s,navigate:a,setDetail:r,setError:o,setThreads:l}){const[i,c]=n.useState(He),[f,v]=n.useState(He),[b,g]=n.useState(He),[S,y]=n.useState(He),[m,p]=n.useState(He),[L,M]=n.useState(!1),[D,I]=n.useState(!1),[A,J]=n.useState(()=>new Set),[Y,Z]=n.useState(!1),[d,B]=n.useState(!1),[Q,_]=n.useState(He);n.useEffect(()=>{c(He),v(He),g(He),y(He),p(He),M(!1),J(new Set),Z(!1),_(He)},[s]);const re=n.useCallback(async()=>{if(s){_(u=>({status:"loading",data:u.data,error:null}));try{const u=await Ai(s);_({status:"ready",data:u,error:null})}catch(u){const N=u instanceof ae?u.payload.message:"Unable to load export turns.";_(X=>({status:"failed",data:X.data,error:N}))}}},[s]);async function oe(u){if(s){o(null),B(!0);try{const{blob:N,filename:X}=await Oi(s,u),Ce=URL.createObjectURL(N),w=document.createElement("a");w.href=Ce,w.download=X,document.body.append(w),w.click(),w.remove(),window.setTimeout(()=>URL.revokeObjectURL(Ce),3e4),Z(!1)}catch(N){const X=N instanceof ae?N.payload.message:"Unable to export transcript.";o(X)}finally{B(!1)}}}async function ve(){if(s){p(u=>{var N;return{status:"loading",data:u.data??((N=t.current)==null?void 0:N.goal)??null,error:null}});try{const u=await zi(s);p({status:"ready",data:u.goal,error:null}),r(N=>N&&(u.goal?{...N,goal:u.goal,goalHistory:hs(N.goalHistory??[],u.goal)}:{...N,goal:u.goal}))}catch(u){p(N=>({status:"failed",data:N.data,error:u instanceof ae?u.payload.message:"Unable to load goal."}))}}}async function ce(u){if(s){p(N=>{var X;return{status:"loading",data:N.data??((X=t.current)==null?void 0:X.goal)??null,error:null}});try{const N=await Gi(s,u);p({status:"ready",data:N.goal,error:null}),r(X=>X&&(N.goal?{...X,goal:N.goal,goalHistory:hs(X.goalHistory??[],N.goal)}:{...X,goal:N.goal}))}catch(N){throw p(X=>({status:"failed",data:X.data,error:N instanceof ae?N.payload.message:"Unable to update goal."})),N}}}async function Ne(){if(s){p(u=>{var N;return{status:"loading",data:u.data??((N=t.current)==null?void 0:N.goal)??null,error:null}});try{const u=await Ji(s);p({status:"ready",data:null,error:null}),r(N=>N&&(u.goalHistory?{...N,goal:null,goalHistory:u.goalHistory}:{...N,goal:null}))}catch(u){throw p(N=>({status:"failed",data:N.data,error:u instanceof ae?u.payload.message:"Unable to clear goal."})),u}}}async function be(u){I(!0);try{await ce({status:u})}finally{I(!1)}}async function ke(){I(!0);try{await Ne()}finally{I(!1)}}async function P(){if(s){c(u=>({status:"loading",data:u.data,error:null}));try{const u=await Yi(s);c({status:"ready",data:u,error:null})}catch(u){c(N=>({status:"failed",data:N.data,error:u instanceof ae?u.payload.message:"Unable to load skills."}))}}}async function W(){if(s){v(u=>({status:"loading",data:u.data,error:null}));try{const u=await Zi(s);v({status:"ready",data:u,error:null})}catch(u){v(N=>({status:"failed",data:N.data,error:u instanceof ae?u.payload.message:"Unable to load MCP servers."}))}}}async function te(){if(s){g(u=>({status:"loading",data:u.data,error:null}));try{const u=await Xi(s);g({status:"ready",data:u,error:null})}catch(u){g(N=>({status:"failed",data:N.data,error:u instanceof ae?u.payload.message:"Unable to load hooks."}))}}}async function O(u){if(s){g(N=>({status:"loading",data:N.data,error:null}));try{const N=await Qi(s,u);g({status:"ready",data:N,error:null})}catch(N){throw g(X=>({status:"failed",data:X.data,error:N instanceof ae?N.payload.message:"Unable to create hook."})),N}}}async function K(u){if(s){g(N=>({status:"loading",data:N.data,error:null}));try{const N=await ed(s,u);g({status:"ready",data:N,error:null})}catch(N){throw g(X=>({status:"failed",data:X.data,error:N instanceof ae?N.payload.message:"Unable to update hook."})),N}}}async function k(u){if(s){g(N=>({status:"loading",data:N.data,error:null}));try{const N=await td(s,u);g({status:"ready",data:N,error:null})}catch(N){throw g(X=>({status:"failed",data:X.data,error:N instanceof ae?N.payload.message:"Unable to trust hook."})),N}}}async function G(u){if(s){g(N=>({status:"loading",data:N.data,error:null}));try{const N=await sd(s,u);g({status:"ready",data:N,error:null})}catch(N){throw g(X=>({status:"failed",data:X.data,error:N instanceof ae?N.payload.message:"Unable to untrust hook."})),N}}}async function ue(){if(s){y(u=>({status:"loading",data:u.data,error:null}));try{const u=await Ki(s);y({status:"ready",data:u,error:null})}catch(u){y(N=>({status:"failed",data:N.data,error:u instanceof ae?u.payload.message:"Unable to load turns for forking."}))}}}async function ge(){if(!s)return;const u=await Er(s,{mode:"latest"});l(N=>At(N,u.thread.thread)),a($e(u.thread.thread.id))}async function fe(u){if(!s)return;const N=await Er(s,{mode:"turn",turnId:u});l(X=>At(X,N.thread.thread)),a($e(N.thread.thread.id))}return{expandedGoalIds:A,exportBusy:d,exportDialogOpen:Y,exportTurnsState:Q,forkTurnOptionsState:S,goalActionBusy:D,goalMonitorOpen:L,goalState:m,handleCreateHook:O,handleExportTranscript:oe,handleForkLatest:ge,handleForkTurn:fe,handleGoalStatusAction:be,handleOpenForkTurns:ue,handleOpenGoal:ve,handleOpenHooks:te,handleOpenMcp:W,handleOpenSkills:P,handleTerminateGoal:ke,handleTrustHook:k,handleUntrustHook:G,handleUpdateGoal:ce,handleUpdateHook:K,hooksState:b,loadExportTurns:re,mcpState:f,setExpandedGoalIds:J,setExportDialogOpen:Z,setGoalMonitorOpen:M,setGoalState:p,skillsState:i}}const vc=5e3;function Wr(t){return JSON.stringify(t)}function bc(t,s){return Wr(t)===Wr(s)}function yc(t,s){const a=new Map(t.map(l=>[l.id,l]));let r=t.length!==s.length;const o=s.map((l,i)=>{var f;const c=a.get(l.id);return c&&bc(c,l)?(((f=t[i])==null?void 0:f.id)!==l.id&&(r=!0),c):(r=!0,l)});return r?o:t}function qn(t){const{enabled:s,setThreads:a,intervalMs:r=vc}=t,o=n.useRef(!1),l=n.useCallback(async()=>{if(!(!s||o.current)&&!(typeof document<"u"&&document.visibilityState==="hidden")){o.current=!0;try{const i=await ra();a(c=>yc(c,i))}catch{}finally{o.current=!1}}},[s,a]);n.useEffect(()=>{if(!s||typeof window>"u")return;const i=window.setInterval(()=>{l()},r),c=()=>{document.visibilityState==="visible"&&l()};return document.addEventListener("visibilitychange",c),()=>{window.clearInterval(i),document.removeEventListener("visibilitychange",c)}},[s,r,l])}function wc({setError:t,workspaceId:s,access:a="write"}){return n.useMemo(()=>!s||a==="none"?null:{listTree:r=>bi(s,{path:r.path??""}),readFile:r=>yi(s,{path:r.path,...r.offset!==void 0?{offset:r.offset}:{},...r.limit!==void 0?{limit:r.limit}:{}}),getRawFileUrl:r=>wi(s,{path:r.path}),...a==="write"?{uploadFile:r=>ki(s,{file:r.file}),writeFile:async r=>{await Si(s,{path:r.path,content:r.content})}}:{},downloadNode:async r=>{t(null);try{const o=await Ni(s,{path:r.path}),l=URL.createObjectURL(o.blob),i=document.createElement("a");i.href=l,i.download=o.filename,document.body.append(i),i.click(),i.remove(),URL.revokeObjectURL(l)}catch(o){t(o instanceof ae?o.payload.message:o instanceof Error?o.message:"Workspace download failed.")}}},[a,t,s])}function st(t){return t.enabled&&t.capabilities.sessions.resume&&t.capabilities.turns.start}function Fr(t,s){var r;const a=t.find(o=>o.provider===s);return a&&st(a)?a.provider:((r=t.find(st))==null?void 0:r.provider)??Ke}function ma({initialWorkspaceId:t,initialTitle:s="",onCreated:a,onCancel:r,variant:o="panel"}){const l=Ut(),i=n.useId(),[c,f]=n.useState([]),[v,b]=n.useState([]),[g,S]=n.useState([]),[y,m]=n.useState((l==null?void 0:l.defaultBackend)??Ke),[p,L]=n.useState(""),[M,D]=n.useState(""),[I,A]=n.useState(()=>s??""),[J,Y]=n.useState("yolo"),[Z,d]=n.useState(!0),[B,Q]=n.useState(!1),[_,re]=n.useState(null),[oe,ve]=n.useState(null),ce=(l==null?void 0:l.defaultBackend)??Ke,Ne=v.find(k=>k.provider===y),be=o==="dialog",ke=be?"host-form-control mt-1.5 h-10 w-full rounded-lg border px-3 text-sm outline-none transition":"host-form-control mt-2 w-full rounded-lg border px-4 py-3 outline-none transition",P=be?"host-secondary-button rounded-lg border px-3 py-2 text-sm font-medium transition disabled:cursor-not-allowed disabled:opacity-60":"host-secondary-button rounded-lg border px-5 py-3 font-medium transition disabled:cursor-not-allowed disabled:opacity-60",W=be?"ui-action-primary rounded-lg px-4 py-2.5 text-sm font-medium transition disabled:cursor-not-allowed":"ui-action-primary rounded-lg px-5 py-3 font-medium transition disabled:cursor-not-allowed";n.useEffect(()=>{A(s??"")},[s]),n.useEffect(()=>{let k=!1;return Promise.all([aa(),is()]).then(async([G,ue])=>{var X,Ce,w;if(k)return;const ge=Fr(ue,ce);m(ge),b(ue);const fe=await rs(ge);if(k)return;f(G),S(fe);const u=t??null,N=G.some(E=>E.id===u)?u:((X=G[0])==null?void 0:X.id)??"";L(N),D(((Ce=fe.find(E=>E.isDefault))==null?void 0:Ce.model)??((w=fe[0])==null?void 0:w.model)??"")}).catch(G=>{k||ve(G instanceof Error?G.message:"Unable to load creation form data.")}).finally(()=>{k||d(!1)}),()=>{k=!0}},[ce,t]),n.useEffect(()=>{if(!y)return;let k=!1;return S([]),D(""),ve(null),rs(y).then(G=>{var ue,ge;k||(S(G),D(((ue=G.find(fe=>fe.isDefault))==null?void 0:ue.model)??((ge=G[0])==null?void 0:ge.model)??""))}).catch(G=>{k||(S([]),D(""),ve(G instanceof Error?G.message:"Unable to load backend models."))}),()=>{k=!0}},[y]);async function te(k=y){var u,N;const G=await is();b(G);const ue=G.find(X=>X.provider===k),ge=ue&&st(ue)?k:Fr(G,ce);m(ge);const fe=await rs(ge);S(fe),D(((u=fe.find(X=>X.isDefault))==null?void 0:u.model)??((N=fe[0])==null?void 0:N.model)??"")}async function O(k){const G=k.installation.installed?"update":"install";re(k.provider),ve(null);try{await kn(k.provider,G),await te(k.provider)}catch(ue){ue instanceof ae?ve(ue.payload.message):ve(ue instanceof Error?ue.message:`Unable to ${G} ${k.displayName}.`);try{await te(y)}catch{}}finally{re(null)}}async function K(k){k.preventDefault(),Q(!0),ve(null);try{const G=await Ui(I.trim()?{workspaceId:p,provider:y,model:M,approvalMode:J,title:I.trim()}:{workspaceId:p,provider:y,model:M,approvalMode:J});a(G)}catch(G){G instanceof ae?ve(G.payload.message):ve(G instanceof Error?G.message:"Unable to create thread.")}finally{Q(!1)}}return Z?e.jsx("div",{className:"host-empty-state rounded-lg border px-6 py-12 text-center",children:"Loading creation form..."}):e.jsxs("form",{onSubmit:K,className:be?"max-h-[min(76vh,36rem)] space-y-3 overflow-y-auto pr-1 text-sm":"space-y-5",children:[be?e.jsxs("div",{className:"pr-8",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Create New Chat"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Choose the workspace, model, and approval mode for this thread."})]}):null,e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-xs font-medium",htmlFor:`${i}-thread-backend`,children:"Backend"}),e.jsx("select",{id:`${i}-thread-backend`,value:y,onChange:k=>{const G=k.target.value;m(G)},className:ke,children:v.map(k=>e.jsxs("option",{value:k.provider,disabled:!st(k),children:[k.displayName,st(k)?"":" (not available)"]},k.provider))}),be?Ne&&!st(Ne)?e.jsx("p",{className:"mt-2 text-xs text-[var(--theme-fg-muted)]",children:"Select an available backend before creating a thread."}):null:e.jsx("div",{className:"mt-3 space-y-2",children:v.map(k=>{const G=st(k),ue=k.provider===y,ge=k.installation.installed?!!k.installation.updateCommand:!!k.installation.installCommand,fe=k.installation.installed?"Update":"Install",u=_===k.provider||k.installation.busy;return e.jsxs("div",{className:`rounded-lg border px-4 py-3 transition ${ue?"host-surface-strong":"host-surface"} ${G?"":"opacity-75"}`,children:[e.jsxs("div",{className:"flex flex-wrap items-start gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>{G&&m(k.provider)},disabled:!G||B||u,className:"min-w-0 flex-1 text-left disabled:cursor-not-allowed",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:k.displayName}),ue?e.jsx("span",{className:"host-pill rounded-full px-2 py-0.5 text-xs",children:"Selected"}):null,G?null:e.jsx("span",{className:"host-pill rounded-full px-2 py-0.5 text-xs",children:"Not available"})]}),e.jsx("p",{className:"mt-1 text-sm opacity-75",children:k.installation.installed?`Installed${k.installation.installedVersion?`: ${k.installation.installedVersion}`:""}`:k.installation.lastError??k.status.lastError??"Runtime is not installed."}),!G&&k.installation.lastError?e.jsx("p",{className:"mt-1 text-xs opacity-70",children:k.installation.lastError}):null]}),ge?e.jsx("button",{type:"button",onClick:()=>O(k),disabled:B||u||_!==null,className:"host-secondary-button rounded-lg border px-3 py-2 text-sm font-medium transition disabled:cursor-not-allowed disabled:opacity-60","aria-label":`${fe} ${k.displayName}`,children:u?`${fe}ing...`:fe}):null]}),!G&&ge?e.jsx("p",{className:"mt-2 text-xs opacity-70",children:"Relay connections install or update the runtime on the selected device."}):null]},k.provider)})}),!be&&Ne&&!st(Ne)?e.jsx("p",{className:"mt-2 text-sm opacity-75",children:"Select an available backend, or install this runtime before creating a thread."}):null]}),e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-xs font-medium",htmlFor:`${i}-thread-workspace`,children:"Workspace"}),e.jsx("select",{id:`${i}-thread-workspace`,value:p,onChange:k=>L(k.target.value),className:ke,children:c.map(k=>e.jsxs("option",{value:k.id,children:[k.label," · ",k.absPath]},k.id))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-xs font-medium",htmlFor:`${i}-thread-model`,children:"Model"}),e.jsxs("select",{id:`${i}-thread-model`,value:M,onChange:k=>D(k.target.value),disabled:g.length===0,className:ke,children:[g.length===0?e.jsx("option",{value:"",children:"No models available"}):null,g.map(k=>e.jsxs("option",{value:k.model,children:[k.displayName," · ",k.model]},k.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-xs font-medium",htmlFor:`${i}-thread-title`,children:"Title"}),e.jsx("input",{id:`${i}-thread-title`,value:I,onChange:k=>A(k.target.value),placeholder:"Optional. Falls back to first prompt.",className:ke})]}),e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-xs font-medium",htmlFor:`${i}-thread-approval-mode`,children:"Approval mode"}),e.jsxs("select",{id:`${i}-thread-approval-mode`,value:J,onChange:k=>Y(k.target.value),className:ke,children:[e.jsx("option",{value:"yolo",children:"yolo"}),e.jsx("option",{value:"guarded",children:"guarded"})]})]}),oe&&e.jsx("div",{className:"host-error rounded-lg border px-4 py-3 text-sm",children:oe}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[e.jsx("button",{type:"submit",disabled:B||!p||!M,className:W,children:B?"Creating...":"Create Thread"}),r?e.jsx("button",{type:"button",onClick:r,disabled:B,className:P,children:"Cancel"}):null]})]})}const qr=3,jc=3,Nc=1e3,kc=2e3,Bs=5500,Sc=3e3,Ws=0,xt=1,Xt=3,Cc=[],Tc=[],Ec=[],Ic={workspace:!0,toolUsage:!1,guide:!1,threadGraph:!1,extensions:!1,defaultTab:"workspace"};function Qt(t,s){return t instanceof ae?t.payload.message:t instanceof Error?t.message:s}function Vr(t){return t==="read"?"View only":"Collaborator"}function zr(t){switch(t){case"write":return"Workspace write";case"read":return"Workspace read";case"none":default:return"No workspace"}}function Rc(t){var s,a;return((a=(s=t.match(/^\[PHOTO\s+([^\]]+)\]$/))==null?void 0:s[1])==null?void 0:a.trim())??null}function Gr(t){return!(t!=null&&t.length)||typeof URL.createObjectURL!="function"?[]:t.flatMap(s=>{if(s.kind!=="photo")return[];const a=Rc(s.placeholder);return a?[{path:a,url:URL.createObjectURL(s.file)}]:[]})}function Ac(t){if(typeof URL.revokeObjectURL=="function")for(const s of t)URL.revokeObjectURL(s.url)}function Pc(t,s){const a=t.trim().replace(/\\/g,"/").replace(/\/+$/,""),r=s.trim().replace(/\\/g,"/").replace(/\/+$/,"");if(!a)return null;if(!a.startsWith("/"))return a.replace(/^\.\/+/,"").replace(/^\/+/,"");if(a===r)return"";const o=`${r}/`;return a.startsWith(o)?a.slice(o.length):null}function Oc(){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 es({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 Lc(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 Jr(){var pr;const{id:t=""}=Mo(),s=Lt(),a=Ze(),r=Ut(),o=rn(),l=n.useRef(""),i=n.useRef(null),c=n.useRef(null),f=n.useRef(null),v=n.useRef(!1),b=n.useRef(null),g=n.useRef(null),S=n.useRef(typeof navigator>"u"?!0:navigator.onLine),y=n.useRef(!1),m=n.useRef(null),p=n.useRef(null),L=n.useRef(0),M=n.useRef(0),D=n.useRef(null),I=n.useRef(null),A=n.useRef(null),J=n.useRef(!1),Y=n.useRef(null),Z=n.useRef(new Set),[d,B]=n.useState(null),[Q,_]=n.useState([]),[re,oe]=n.useState([]),[ve,ce]=n.useState(null),[Ne,be]=n.useState(null),[ke,P]=n.useState(null),[W,te]=n.useState(0),[O,K]=n.useState(null),[k,G]=n.useState(""),[ue,ge]=n.useState(null),[fe,u]=n.useState(null),N=n.useRef(null),[X,Ce]=n.useState(!0),[w,E]=n.useState(0),[H,ee]=n.useState(0),[pe,Pe]=n.useState(0),[rt,nt]=n.useState(!1),[xs,ct]=n.useState(!1),[$t,Xe]=n.useState(!0),[Mt,gs]=n.useState(!1),[ot,Qe]=n.useState(!1),[_e,ha]=n.useState("chat"),[Xn,Qn]=n.useState(null),fa=o.getThreadPanels().some(h=>h.kind==="terminal");n.useEffect(()=>{N.current=fe},[fe]);const pa=n.useMemo(()=>({fetchState:Li,createShell:$i,terminateShell:Mi,updateShell:Hi,connectSocket:id}),[]),xa=n.useCallback(h=>$e(h),[]),Ht=n.useCallback(h=>{a($e(h))},[a]),ga=n.useCallback(h=>ls(h),[]),va=n.useCallback(({close:h,closeNavigation:j,currentWorkspaceId:x})=>e.jsx(ma,{variant:"dialog",initialWorkspaceId:x,onCancel:h,onCreated:C=>{h(),j(),a($e(C.id))}}),[a]),ba=n.useCallback(({threadId:h,path:j})=>ji(h,{path:j}),[]),[ya,vs]=n.useState({prompt:"",attachments:[]}),[le,wa]=n.useState(null),[ja,wt]=n.useState(!1),[eo,Na]=n.useState(!1),[to,ka]=n.useState(!1),[Sa,Ca]=n.useState(null),[lt,_t]=n.useState("idle"),[et,Ta]=n.useState({status:S.current?"checking":"offline",browserOnline:S.current,healthOk:!1,socketOpen:!1,lastHealthyAt:null}),[ye,De]=n.useState(null),[Bt,ut]=n.useState([]);n.useEffect(()=>{const h=(ye==null?void 0:ye.attachmentPreviews)??[];return()=>{Ac(h)}},[ye]);const[Ve,bs]=n.useState(null),[ys,Ea]=n.useState(!1),[so,se]=n.useState(null),ws=((pr=O==null?void 0:O.hostConfigFiles.find(h=>{var j;return(j=h.roles)==null?void 0:j.includes("mcp")}))==null?void 0:pr.name)??null,{exportBusy:js,exportDialogOpen:Wt,exportTurnsState:Ia,forkTurnOptionsState:ao,goalState:Ra,handleCreateHook:ro,handleExportTranscript:Aa,handleForkLatest:no,handleForkTurn:oo,handleOpenForkTurns:lo,handleOpenGoal:io,handleOpenHooks:co,handleOpenMcp:uo,handleOpenSkills:mo,handleTrustHook:ho,handleUntrustHook:fo,handleUpdateGoal:po,handleUpdateHook:xo,hooksState:go,loadExportTurns:Pa,mcpState:vo,setExportDialogOpen:Ns,setGoalState:ks,skillsState:bo}=gc({detailRef:A,id:t,navigate:a,setDetail:B,setError:se,setThreads:_}),[Ss,Ft]=n.useState(!1),[Oa,ze]=n.useState({status:"idle",shares:[],error:null}),[qt,Vt]=n.useState({status:"idle",access:null,error:null}),La=dn(s.pathname),it=at()&&!!La,ie=qt.access,jt=!it||(ie==null?void 0:ie.kind)==="owner",Oe=jt||(ie==null?void 0:ie.kind)==="shared"&&ie.threadAccess==="control",Ua=it&&(ie==null?void 0:ie.kind)==="owner",yo=(d==null?void 0:d.workspace.id)??(d==null?void 0:d.thread.workspaceId)??null,wo=it?(ie==null?void 0:ie.kind)==="owner"?"write":(ie==null?void 0:ie.kind)==="shared"&&ie.workspaceId&&ie.workspaceId===yo?ie.workspaceAccess:"none":"write",mt=n.useCallback(async()=>{const h=A.current,j=Ye();if(!at()||!h||!j){ze({status:"ready",shares:[],error:null});return}ze(x=>({...x,status:"loading",error:null}));try{const C=(await yn()).sharedByMe.filter(U=>U.deviceId===j&&U.threadId===h.thread.id).map(U=>({id:U.id,targetUsername:U.targetUsername,label:U.label,threadAccess:U.threadAccess,workspaceAccess:U.workspaceAccess,createdAt:U.createdAt}));ze({status:"ready",shares:C,error:null})}catch(x){ze(C=>({...C,status:"failed",error:Qt(x,"Unable to load active shares.")}))}},[A]),Da=n.useCallback(async h=>{const j=A.current,x=Ye();if(!at()||!j||!x){ze(U=>({...U,status:"failed",error:"Relay sharing is only available from a relay device route."}));return}const C=h.workspaceAccess==="none"?null:j.workspace.id??j.thread.workspaceId??null;if(h.workspaceAccess!=="none"&&!C){ze(U=>({...U,status:"failed",error:"This thread is not attached to a workspace."}));return}Ft(!0),ze(U=>({...U,error:null}));try{await _l({targetIdentifier:h.targetIdentifier,deviceId:x,threadId:j.thread.id,workspaceId:C,label:h.label??null,threadAccess:h.threadAccess,workspaceAccess:h.workspaceAccess}),await mt()}catch(U){const z=Qt(U,"Unable to create share.");ze(de=>({...de,status:"failed",error:z})),se(z)}finally{Ft(!1)}},[A,mt]),$a=n.useCallback(async h=>{Ft(!0),ze(j=>({...j,error:null}));try{await wn(h),await mt()}catch(j){const x=Qt(j,"Unable to revoke share.");ze(C=>({...C,status:"failed",error:x})),se(x)}finally{Ft(!1)}},[mt]),Ma=n.useCallback(()=>{const h=Ye();h&&(Ns(!1),a(`/relay-devices?shareDevice=${encodeURIComponent(h)}`))},[a]);n.useEffect(()=>{Wt&&mt()},[Wt,mt]),n.useEffect(()=>{const h=A.current,j=Ye();if(!at()||!h||!j){Vt({status:"idle",access:null,error:null});return}let x=!1;return Vt(C=>({...C,status:"loading",error:null})),Ul({deviceId:j,threadId:h.thread.id}).then(C=>{x||Vt({status:"ready",access:C,error:null})}).catch(C=>{x||Vt({status:"failed",access:null,error:Qt(C,"Unable to verify relay permissions.")})}),()=>{x=!0}},[d==null?void 0:d.thread.id,d==null?void 0:d.workspace.id,A]),qn({enabled:!!t,setThreads:_});const Ha=n.useCallback(()=>{const h=l.current;l.current="",i.current=null,h&&n.startTransition(()=>{G(j=>j+h)})},[]),_a=n.useCallback(h=>{l.current+=h,i.current===null&&(i.current=window.requestAnimationFrame(()=>{Ha()}))},[Ha]),Ba=n.useCallback((h,j)=>{u(x=>{const C=(x==null?void 0:x.turnId)===h?x.items:[],U=C.findIndex(ne=>ne.id===j.id),z=_n(C[U],j),de=U>=0?C.map((ne,xe)=>xe===U?z:ne):[...C,z];return{turnId:h,items:de,updatedAt:new Date().toISOString()}})},[]),Wa=n.useCallback((h,j,x,C,U)=>{u(z=>{const de=(z==null?void 0:z.turnId)===h?z.items:[],ne=de.find(Te=>Te.id===j),xe=(ne==null?void 0:ne.kind)==="agentMessage"?{...ne,text:`${ne.text}${x}`,sequence:C??ne.sequence??null}:{id:j,createdAt:U??new Date().toISOString(),kind:"agentMessage",text:x,sequence:C},F=de.findIndex(Te=>Te.id===j),Re=F>=0?de.map((Te,Ie)=>Ie===F?xe:Te):[...de,xe];return{turnId:h,items:Re,updatedAt:new Date().toISOString()}})},[]),Ge=n.useCallback(()=>{l.current="",i.current!==null&&(window.cancelAnimationFrame(i.current),i.current=null)},[]),Fa=n.useCallback(h=>{const j=Y.current,x=j&&Object.keys(j).length>0?{...h,thread:{...h.thread,...j}}:h,C={...x,turns:rc(x.turns,N.current)},U=A.current;A.current=C,ge(C.livePlan??null);const z=U?Je(U.turns,C.turns):C.turns;u(F=>ic(F,C.liveItems??null,z)),ks(F=>F.status==="idle"?F:{...F,data:C.goal??null});const de=C.thread.activeTurnId===null&&C.thread.status!=="running";B(F=>F&&!C.goalHistory?{...C,turns:Je(F.turns,C.turns),pendingRequests:_r(F.pendingRequests,C.pendingRequests,Z.current),...F.goalHistory?{goalHistory:F.goalHistory}:{}}:F?{...C,turns:Je(F.turns,C.turns),pendingRequests:_r(F.pendingRequests,C.pendingRequests,Z.current)}:C),_(F=>At(F,C.thread));const ne=new Map(C.turns.map(F=>[F.id,F])),xe=new Set((C.pendingSteers??[]).map(F=>F.clientRequestId).filter(F=>!!F));ut(F=>F.filter(Re=>{if(xe.has(Re.clientRequestId))return!1;const Te=ne.get(Re.turnId);return!(!Te||ca(Te,Re.prompt)||C.thread.activeTurnId!==Re.turnId&&Te.status!=="inProgress")})),De(F=>{if(!F)return F;const Re=F.serverTurnId??F.id,Te=C.turns.some(V=>V.id===Re),Ie=ne.get(Re)??null,T=hc(C.turns,F.prompt),$=!!T;if(T&&!F.serverTurnId)return{...F,id:T.id,serverTurnId:T.id,status:F.status==="failed"?F.status:T.status==="inProgress"?"inProgress":F.status};if(Ie&&F.serverTurnId)return Ie.items.some(he=>he.kind==="userMessage")?Ie.status==="inProgress"?{...F,id:Ie.id,serverTurnId:Ie.id,status:F.status==="failed"?F.status:"inProgress"}:null:{...F,id:Ie.id,serverTurnId:Ie.id,status:F.status==="failed"?F.status:Ie.status==="inProgress"?"inProgress":Ie.status==="failed"?"failed":"completed"};if(!F.serverTurnId&&ua(F.prompt)&&C.thread.activeTurnId&&C.thread.status==="running"){const V=ne.get(C.thread.activeTurnId);if(V&&Fn(V))return{...F,id:V.id,serverTurnId:V.id,status:F.status==="failed"?F.status:"inProgress"}}return Te||de&&$?null:F}),(de||I.current&&C.turns.some(F=>F.id===I.current))&&(I.current=null,Ge(),G(""),ge(null),u(null))},[Ge]);n.useEffect(()=>{A.current=d},[d]),n.useEffect(()=>{d!=null&&d.thread.title&&(document.title=d.thread.title)},[d==null?void 0:d.thread.title]),n.useEffect(()=>{const h=d==null?void 0:d.thread.provider;if(!h||h!=="codex"&&h!=="claude"){P(null);return}let j=!1;const x=async()=>{var U;try{const z=await ui(h);j||P(((U=z.usage)==null?void 0:U.authKind)==="subscription"&&z.usage.windows.length>0?z.usage:null)}catch{j||P(z=>z?{...z,stale:!0}:null)}};x();const C=window.setInterval(x,6e4);return()=>{j=!0,window.clearInterval(C)}},[d==null?void 0:d.thread.lastTurnCompletedAt,d==null?void 0:d.thread.provider,W]);const qa=n.useCallback(async({seedThread:h}={})=>{var de;const j=M.current+1;M.current=j;const x=(h==null?void 0:h.provider)??((de=A.current)==null?void 0:de.thread.provider)??"codex",[C,U,z]=await Promise.allSettled([ra(),Nn(x),rs(x)]);M.current===j&&(C.status==="fulfilled"?_(h?At(C.value,h):C.value):h&&_(ne=>At(ne,h)),U.status==="fulfilled"&&(D.current=x,ce(U.value.status),be(U.value.capabilities),K(U.value.managementSchema)),z.status==="fulfilled"&&(D.current=x,oe(z.value)))},[]),ht=n.useCallback(async({showLoading:h=!0,clearError:j=!0,reportError:x=!0,limit:C=qr}={})=>{const U=L.current+1;L.current=U,h&&Xe(!0),j&&se(null);try{const z=await Cr(t,{limit:C});if(L.current!==U)return;Fa(z),D.current!==z.thread.provider&&qa({seedThread:z.thread})}catch(z){if(L.current!==U||!x)return;se(z instanceof Error?z.message:"Unable to load thread detail.")}finally{L.current===U&&Xe(!1)}},[Fa,t,qa]),Ee=n.useCallback(()=>{var ne;const h=((ne=c.current)==null?void 0:ne.readyState)??Xt,j=h===xt,x=S.current,C=Date.now(),U=b.current!==null&&C-Date.parse(b.current)<=Bs,z=g.current!==null&&C-g.current<=Bs;let de;x?j&&z?de="connected":h===Ws||f.current!==null||U||z||v.current?de="reconnecting":de="checking":de="offline",Ta(xe=>xe.status===de&&xe.browserOnline===x&&xe.healthOk===U&&xe.socketOpen===j&&xe.lastHealthyAt===b.current?xe:{status:de,browserOnline:x,healthOk:U,socketOpen:j,lastHealthyAt:b.current})},[]);n.useEffect(()=>{L.current+=1,M.current+=1,B(null),se(null),Xe(!0),vs({prompt:"",attachments:[]}),gs(!1),_t("idle"),De(null),ut([]),u(null),Y.current=null,I.current=null,Z.current=new Set,b.current=null,g.current=null,y.current=!1,S.current=typeof navigator>"u"?!0:navigator.onLine,Ta({status:S.current?"checking":"offline",browserOnline:S.current,healthOk:!1,socketOpen:!1,lastHealthyAt:null})},[t,La]),n.useEffect(()=>{if(lt==="idle")return;const h=window.setTimeout(()=>{_t("idle")},lt==="copied"?1200:1600);return()=>{window.clearTimeout(h)}},[lt]),n.useEffect(()=>{if(typeof document>"u")return;const{documentElement:h,body:j}=document;return h.classList.add("thread-detail-scroll-locked"),j.classList.add("thread-detail-scroll-locked"),()=>{h.classList.remove("thread-detail-scroll-locked"),j.classList.remove("thread-detail-scroll-locked")}},[]),n.useEffect(()=>{ht({showLoading:!0,limit:qr})},[ht]),n.useEffect(()=>{let h=!1,j=null;const x=()=>{ht({showLoading:!1,clearError:!1,reportError:!1})},C=()=>{f.current!==null&&(window.clearTimeout(f.current),f.current=null)},U=()=>{h||!S.current||f.current!==null||(f.current=window.setTimeout(()=>{f.current=null,!h&&xe()},Nc),Ee())},z=()=>{const T=c.current;if(c.current=null,T)try{T.close()}catch{}},de=T=>{if(T.threadId===t){if(T.type==="thread.output.delta"&&typeof T.payload.delta=="string"){const $=typeof T.payload.turnId=="string"?T.payload.turnId:null,V=typeof T.payload.itemId=="string"?T.payload.itemId:null,he=typeof T.payload.sequence=="number"&&Number.isFinite(T.payload.sequence)?T.payload.sequence:null;$&&V?Wa($,V,T.payload.delta,he,T.payload.createdAt??T.timestamp):_a(T.payload.delta),$&&De(me=>me&&(me.serverTurnId===null||me.serverTurnId===$)?{...me,serverTurnId:$,id:$,status:me.status==="failed"?me.status:"inProgress",tokenUsage:me.tokenUsage}:me)}if(T.type==="thread.context.updated"){const $=T.payload.contextUsage&&typeof T.payload.contextUsage=="object"?T.payload.contextUsage:null;if($){const V=$;B(he=>he&&{...he,thread:{...he.thread,contextUsage:V}}),_(he=>he.map(me=>me.id===t?{...me,contextUsage:V}:me))}}if(T.type==="thread.turn.token.updated"&&typeof T.payload.turnId=="string"&&T.payload.tokenUsage&&typeof T.payload.tokenUsage=="object"){const $=T.payload.turnId,V=T.payload.tokenUsage,he=T.payload.priceEstimate&&typeof T.payload.priceEstimate=="object"?T.payload.priceEstimate:null;B(me=>{if(!me)return me;const St=pc(me.turns,$,V,he);return St===me.turns?me:{...me,turns:St}}),De(me=>me&&(me.serverTurnId===$||me.id===$)?{...me,tokenUsage:V,priceEstimate:he}:me)}if(T.type==="thread.turn.started"||T.type==="thread.turn.completed"||T.type==="thread.turn.failed"||T.type==="thread.updated"||T.type==="thread.goal.updated"||T.type==="thread.goal.cleared"||T.type==="thread.request.created"||T.type==="thread.request.resolved"){if(T.type==="thread.goal.updated"){const $=T.payload.goal&&typeof T.payload.goal=="object"?T.payload.goal:null,V=Array.isArray(T.payload.goalHistory)?T.payload.goalHistory:null;ks({status:"ready",data:$,error:null}),B(he=>he&&(V?{...he,goal:$,goalHistory:V}:$?{...he,goal:$,goalHistory:hs(he.goalHistory??[],$)}:{...he,goal:$}))}if(T.type==="thread.goal.cleared"){const $=Array.isArray(T.payload.goalHistory)?T.payload.goalHistory:null;ks({status:"ready",data:null,error:null}),B(V=>V&&($?{...V,goal:null,goalHistory:$}:{...V,goal:null}))}if(x(),T.type==="thread.turn.started"){Ge(),G(""),u(null),I.current=null;const $=typeof T.payload.turnId=="string"?T.payload.turnId:null;$&&De(V=>V&&{...V,serverTurnId:$,id:$,status:V.status==="failed"?V.status:"inProgress",error:null,tokenUsage:V.tokenUsage})}if(T.type==="thread.turn.completed"||T.type==="thread.turn.failed"){Ge(),G("");const $=typeof T.payload.turnId=="string"?T.payload.turnId:null;$&&(I.current=$,T.type==="thread.turn.failed"&&De(V=>V&&(V.serverTurnId===$||V.id===$)?{...V,status:"failed",error:typeof T.payload.error=="string"?T.payload.error:"Unable to complete the turn.",tokenUsage:V.tokenUsage}:V))}}if(T.type==="thread.request.created"&&lc(T.payload.request)&&(Z.current.delete(T.payload.request.id),B($=>$&&nc($,T.payload.request))),T.type==="thread.request.resolved"&&typeof T.payload.requestId=="string"){const $=T.payload.requestId;Z.current.add($),B(V=>V&&oc(V,$))}if((T.type==="thread.item.started"||T.type==="thread.item.completed")&&T.payload.item&&typeof T.payload.item=="object"&&typeof T.payload.turnId=="string"){const $=T.payload.turnId,V=T.payload.item;typeof V.id=="string"&&typeof V.text=="string"&&Ba($,V)}T.type==="thread.plan.updated"&&Array.isArray(T.payload.plan)&&ge({turnId:String(T.payload.turnId??""),explanation:typeof T.payload.explanation=="string"?T.payload.explanation:null,plan:T.payload.plan})}},ne=()=>{const T=c.current;if(!(!T||T.readyState!==xt))try{T.send(JSON.stringify({type:"supervisor.ping",timestamp:new Date().toISOString()}))}catch{y.current=!0,z(),U(),Ee()}},xe=()=>{var V;if(h||!S.current){Ee();return}const T=((V=c.current)==null?void 0:V.readyState)??Xt;if(T===Ws||T===xt){Ee();return}const $=In(de);c.current=$,Ee(),$.addEventListener("message",he=>{if(c.current===$)try{const me=JSON.parse(he.data);(me.type==="supervisor.connected"||me.type==="supervisor.pong")&&(g.current=Date.now(),Ee())}catch{}}),$.addEventListener("open",()=>{c.current===$&&(y.current=!0,te(he=>he+1),x(),ne(),Ee())}),$.addEventListener("close",()=>{c.current===$&&(c.current=null),y.current=!0,U(),Ee()}),$.addEventListener("error",()=>{c.current===$&&(c.current=null),y.current=!0,U(),Ee()})},F=async()=>{var T;if(!(h||!S.current||v.current)){v.current=!0,Ee();try{await vi();const $=y.current;b.current=new Date().toISOString(),$&&(y.current=!1,x()),(((T=c.current)==null?void 0:T.readyState)??Xt)!==xt&&xe()}catch{b.current=null,y.current=!0,U()}finally{v.current=!1,Ee()}}},Re=()=>{S.current=!0,y.current=!0,Ee(),xe(),F()},Te=()=>{S.current=!1,b.current=null,g.current=null,y.current=!0,C(),z(),Ee()},Ie=()=>{var V;if(h||!S.current){Ee();return}const T=((V=c.current)==null?void 0:V.readyState)??Xt,$=g.current===null?null:Date.now()-g.current;T===xt&&$!==null&&$>Bs?(y.current=!0,z(),U()):T===xt?ne():T!==Ws&&xe(),F(),Ee()};return window.addEventListener("online",Re),window.addEventListener("offline",Te),xe(),F(),j=window.setInterval(Ie,kc),()=>{h=!0,window.removeEventListener("online",Re),window.removeEventListener("offline",Te),C(),j!==null&&window.clearInterval(j),Ge(),z()}},[Wa,Ge,t,ht,_a,Ee,Ba]),n.useEffect(()=>{if(!((d==null?void 0:d.thread.activeTurnId)!==null||(d==null?void 0:d.thread.status)==="running"||ye!==null||Bt.length>0||k.length>0||ue!==null||fe!==null))return;const j=window.setInterval(()=>{ht({showLoading:!1,clearError:!1,reportError:!1})},Sc);return()=>{window.clearInterval(j)}},[d==null?void 0:d.thread.activeTurnId,d==null?void 0:d.thread.status,k.length,fe,ue,ht,Bt.length,ye]);const Va=n.useCallback(async()=>{var h;if(!(!d||d.turns.length===0||Mt)){gs(!0),se(null);try{const j=(h=d.turns[0])==null?void 0:h.id,x=await Cr(t,{limit:jc,...j?{beforeTurnId:j}:{}});B(C=>C?{...x,turns:ac(C.turns,x.turns)}:x),_(C=>C.map(U=>U.id===x.thread.id?x.thread:U))}catch(j){se(j instanceof Error?j.message:"Unable to load earlier turns.")}finally{gs(!1)}}},[d,t,Mt]);async function jo(h){var Re,Te,Ie;if(_e==="shell"){if((d==null?void 0:d.thread.isLoaded)===!1)return await Cs({attachShell:!0}),!1;let T=!1;if((le==null?void 0:le.shellInputEnabled)!==!0&&((le==null?void 0:le.loading)===!1&&(le==null?void 0:le.isConnecting)!==!0&&(le==null?void 0:le.status)!=="creating"&&(le==null?void 0:le.status)!=="workspace_missing"&&(await((Re=m.current)==null?void 0:Re.toggleConnection()),T=!0),(le==null?void 0:le.isConnecting)===!0))return se("Connecting to the shell. Try again after it attaches."),!1;if(((Te=m.current)==null?void 0:Te.sendCommand(h.prompt))??!1)se(null);else return se(T?"Shell is still attaching. Try again after it connects.":"Connect the shell before sending commands."),!1;return!0}if(Nt)return se(Nt),!1;Qe(!0),se(null),E(T=>T+1);const j=A.current,x=j?{...j.thread,...Y.current??{}}:null,C=(x==null?void 0:x.model)??null,U=(x==null?void 0:x.reasoningEffort)??null,z=uc(),de=`optimistic-${Date.now()}`,ne=`optimistic-steer-${z}`,xe=new Date().toISOString();let F=[];try{let T=A.current;if(T&&!T.thread.isLoaded){const we={...T.thread,...Y.current??{}},Me=await As(t,{...T.thread.model?{model:T.thread.model}:{}}),Le={...Me,thread:{...Me.thread,model:we.model??Me.thread.model,reasoningEffort:we.reasoningEffort??Me.thread.reasoningEffort,collaborationMode:we.collaborationMode??Me.thread.collaborationMode}};T=Le,A.current=Le,B(Yt=>Yt?{...Le,turns:Je(Yt.turns,Le.turns)}:Le),_(Yt=>Yt.map(xr=>xr.id===Le.thread.id?Le.thread:xr))}const $=T?{...T.thread,...Y.current??{}}:null,V=($==null?void 0:$.status)==="running"?$.activeTurnId:null,he=_e==="chat"&&!!V;he&&V?ut(we=>[...we,{id:ne,clientRequestId:z,turnId:V,prompt:h.prompt,createdAt:xe,status:"steering"}]):(F=Gr(h.attachments),Ge(),G(""),De({id:de,serverTurnId:null,startedAt:xe,status:"sending",error:null,prompt:h.prompt,attachmentPreviews:F,model:C,reasoningEffort:U,reasoningEffortAvailable:_s(re,C),tokenUsage:null,priceEstimate:null}));const me={prompt:h.prompt,clientRequestId:z,...$!=null&&$.model?{model:$.model}:{},...$!=null&&$.reasoningEffort?{reasoningEffort:$.reasoningEffort}:{},...$!=null&&$.collaborationMode?{collaborationMode:$.collaborationMode}:{},...(Ie=h.attachments)!=null&&Ie.length?{attachments:h.attachments}:{}},St=await Bi(t,me),Be=Y.current&&Object.keys(Y.current).length>0?{...St,...Y.current}:St;B(we=>we&&{...we,thread:Be}),_(we=>we.map(Me=>Me.id===Be.id?Be:Me)),he&&V?Be.activeTurnId!==null&&Be.activeTurnId!==V&&Be.lastTurnStartedAt!==($==null?void 0:$.lastTurnStartedAt)?(F=Gr(h.attachments),Ge(),G(""),ge(null),ut(Me=>Me.filter(Le=>Le.id!==ne)),De({id:de,serverTurnId:Be.activeTurnId,startedAt:Be.lastTurnStartedAt??xe,status:"inProgress",error:null,prompt:h.prompt,attachmentPreviews:F,model:C,reasoningEffort:U,reasoningEffortAvailable:_s(re,C),tokenUsage:null,priceEstimate:null})):ut(Me=>Me.map(Le=>Le.id===ne?{...Le,turnId:Be.activeTurnId??Le.turnId,status:"accepted"}:Le)):(De(we=>we&&we.id===de?{...we,id:Be.activeTurnId??we.id,serverTurnId:Be.activeTurnId??we.serverTurnId,status:"inProgress",error:null,tokenUsage:we.tokenUsage,priceEstimate:we.priceEstimate}:we),ge(null)),vs({prompt:"",attachments:[]})}catch(T){const $=T instanceof ae?T.payload.message:T instanceof Error?T.message:"Unable to send prompt.";T instanceof ae?se(T.payload.message):se($),ut(V=>V.filter(he=>he.clientRequestId!==z)),De(V=>V&&V.id===de?{...V,status:"failed",error:$}:V)}finally{Qe(!1)}}async function za(h){if(J.current)return!1;J.current=!0;try{return await jo(h)}finally{J.current=!1}}async function No(){const h=A.current;if(!h)return se("Thread detail is still loading."),!1;if(h.thread.isLoaded)return!0;Qe(!0),se(null);try{const j=await As(t,{...h.thread.model?{model:h.thread.model}:{}});return B(x=>x?{...j,turns:Je(x.turns,j.turns)}:j),_(x=>x.map(C=>C.id===j.thread.id?j.thread:C)),!0}catch(j){return se(j instanceof Error?j.message:"Unable to connect this thread before setting its goal."),!1}finally{Qe(!1)}}async function ko(h){var de;const j=((de=h.objective)==null?void 0:de.trim())??"",x=j?`optimistic-goal-${Date.now()}`:null,C=new Date().toISOString(),U=A.current,z=(U==null?void 0:U.thread)??null;x&&(E(ne=>ne+1),De({id:x,serverTurnId:null,startedAt:C,status:"sending",error:null,prompt:j,attachmentPreviews:[],model:(z==null?void 0:z.model)??null,reasoningEffort:(z==null?void 0:z.reasoningEffort)??null,reasoningEffortAvailable:_s(re,(z==null?void 0:z.model)??null),tokenUsage:null,priceEstimate:null}));try{await po(h),x&&De(ne=>ne&&ne.id===x?{...ne,status:"completed",error:null}:ne)}catch(ne){const xe=ne instanceof ae?ne.payload.message:ne instanceof Error?ne.message:"Unable to set goal.";throw se(xe),x&&De(F=>F&&F.id===x?{...F,status:"failed",error:xe}:F),ne}}async function So(){const h=d==null?void 0:d.thread.providerSessionId;if(h)try{await navigator.clipboard.writeText(h),_t("copied")}catch{_t("failed")}}async function Cs(h){if(d){Qe(!0),se(null),Ge(),G("");try{if(d.thread.isLoaded){const x=await _i(t);B(C=>C?{...x,turns:Je(C.turns,x.turns)}:x),wa(null),_(C=>C.map(U=>U.id===x.thread.id?x.thread:U)),wt(!1);return}const j=await As(t,{...d.thread.model?{model:d.thread.model}:{}});B(x=>x?{...j,turns:Je(x.turns,j.turns)}:j),_(x=>x.map(C=>C.id===j.thread.id?j.thread:C)),h!=null&&h.attachShell&&_e==="shell"&&wt(!0)}catch(j){se(j instanceof Error?j.message:"Unable to change connection state.")}finally{Qe(!1)}}}async function zt(){var h;if(_e==="shell"){const j=((h=m.current)==null?void 0:h.sendControl("ctrl_c"))??!1;se(j?null:"Connect the shell before sending Ctrl-C.");return}Qe(!0),se(null);try{const j=d!=null&&d.thread.activeTurnId?await Tr(t,{turnId:d.thread.activeTurnId}):await Tr(t);B(x=>x&&{...x,thread:j}),_(x=>x.map(C=>C.id===j.id?j:C)),Ge(),G("")}catch(j){se(j instanceof Error?j.message:"Unable to interrupt turn.")}finally{Qe(!1)}}async function Ts(h){if(!d)return;const j=d,x={...Y.current??{},...h.model!==void 0?{model:h.model}:{},...h.reasoningEffort!==void 0?{reasoningEffort:h.reasoningEffort}:{},...h.fastMode!==void 0?{fastMode:h.fastMode}:{},...h.collaborationMode!==void 0?{collaborationMode:h.collaborationMode}:{}},C={...d.thread,...x};Na(!0),Y.current=x,A.current={...d,thread:C},B(U=>U&&{...U,thread:C}),_(U=>U.map(z=>z.id===C.id?{...z,...C}:z));try{const U=await qi(t,{...h.model!==void 0?{model:h.model}:{},...h.reasoningEffort!==void 0?{reasoningEffort:h.reasoningEffort}:{},...h.fastMode!==void 0?{fastMode:h.fastMode}:{},...h.collaborationMode!==void 0?{collaborationMode:h.collaborationMode}:{}});Y.current=null,A.current=j?{...j,thread:U}:null,B(z=>z&&{...z,thread:U}),_(z=>z.map(de=>de.id===U.id?U:de))}catch(U){Y.current=null,A.current=j,B(j),_(z=>z.map(de=>de.id===j.thread.id?j.thread:de)),se(U instanceof Error?U.message:"Unable to update thread settings.")}finally{Na(!1)}}const Ga=n.useCallback(async(h,j)=>{if((ie==null?void 0:ie.kind)==="shared"&&ie.threadAccess==="read"){se("This shared session is view only.");return}Ca(h),se(null);try{const x=await ad(t,h,j);B(C=>C?{...x,turns:Je(C.turns,x.turns)}:x),ge(x.livePlan??null),u(x.liveItems??null)}catch(x){se(x instanceof Error?x.message:"Unable to answer this request.")}finally{Ca(null)}},[t]),Ja=n.useCallback(h=>Ci(t,h),[t]),Ka=n.useCallback(async(h,j)=>{se(null);try{const x=await Wi(h,j);B(C=>C?{...x,turns:Je(C.turns,x.turns)}:x),_(C=>C.map(U=>U.id===x.thread.id?x.thread:U))}catch(x){throw se(x instanceof Error?x.message:"Unable to cancel queued prompt."),x}},[]),Ya=n.useCallback(async(h,j)=>{se(null);try{const x=await Fi(h,j);B(C=>C?{...x,turns:Je(C.turns,x.turns)}:x),_(C=>C.map(U=>U.id===x.thread.id?x.thread:U))}catch(x){throw se(x instanceof Error?x.message:"Unable to steer queued prompt."),x}},[]);async function Es(){if(d){ka(!0),se(null);try{const h=await Vi(t);B(j=>j&&{...j,thread:h}),_(j=>j.map(x=>x.id===h.id?h:x))}catch(h){se(h instanceof Error?h.message:"Unable to compact this thread context.")}finally{ka(!1)}}}async function Za(h,j){try{const x=await Tn(h,{title:j});_(C=>C.map(U=>U.id===x.id?{...U,title:x.title,updatedAt:x.updatedAt}:U)),B(C=>C&&C.thread.id===x.id?{...C,thread:{...C.thread,title:x.title,updatedAt:x.updatedAt}}:C)}catch(x){throw se(x instanceof Error?x.message:"Unable to rename thread."),x}}async function Xa(){if(Ve){Ea(!0),se(null);try{await En(Ve.id),_(j=>j.filter(x=>x.id!==Ve.id));const h=Ve.id===(d==null?void 0:d.thread.id);if(bs(null),h){const j=Q.find(x=>x.id!==Ve.id&&x.workspaceId===(d==null?void 0:d.thread.workspaceId))??Q.find(x=>x.id!==Ve.id);a(j?$e(j.id):Pt())}}catch(h){se(h instanceof Error?h.message:"Unable to delete thread.")}finally{Ea(!1)}}}function Qa(){ha(h=>h==="chat"?(d!=null&&d.thread.isLoaded&&wt(!0),"shell"):"chat")}async function er(){var j;const h=await((j=m.current)==null?void 0:j.copyLastCommandOutput());se(h?null:"Unable to copy the last shell command output.")}function tr(h){var x,C;const j=h==="clear"?((x=m.current)==null?void 0:x.sendCommand("clear"))??!1:((C=m.current)==null?void 0:C.sendControl(h))??!1;se(j?null:"Connect the shell before sending control input.")}n.useEffect(()=>{if(!(!ja||_e!=="shell"||!m.current||(d==null?void 0:d.thread.isLoaded)===!1||(le==null?void 0:le.loading)!==!1)){if((le==null?void 0:le.status)==="attached"){wt(!1);return}wt(!1),m.current.toggleConnection()}},[_e,d==null?void 0:d.thread.isLoaded,ja,le==null?void 0:le.loading,le==null?void 0:le.status]),n.useEffect(()=>{if(_e!=="shell")return;const h=window.requestAnimationFrame(()=>{var j;(j=m.current)==null||j.refreshLayout({syncBackendSize:!1})});return()=>{window.cancelAnimationFrame(h)}},[_e]);const Nt=d?d.workspacePathStatus==="missing"?"Restore this workspace path on the current machine before continuing.":it&&qt.status==="loading"?"Checking relay permissions...":it&&qt.status==="failed"?qt.error??"Unable to verify relay permissions.":(ie==null?void 0:ie.kind)==="shared"&&ie.threadAccess==="read"?"This shared session is view only.":null:null,{floatingMobileComposerBottomOffset:Co,timelineBottomSpacer:sr,useFloatingMobileComposer:To}=xc({activeView:_e,composerHostRef:p,threadId:(d==null?void 0:d.thread.id)??t}),Eo=d?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:d.thread.providerSessionId??"Unavailable"}),d.thread.providerSessionId&&e.jsx("button",{type:"button","aria-label":"Copy session ID",title:lt==="copied"?"Copied":lt==="failed"?"Copy failed":"Copy session ID",onClick:()=>void So(),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 backdrop-blur transition ${lt==="copied"?"ui-status-info":lt==="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(Oc,{})})})]}),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:d.thread.source==="local_codex_import"?`Imported local ${d.thread.provider} session`:`${d.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:Fo(d.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:gr(d.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:d.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:d.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:d.thread.activeTurnId??"None"})]})]}):null,Io=null,ar=ye&&d?fc(d.turns,ye):null,rr=n.useMemo(()=>ye&&!ar?{id:ye.id,startedAt:ye.startedAt,status:ye.status,error:ye.error,model:ye.model,reasoningEffort:ye.reasoningEffort,reasoningEffortAvailable:ye.reasoningEffortAvailable,tokenUsage:ye.tokenUsage,priceEstimate:ye.priceEstimate,items:[{id:`${ye.id}-user-message`,kind:"userMessage",text:ye.prompt,attachmentPreviewUrls:Object.fromEntries(ye.attachmentPreviews.map(h=>[h.path,h.url]))}]}:null,[ar,ye]),kt=(d==null?void 0:d.thread.isLoaded)??!1,Gt=kt?et.status==="connected"?"ui-action-success shadow-[var(--theme-shadow)]":et.status==="reconnecting"?"thread-live-connection-reconnecting ui-status-success shadow-[var(--theme-shadow)]":et.status==="offline"?"ui-status-danger shadow-[var(--theme-shadow)]":"ui-status-warning shadow-[var(--theme-shadow)]":"host-icon-button border shadow-[var(--theme-shadow)]",nr=Lc(kt,et),Jt=[nr,kt?null:"Tap to connect this thread",et.lastHealthyAt?`Last healthy ${gr(et.lastHealthyAt)}`:null].filter(Boolean).join(" · "),or=kt?e.jsx("div",{role:"status","aria-live":"polite","aria-label":nr,title:Jt,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition ${Gt}`,children:e.jsx(es,{status:et.status})}):e.jsx("button",{type:"button",onClick:()=>void Cs(),disabled:ot||!d,"aria-label":ot?"Connecting thread":"Connect thread",title:ot?"Connecting thread":Jt,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition ${Gt}`,children:e.jsx(es,{status:"detached"})}),lr=kt?e.jsx("div",{title:Jt,className:`hidden lg:inline-flex h-9 w-9 items-center justify-center rounded-full transition ${Gt}`,children:e.jsx(es,{status:et.status})}):e.jsx("button",{type:"button",onClick:()=>void Cs(),disabled:ot||!d,title:ot?"Connecting thread":Jt,className:`hidden lg:inline-flex h-9 w-9 items-center justify-center rounded-full transition ${Gt}`,children:e.jsx(es,{status:"detached"})}),ir=Ra.data??(d==null?void 0:d.goal)??null,dr=(d==null?void 0:d.goalHistory)??[],Ro=ir?hs(dr,ir):Bn(dr),Kt=n.useMemo(()=>(ie==null?void 0:ie.kind)==="shared"?e.jsxs("div",{className:"host-secondary-button inline-flex max-w-[10rem] items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] font-medium sm:max-w-[16rem]",title:`${Vr(ie.threadAccess)} / ${zr(ie.workspaceAccess)}`,children:[e.jsx("span",{children:Vr(ie.threadAccess)}),e.jsx("span",{className:"host-muted",children:"/"}),e.jsx("span",{className:"truncate",children:zr(ie.workspaceAccess)})]}):null,[ie]),Ao=n.useMemo(()=>e.jsx("button",{type:"button","aria-label":"Thread actions",title:"Thread actions",onClick:()=>Ns(!0),disabled:!d,className:"host-icon-button inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border shadow-[var(--theme-shadow)] transition disabled:cursor-not-allowed disabled:opacity-50 lg:h-9 lg:w-9",children:e.jsx(q.Share2,{className:"h-4 w-4","aria-hidden":"true"})}),[d]),Po=n.useMemo(()=>e.jsxs("div",{className:"relative flex items-center justify-end gap-1.5",children:[Kt,or]}),[or,Kt]),Oo=n.useMemo(()=>e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[Kt,lr]}),[lr,Kt]),Lo=n.useMemo(()=>({livePlan:ue,liveItems:fe,respondingRequestId:Sa,onRespondToRequest:Ga,scrollRequestKey:w,previousTurnScrollRequestKey:H,nextTurnScrollRequestKey:pe,bottomSpacer:sr,className:"thread-timeline-surface min-h-0 flex-1",onTailVisibilityChange:Ce,onPreviousTurnAvailabilityChange:nt,onNextTurnAvailabilityChange:ct,loadingEarlier:Mt,onLoadEarlier:Va,onOpenThread:Ht,answeredRequestNotes:(d==null?void 0:d.answeredRequestNotes)??Cc,activityNotes:(d==null?void 0:d.activityNotes)??Tc,pendingSteers:(d==null?void 0:d.pendingSteers)??Ec,optimisticSteers:Bt,optimisticTurn:rr}),[d==null?void 0:d.answeredRequestNotes,d==null?void 0:d.activityNotes,d==null?void 0:d.pendingSteers,Va,Ga,fe,ue,Mt,Ht,Bt,Sa,w,H,pe,sr,rr]),cr=d?{busy:_e==="chat"?ot:!1,settingsBusy:eo,error:null,model:d.thread.model,reasoningEffort:d.thread.reasoningEffort,fastMode:d.thread.fastMode??!1,collaborationMode:d.thread.collaborationMode,sandboxMode:null,modelOptions:re,contextUsage:d.thread.contextUsage,subscriptionUsage:ke,capabilities:Ne,toolboxItems:(O==null?void 0:O.toolboxItems)??[],hookCommandTemplates:(O==null?void 0:O.hookCommandTemplates)??[],mcpConfigFormat:(O==null?void 0:O.mcpConfigFormat)??"none",followTail:X,threadConnected:d.thread.isLoaded,shellAvailable:fa,disabled:!!Nt,...Nt?{disabledPlaceholder:Nt}:{},shellControlState:le,draftPrompt:ya.prompt,draftAttachments:ya.attachments,onDraftChange:vs,canInterrupt:!!(d.thread.activeTurnId&&Oe),...Oe?{onInterrupt:zt}:{},...Oe?{onCompact:Es,onOpenForkTurns:lo,onForkLatest:no,onForkTurn:oo,onOpenSkills:mo,onOpenMcp:uo,onOpenHooks:co,onCreateHook:ro,onUpdateHook:xo,onTrustHook:ho,onUntrustHook:fo}:{},goalState:Ra,goalHistory:Ro,...Oe?{onOpenGoal:io,onPrepareGoalSubmit:No,onUpdateGoal:ko}:{},...ws?{...jt?{onReadProviderConfig:()=>Sn(d.thread.provider,ws),onWriteProviderConfig:h=>Cn(d.thread.provider,ws,{content:h})}:{}}:{},onToggleFollow:()=>E(h=>h+1),canJumpToPreviousTurn:rt,onJumpToPreviousTurn:()=>ee(h=>h+1),canJumpToNextTurn:xs,onJumpToNextTurn:()=>Pe(h=>h+1),...Oe?{onUpdateSettings:Ts}:{},onToggleView:Qa,onShellCopy:er,...Oe?{onShellControl:tr}:{},compactBusy:to,skillsState:bo,mcpState:vo,hooksState:go,forkTurnOptionsState:ao}:null,ur=d?{busy:ot,settingsBusy:!1,error:d.thread.isLoaded?(le==null?void 0:le.error)??null:null,followTail:!1,capabilities:Ne,toolboxItems:(O==null?void 0:O.toolboxItems)??[],hookCommandTemplates:(O==null?void 0:O.hookCommandTemplates)??[],mcpConfigFormat:(O==null?void 0:O.mcpConfigFormat)??"none",threadConnected:d.thread.isLoaded,shellAvailable:fa,shellControlState:le,canInterrupt:!!(d.thread.isLoaded&&(le!=null&&le.isCommandRunning)&&Oe),...Oe?{onInterrupt:zt}:{},onToggleView:Qa,onShellCopy:er,...Oe?{onShellControl:tr}:{}}:null,mr=n.useCallback(h=>d?ba({threadId:d.thread.id,path:h}):"",[d==null?void 0:d.thread.id,ba]),hr=wc({setError:se,workspaceId:(d==null?void 0:d.workspace.id)??null,access:wo}),fr=n.useCallback(h=>{const j=A.current;if(!j)return;const x=Pc(h.path,j.workspace.absPath);if(x===null){se(`Cannot open ${h.path}; it is outside this workspace.`);return}ha("chat"),Qn(C=>({path:x,...h.line!==void 0?{line:h.line}:{},requestId:((C==null?void 0:C.requestId)??0)+1}))},[]),Uo=n.useMemo(()=>({openThread:Ht,getThreadHref:xa,getNewThreadHref:ga,renderNewThreadDialogContent:va,...jt?{renameThread:Za}:{},...jt?{deleteThread:bs}:{},cancelPendingSteer:Ka,...Oe?{steerPendingPrompt:Ya}:{},sendPrompt:za,...Oe?{interrupt:zt}:{},...Oe?{compact:Es}:{},...Oe?{updateSettings:Ts}:{},loadHistoryItemDetail:Ja,getImageAssetUrl:mr,openWorkspaceFile:fr,workspace:hr,shell:pa}),[mr,ga,xa,va,Es,Ka,Ya,zt,Ja,fr,za,Za,Ts,pa,Ht,Oe,jt,hr]),Do=d!=null&&d.thread.workspaceId?Pt(d.thread.workspaceId):fs(),$o=n.useMemo(()=>e.jsxs(e.Fragment,{children:[e.jsx(qo,{open:Wt,busy:js||Ss,turnsState:Ia,shareAvailable:Ua,...it&&(ie==null?void 0:ie.kind)==="shared"?{shareUnavailableMessage:"Only the owner can share this session."}:{},shareState:Oa,onCancel:()=>{!js&&!Ss&&Ns(!1)},onLoadTurns:Pa,onExport:Aa,...Ua?{onCreateShare:Da,onOpenDeviceSharing:Ma,onRevokeShare:$a}:{}}),e.jsx(ea,{open:Ve!==null,title:"Delete Thread",description:Ve?`Delete ${ol(Ve.title)} from supervisor. The backend session id will no longer appear in this workspace list.`:"",confirmLabel:"Delete Thread",busy:ys,onCancel:()=>{ys||bs(null)},onConfirm:()=>void Xa()})]}),[Ve,ys,js,Wt,Ia,Da,Xa,Aa,Ma,$a,Pa,it,Ss,Oa]);return e.jsx(Vo,{threads:Q,detail:d,status:ve,loading:$t,error:$t?null:so,plugins:o,adapter:Uo,metaContent:Eo,settingsContent:Io,globalSettingsContent:e.jsx(na,{embedded:!0}),mobileHeaderAction:Po,workspaceReturnHref:Do,onCloseAppNavigation:(r==null?void 0:r.closeNav)??(()=>{}),threadActionsButton:Ao,surfaceActions:Oo,workspaceFeatures:Ic,workspaceFocusPathRequest:Xn,activeView:_e,liveOutput:k,timelineProps:Lo,timelineComponent:Go,useFloatingMobileComposer:To,floatingMobileComposerBottomOffset:Co,composerHostRef:p,shellPanelRef:m,shellPanelComponent:zo,shellEffectiveTheme:(r==null?void 0:r.effectiveTheme)??"dark",shellThemeMode:(r==null?void 0:r.themeMode)??"system",...r!=null&&r.setThemeMode?{onShellThemeModeChange:r.setThemeMode}:{},onShellStateChange:wa,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:$o,...cr?{composerProps:cr}:{},...ur?{shellComposerProps:ur}:{}})}function Kr(){const t=Ze(),[s,a]=n.useState(""),[r,o]=n.useState(Ke),[l,i]=n.useState([]),[c,f]=n.useState(!0),[v,b]=n.useState(!1),[g,S]=n.useState(null);n.useEffect(()=>{let p=!1;return f(!0),is().then(L=>{var D,I;if(p)return;i(L);const M=((D=L.find(A=>A.isDefault&&A.enabled))==null?void 0:D.provider)??((I=L.find(A=>A.enabled))==null?void 0:I.provider)??Ke;o(M)}).catch(()=>{p||i([])}).finally(()=>{p||f(!1)}),()=>{p=!0}},[]);const y=n.useMemo(()=>l.length>0?l:[{provider:Ke,displayName:vr[Ke].displayName,enabled:!0}],[l]);async function m(p){p.preventDefault();const L=s.trim();if(!L){S("Session ID is required.");return}b(!0),S(null);try{const M=await Di({sessionId:L,provider:r});t($e(M.thread.id))}catch(M){M instanceof ae?S(M.payload.message):S(M instanceof Error?M.message:"Unable to import session.")}finally{b(!1)}}return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"host-page-eyebrow text-xs uppercase tracking-[0.3em]",children:"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:m,className:"host-panel space-y-5 rounded-lg border p-5 sm: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:r,onChange:p=>o(p.target.value),disabled:v||c,className:"host-form-control mt-2 w-full rounded-lg border px-4 py-3 outline-none transition",children:y.map(p=>e.jsxs("option",{value:p.provider,children:[p.displayName||vr[p.provider].displayName,p.enabled?"":" (not ready)"]},p.provider))})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"session-id",className:"host-form-label text-sm font-medium",children:"Session ID"}),e.jsx("input",{id:"session-id",value:s,onChange:p=>a(p.target.value),placeholder:"019d6fb7-7033-7a30-a2c7-74d0919e87d4",className:"host-form-control mt-2 w-full rounded-lg border px-4 py-3 outline-none transition"})]}),g&&e.jsx("div",{className:"host-error rounded-lg border px-4 py-3 text-sm",children:g}),e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:e.jsx("button",{type:"submit",disabled:v,className:"ui-action-primary rounded-lg px-5 py-3 font-medium transition disabled:cursor-not-allowed",children:v?"Importing...":"Import Session"})})]})]})}function Vn({eyebrow:t,title:s,description:a,children:r,maxWidthClassName:o="max-w-2xl"}){return e.jsx("div",{className:"flex min-h-[calc(100vh-2rem)] items-start justify-center py-[calc(env(safe-area-inset-top)+3.75rem)] sm:items-center sm:py-[calc(env(safe-area-inset-top)+2rem)]",children:e.jsxs("section",{className:`host-panel w-full ${o} overflow-hidden rounded-lg border shadow-[var(--theme-shadow)]`,children:[e.jsxs("header",{className:"border-b border-[var(--theme-border)] px-5 py-4 sm:px-6",children:[e.jsx("p",{className:"host-page-eyebrow text-xs uppercase tracking-[0.22em]",children:t}),e.jsx("h1",{className:"host-page-title mt-2 text-xl font-semibold tracking-normal sm:text-2xl",children:s}),a?e.jsx("p",{className:"host-page-description mt-2 max-w-2xl text-sm leading-6",children:a}):null]}),e.jsx("div",{className:"px-5 py-5 sm:px-6",children:r})]})})}function Yr(){const t=Ze(),[s]=Qs(),a=s.get("workspaceId"),r=s.get("title");function o(){if(window.history.length>1){t(-1);return}if(a){t(Pt(a));return}t(fs())}return e.jsx(Vn,{eyebrow:"New Thread",title:"Start a backend session",description:"Choose the workspace, model, and approval mode that should back the new thread.",maxWidthClassName:"max-w-3xl",children:e.jsx(ma,{initialWorkspaceId:a,initialTitle:r,onCancel:o,onCreated:l=>t($e(l.id))})})}function Uc(t){return ls(t)}function Dc({getThreadHref:t,onOpenThread:s,getNewThreadHref:a,renderThreadLink:r,onCloseAppNavigation:o,...l}){const i=Ze(),c=Ut(),f=o??(c==null?void 0:c.closeNav),v=l.effectiveTheme??(c==null?void 0:c.effectiveTheme),b=l.themeMode??(c==null?void 0:c.themeMode),g=l.onThemeModeChange??(c==null?void 0:c.setThemeMode);return e.jsx(Jo,{...l,workspaceReturnHref:l.workspaceReturnHref??fs(),globalSettingsContent:l.globalSettingsContent??e.jsx(na,{embedded:!0}),...v?{effectiveTheme:v}:{},...b?{themeMode:b}:{},...g?{onThemeModeChange:g}:{},getThreadHref:t??(S=>$e(S)),onOpenThread:s??(S=>i($e(S))),getNewThreadHref:a??Uc,renderNewThreadDialogContent:l.renderNewThreadDialogContent??(({close:S,closeNavigation:y,currentWorkspaceId:m})=>e.jsx(ma,{variant:"dialog",initialWorkspaceId:m,onCancel:S,onCreated:p=>{S(),y(),i($e(p.id))}})),renderThreadLink:r??(({thread:S,children:y,className:m,onClick:p})=>e.jsx(Ue,{to:$e(S.id),className:m,onClick:p,children:y})),...f?{onCloseAppNavigation:f}:{}})}function zn({open:t,title:s,label:a,value:r,busy:o=!1,onChange:l,onCancel:i,onSubmit:c}){if(n.useEffect(()=>{if(!t)return;function v(b){b.key==="Escape"&&!o&&i()}return window.addEventListener("keydown",v),()=>{window.removeEventListener("keydown",v)}},[o,i,t]),!t)return null;function f(v){v.preventDefault(),c()}return sn.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:i,disabled:o,className:"ui-overlay-scrim absolute inset-0 backdrop-blur-sm disabled:cursor-not-allowed"}),e.jsxs("form",{role:"dialog","aria-modal":"true","aria-label":s,onSubmit:f,className:"host-dialog relative z-[1] w-full max-w-md rounded-lg border p-5 shadow-[var(--theme-shadow)] 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:i,disabled:o,className:"host-icon-button inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full border transition disabled:cursor-not-allowed disabled:opacity-60",children:e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-current",children:e.jsx("path",{d:"M3.22 2.47 8 7.25l4.78-4.78 1.06 1.06L9.06 8.31l4.78 4.78-1.06 1.06L8 9.37l-4.78 4.78-1.06-1.06 4.78-4.78-4.78-4.78 1.06-1.06Z"})})})]}),e.jsxs("div",{className:"mt-5",children:[e.jsx("label",{htmlFor:"rename-dialog-input",className:"host-form-label text-sm font-medium",children:a}),e.jsx("input",{id:"rename-dialog-input","aria-label":a,autoFocus:!0,value:r,onChange:v=>l(v.target.value),className:"host-form-control mt-2 w-full rounded-lg 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:i,disabled:o,className:"host-secondary-button rounded-lg 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:o||!r.trim(),className:"ui-action-success rounded-lg px-4 py-2 text-sm font-medium transition disabled:cursor-not-allowed",children:"Save"})]})]})]}),document.body)}function Zr(){const[t]=Qs(),s=Ze(),a=Ut(),r=t.get("workspaceId"),[o,l]=n.useState([]),[i,c]=n.useState([]),[f,v]=n.useState(null),[b,g]=n.useState(!0),[S,y]=n.useState(null),[m,p]=n.useState(null),[L,M]=n.useState(""),[D,I]=n.useState(null),[A,J]=n.useState(null),[Y,Z]=n.useState(!1),d=(a==null?void 0:a.defaultBackend)??Ke,B=n.useCallback(async()=>{g(!0),y(null);try{const[P,W,te]=await Promise.all([Nn(d).then(O=>O.status),ra(),aa()]);v(P),l(W),c(te)}catch(P){y(P instanceof Error?P.message:"Unable to load threads.")}finally{g(!1)}},[d]);n.useEffect(()=>{if(r===null)return;B();const P=In(W=>{l(te=>te.map(O=>O.id===W.threadId?{...O,status:W.type==="thread.updated"&&typeof W.payload.status=="string"?W.payload.status:O.status,lastError:(W.type==="thread.turn.failed"||W.type==="thread.turn.completed")&&typeof W.payload.error=="string"?W.payload.error:O.lastError,title:W.type==="thread.updated"&&typeof W.payload.title=="string"?W.payload.title:O.title}:O))});return()=>{P.close()}},[B,r]);const Q=Object.fromEntries(i.map(P=>[P.id,P.label])),_=i.find(P=>P.id===r)??null,re=n.useMemo(()=>r?o.filter(P=>P.workspaceId===r):[],[r,o]),oe=re.filter(P=>P.status==="running").length,ve=r?ls(r):ls();if(qn({enabled:r!==null,setThreads:l}),r===null)return e.jsx(os,{to:fs(),replace:!0});function ce(){switch(f==null?void 0:f.state){case"ready":return"bg-teal-300 shadow-[0_0_0_3px_rgba(94,234,212,0.14)]";case"starting":return"bg-[var(--status-warning-fg)] shadow-[0_0_0_3px_var(--status-warning-bg)]";case"degraded":case"failed":return"bg-rose-400 shadow-[0_0_0_3px_rgba(251,113,133,0.14)]";default:return"bg-slate-500 shadow-[0_0_0_3px_rgba(100,116,139,0.14)]"}}async function Ne(P,W){try{const te=await Tn(P,{title:W});l(O=>O.map(K=>K.id===te.id?{...K,title:te.title,updatedAt:te.updatedAt}:K))}catch(te){throw y(te instanceof Error?te.message:"Unable to rename thread."),te}}async function be(){if(!m)return;const P=L.trim();if(P){I(m);try{await Ne(m,P),p(null),M("")}finally{I(null)}}}async function ke(){if(A){Z(!0);try{await En(A.id),l(P=>P.filter(W=>W.id!==A.id)),J(null)}catch(P){y(P instanceof Error?P.message:"Unable to delete thread.")}finally{Z(!1)}}}return e.jsx(Dc,{threads:o,workspaceLabels:Q,status:f,loading:b,error:S,viewportConstrained:r!==null,showMobileAppMenu:!0,showMobileThreadNavToggle:!1,showMobileNewThreadShortcut:!1,currentWorkspaceId:r,currentWorkspaceLabel:(_==null?void 0:_.label)??null,onRenameThread:Ne,onDeleteThread:J,children:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"host-panel flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border shadow-[var(--theme-shadow)]",children:[e.jsx("div",{className:"border-b border-[var(--theme-border)] px-4 py-3 sm:px-6 sm:py-4",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("h2",{className:"host-page-title min-w-0 truncate text-base font-semibold sm:text-lg",title:_?`${_.label} threads`:"All threads",children:_?_.label:"All Threads"}),e.jsx(Ue,{to:ve,className:"ui-action-primary inline-flex h-9 shrink-0 items-center rounded-lg 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-lg 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 ${ce()}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"host-muted truncate text-[11px] uppercase tracking-[0.22em]",children:"Supervisor"}),e.jsx("p",{className:"host-soft truncate text-sm",children:(f==null?void 0:f.lastError)??((f==null?void 0:f.state)==="ready"?"Ready":(f==null?void 0:f.state)??"Checking")})]})]})}),!b&&!S&&re.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:[re.length," total"]}),oe>0&&e.jsxs("span",{className:"host-muted text-xs",children:["· ",oe," running"]})]}),e.jsx("div",{className:"mt-3 min-h-0 flex-1",children:e.jsx(Ko,{threads:re,currentWorkspaceId:r,workspaceLabels:Q,onOpenThread:P=>s($e(P)),onBeginRenameThread:P=>{p(P.id),M(P.title)},onDeleteThread:P=>J(P),scrollable:!0,maxHeightClassName:"max-h-full",showDeleteButton:!0,showSessionCopyButton:!0})})]}),!b&&!S&&re.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(zn,{open:m!==null,title:"Rename Thread",label:"Thread Title",value:L,busy:D!==null,onChange:M,onCancel:()=>{p(null),M("")},onSubmit:()=>void be()}),e.jsx(ea,{open:A!==null,title:"Delete Thread",description:A?`Delete ${al(A.title)} from supervisor. The backend session id will no longer appear in this workspace list.`:"",confirmLabel:"Delete Thread",busy:Y,onCancel:()=>{Y||J(null)},onConfirm:()=>void ke()})]})})}function Xr(t){const s=t.trim(),a=s.replace(/[\\/]+$/,"");if(!a)return"";if(Gn(s)){const o=(a.split(/[?#]/)[0]??a).split(/[/:]/).filter(Boolean).at(-1)??"";return o.endsWith(".git")?o.slice(0,-4):o}return a.split(/[\\/]/).filter(Boolean).at(-1)??""}function Gn(t){const s=t.trim();return/^https?:\/\/.+/i.test(s)||/^ssh:\/\/.+/i.test(s)||/^git@[^:]+:.+/.test(s)}function $c({initialPath:t="",initialLabel:s="",submitLabel:a="Save Workspace",error:r,busy:o=!1,surface:l=!0,onSubmit:i}){const c=Xr(t),[f,v]=n.useState(t),[b,g]=n.useState(s||c),[S,y]=n.useState(null),m=n.useRef(c);n.useEffect(()=>{const M=Xr(f);g(D=>!D.trim()||D===m.current?M:D),m.current=M},[f]);async function p(M){M.preventDefault();const D=f.trim();if(!D){y("Workspace path or Git URL is required.");return}y(null);const I=b.trim(),A=Gn(D)?"gitUrl":"absPath";await i(I?{[A]:D,label:I}:{[A]:D})}const L=l?"host-panel space-y-5 rounded-lg border p-5 sm:p-6":"space-y-5";return e.jsxs("form",{onSubmit:p,className:L,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:f,onChange:M=>v(M.target.value),placeholder:"test, /Users/name/project, or https://github.com/owner/repo.git",className:"host-form-control mt-2 w-full rounded-lg border px-4 py-3 outline-none transition"}),e.jsx("p",{className:"host-muted mt-2 text-xs",children:"A name such as “test” creates a folder under the configured workspace directory. Absolute paths register existing directories; Git URLs clone a repository."})]}),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:b,onChange:M=>g(M.target.value),placeholder:"Optional override",className:"host-form-control mt-2 w-full rounded-lg 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."})]}),(S||r)&&e.jsx("div",{className:"host-error rounded-lg border px-4 py-3 text-sm",children:S??r}),e.jsx("button",{type:"submit",disabled:o,className:"ui-action-primary rounded-lg px-5 py-3 font-medium transition disabled:cursor-not-allowed",children:o?"Saving...":a})]})}function Qr(){const t=Ze(),[s,a]=n.useState(null),[r,o]=n.useState(!1),[l,i]=n.useState(null);n.useEffect(()=>{jn().then(f=>i(f.devHome)).catch(()=>i(null))},[]);async function c(f){o(!0),a(null);try{const v="absPath"in f&&l&&/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(f.absPath)?{...f,absPath:`${l.replace(/\/$/,"")}/${f.absPath}`}:f,b=await rd(v);t(Pt(b.id))}catch(v){v instanceof ae?a(v.payload.message):a(v instanceof Error?v.message:"Unable to create workspace.")}finally{o(!1)}}return e.jsx(Vn,{eyebrow:"Add Workspace",title:"Create a workspace",description:"Enter a folder name to create it under the workspace directory, register an absolute path, or clone a Git repository.",children:e.jsx($c,{busy:r,error:s,submitLabel:"Create Workspace",surface:!1,onSubmit:c})})}function en(t){return Date.parse(t.lastOpenedAt??t.createdAt)}function Mc(t,s){return t.isFavorite!==s.isFavorite?t.isFavorite?-1:1:en(s)-en(t)}function Hc(t){return t?new Date(t).toLocaleString():"Never opened"}function _c(t,s=28){return t.length<=s?t:`...${t.slice(-(s-3))}`}function Bc({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 Wc(){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 tn(){const t=Ze(),[s,a]=n.useState([]),[r,o]=n.useState(!0),[l,i]=n.useState(null),[c,f]=n.useState(null),[v,b]=n.useState(null),[g,S]=n.useState(null),[y,m]=n.useState(""),[p,L]=n.useState(null),[M,D]=n.useState(null),[I,A]=n.useState(null),[J,Y]=n.useState(!1),[Z,d]=n.useState(!1),[B,Q]=n.useState(0);n.useEffect(()=>{let P=!1,W=null;const te=K=>{var k;return K.reason instanceof ae&&((k=K.reason.payload.details)==null?void 0:k.reason)==="hosted_sandbox_starting"},O=async()=>{const[K,k]=await Promise.allSettled([aa(),Tl()]);if(!P){if(K.status==="rejected"&&te(K)||k.status==="rejected"&&te(k)){d(!0),o(!0),b(null),f(null),Q(G=>G+1),W=setTimeout(()=>void O(),1500);return}d(!1),o(!1),K.status==="fulfilled"?(a(K.value),b(null)):b(K.reason instanceof Error?K.reason.message:"Unable to load workspaces."),k.status==="fulfilled"?(i(k.value),f(null)):f(k.reason instanceof Error?k.reason.message:"Unable to load supervisor config.")}};return O(),()=>{P=!0,W&&clearTimeout(W)}},[]);async function _(P){const W={...P,isFavorite:!P.isFavorite};a(te=>te.map(O=>O.id===P.id?W:O));try{const te=await ld(P.id,{isFavorite:!P.isFavorite});a(O=>O.map(K=>K.id===te.id?te:K))}catch(te){a(O=>O.map(K=>K.id===P.id?P:K)),b(te instanceof Error?te.message:"Unable to update workspace.")}}async function re(P){const W=y.trim();if(W){L(P);try{const te=await nd(P,{label:W});a(O=>O.map(K=>K.id===te.id?te:K)),S(null),m("")}catch(te){b(te instanceof Error?te.message:"Unable to rename workspace.")}finally{L(null)}}}function oe(P){S(P.id),m(P.label)}function ve(){S(null),m("")}function ce(P){t(Pt(P))}async function Ne(){if(I){Y(!0);try{await od(I.id,{confirmWorkspaceId:I.id,confirmLabel:I.label}),a(P=>P.filter(W=>W.id!==I.id)),A(null)}catch(P){b(P instanceof Error?P.message:"Unable to delete workspace.")}finally{Y(!1)}}}function be(P,W){(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),ce(W))}const ke=n.useMemo(()=>[...s].sort(Mc),[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-lg sm:border sm:px-4",children:e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 sm:gap-2",children:[e.jsx(la,{}),e.jsx(Ue,{to:wr("/threads/import"),className:"host-info-pill inline-flex h-8 shrink-0 items-center rounded-md 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(Ue,{to:wr("/workspaces/new"),className:"ui-action-primary inline-flex h-8 shrink-0 items-center rounded-md 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.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:[Z?e.jsxs("div",{"aria-live":"polite",className:"overflow-hidden rounded-lg border border-[var(--status-warning-border)] bg-[var(--theme-panel)]",role:"status",children:[e.jsxs("div",{className:"px-5 py-5",children:[e.jsx("p",{className:"text-sm font-semibold text-[var(--theme-fg)]",children:"Starting hosted VM"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Waiting for the supervisor to connect. This page will resume automatically."})]}),e.jsx("div",{className:"h-1 overflow-hidden bg-[var(--theme-muted)]",children:e.jsx("div",{className:"h-full w-1/3 animate-pulse bg-[var(--theme-accent-solid)]"})}),e.jsxs("p",{className:"px-5 py-3 text-xs text-[var(--theme-fg-muted)]",children:["Connection check ",B]})]}):r?e.jsx("div",{className:"host-empty-state rounded-lg border px-6 py-12 text-center",children:"Loading workspace registry..."}):null,v&&e.jsx("div",{className:"host-error rounded-lg border px-4 py-4",children:v}),!r&&!v&&s.length===0&&e.jsxs("div",{className:"host-empty-state rounded-lg 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."})]}),!r&&ke.length>0&&e.jsx("div",{className:"space-y-2 overflow-x-hidden",children:ke.map(P=>e.jsxs("article",{role:"link",tabIndex:0,onClick:()=>ce(P.id),onKeyDown:W=>be(W,P.id),className:"host-card relative overflow-hidden rounded-lg 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 ${P.label}`,title:"Delete workspace",onClick:W=>{W.stopPropagation(),A(P)},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(Wc,{})}),e.jsx("button",{type:"button","aria-label":P.isFavorite?`Unpin workspace ${P.label}`:`Pin workspace ${P.label}`,title:P.isFavorite?"Unpin workspace":"Pin workspace",onClick:W=>{W.stopPropagation(),_(P)},className:`inline-flex h-7 w-7 items-center justify-center rounded-full border transition ${P.isFavorite?"host-warning-pill":"host-icon-button"}`,children:e.jsx(Bc,{active:P.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:P.label,children:P.label}),e.jsx("button",{type:"button",onClick:W=>{W.stopPropagation(),oe(P)},"aria-label":`Rename workspace ${P.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":P.absPath,title:P.absPath,onClick:W=>{W.stopPropagation(),D(P.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:_c(P.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: ",Hc(P.lastOpenedAt)]})})]})})]},P.id))})]}),e.jsx(Fc,{config:l,error:c,vmStarting:Z,workspaceCount:s.length})]}),e.jsx(zn,{open:g!==null,title:"Rename Workspace",label:"Workspace Label",value:y,busy:p!==null,onChange:m,onCancel:ve,onSubmit:()=>g?re(g):void 0}),e.jsx(Yo,{open:M!==null,title:"Workspace Path",text:M??"",onClose:()=>D(null)}),e.jsx(ea,{open:I!==null,title:"Delete Workspace",description:I?`Delete ${I.label} from supervisor. This also removes its threads and local supervisor metadata.`:"",confirmLabel:"Delete Workspace",busy:J,onCancel:()=>{J||A(null)},onConfirm:()=>void Ne()})]})}function Fc({config:t,error:s,vmStarting:a,workspaceCount:r}){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-lg 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(ts,{label:"Workspace root",value:(t==null?void 0:t.workspaceRoot)??(a?"VM is starting…":"Loading...")}),e.jsx(ts,{label:"Environment",value:t?`${t.environment} · ${t.host}:${t.port}`:a?"Connecting automatically…":s??"Loading..."}),e.jsx(ts,{label:"Version",value:t?`${t.appName} ${t.appVersion}`:"Loading..."}),e.jsx(ts,{label:"Workspaces",value:String(r)})]})]}),s&&!a?e.jsx("section",{className:"rounded-lg 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 ts({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 Jn="remote-codex-theme-mode",Kn="remote-codex-default-backend",Yn="remote-codex-auto-collapse-completed-turns";function qc({children:t}){const s=n.useMemo(()=>({fetchPlugins:Ti,importPlugin:Ei,updatePlugin:Ii,deletePlugin:Ri}),[]);return e.jsx(Zo,{adapter:s,children:t})}function Vc(){if(typeof window>"u")return"system";const t=window.localStorage.getItem(Jn);return t==="light"||t==="dark"||t==="system"?t:"system"}function zc(){if(typeof window>"u")return Ke;const t=window.localStorage.getItem(Kn);return tl(t)??Ke}function Gc(){return typeof window>"u"?!0:window.localStorage.getItem(Yn)!=="false"}function Jc(t){return(t==null?void 0:t.trim())||"Remote Codex"}function Kc(t){return t==="/"||t==="/relay-portal"?"Relay Portal":t==="/relay-guide"?"Relay Setup":t==="/relay-admin"?"Relay Admin":t==="/relay-account"?"Account":t==="/relay-devices"?"Devices and Shared Sessions":t==="/workspaces"||/^\/devices\/[^/]+\/workspaces$/.test(t)?"Workspaces":t==="/workspaces/new"||/^\/devices\/[^/]+\/workspaces\/new$/.test(t)?"New Workspace":t==="/threads"||/^\/devices\/[^/]+\/threads$/.test(t)?"Threads":t==="/threads/import"||/^\/devices\/[^/]+\/threads\/import$/.test(t)?"Import Thread":t==="/threads/new"||/^\/devices\/[^/]+\/threads\/new$/.test(t)?"New Thread":/^\/threads\/[^/]+$/.test(t)||/^\/devices\/[^/]+\/threads\/[^/]+$/.test(t)?"Thread":null}function Yc(){const t=Lt();return n.useEffect(()=>{document.title=Jc(Kc(t.pathname))},[t.pathname]),null}function Zc(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Xc({themeMode:t,setThemeMode:s,effectiveTheme:a}){const[r,o]=n.useState(!1),[l,i]=n.useState(!1),[c,f]=n.useState(zc),[v,b]=n.useState(Gc),[g,S]=n.useState(null),y=Lt(),p=!(/^\/threads\/(?:import|new)$/.test(y.pathname)||/^\/devices\/[^/]+\/threads\/(?:import|new)$/.test(y.pathname))&&(/^\/threads\/[^/]+$/.test(y.pathname)||/^\/devices\/[^/]+\/threads\/[^/]+$/.test(y.pathname)),L=y.pathname==="/threads"||/^\/devices\/[^/]+\/threads$/.test(y.pathname),M=p||L,D=L||p,I=y.pathname==="/workspaces"||/^\/devices\/[^/]+\/workspaces$/.test(y.pathname);n.useEffect(()=>{o(!1)},[y.pathname,y.search]),n.useEffect(()=>{const Z=d=>{const B=d.detail;if(B.state==="connected"){S(null);return}S(Q=>({attempt:B.attempt,startedAt:(Q==null?void 0:Q.startedAt)??Date.now()}))};return window.addEventListener(Zs,Z),()=>window.removeEventListener(Zs,Z)},[]);function A(Z){f(Z),window.localStorage.setItem(Kn,Z)}function J(Z){b(Z),window.localStorage.setItem(Yn,Z?"true":"false")}const Y={navOpen:r,openNav:()=>o(!0),toggleNav:()=>o(Z=>!Z),closeNav:()=>o(!1),settingsOpen:l,openSettings:()=>{o(!1),i(!0)},closeSettings:()=>i(!1),themeMode:t,setThemeMode:s,effectiveTheme:a,defaultBackend:c,setDefaultBackend:A,autoCollapseCompletedTurns:v,setAutoCollapseCompletedTurns:J};return e.jsxs(Xo.Provider,{value:Y,children:[e.jsxs("div",{className:`bg-[var(--app-bg)] text-[var(--app-fg)] ${M?"fixed inset-0 overflow-hidden overscroll-none":"min-h-screen"}`,children:[g?e.jsxs("div",{"aria-live":"polite",className:"fixed inset-x-4 top-4 z-[80] mx-auto max-w-2xl overflow-hidden rounded-lg border border-[var(--status-warning-border)] bg-[var(--theme-panel)] shadow-[var(--theme-shadow)]",role:"status",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-[var(--theme-fg)]",children:"Starting hosted VM"}),e.jsx("p",{className:"truncate text-xs text-[var(--theme-fg-muted)]",children:"Waiting for the supervisor. Pages will resume automatically."})]}),e.jsxs("span",{className:"shrink-0 text-xs tabular-nums text-[var(--theme-fg-muted)]",children:["Check ",g.attempt]})]}),e.jsx("div",{className:"h-1 overflow-hidden bg-[var(--theme-muted)]",children:e.jsx("div",{className:"h-full w-1/3 animate-pulse bg-[var(--theme-accent-solid)]"})})]}):null,e.jsx("main",{className:`mx-auto w-full ${D?"max-w-none":"max-w-[1600px]"} ${M?"absolute inset-0 pb-0 sm:pb-4":"pb-4"} ${D?p?"pt-0":L?"pt-[env(safe-area-inset-top)] sm:pt-0":"pt-[calc(env(safe-area-inset-top)+4rem)] sm:pt-4":I?"pt-[env(safe-area-inset-top)] sm:pt-4":"pt-4"} ${M?"overflow-hidden overscroll-none px-0":"px-4 sm:px-6"}`,children:e.jsx("section",{className:`min-w-0 ${M?p?"h-full min-h-0 overflow-hidden overscroll-none":"h-full overflow-hidden overscroll-none":""}`,children:e.jsx(_o,{})})})]}),e.jsx(na,{})]})}function Qc({children:t}){const[s,a]=n.useState({status:"checking"});async function r(i){try{const c=await El();if(i!=null&&i())return;a(!c.authRequired||c.authenticated?{status:"authenticated"}:{status:"loginRequired",session:c,error:null})}catch(c){if(i!=null&&i())return;if(c instanceof ae&&c.statusCode===401){a({status:"loginRequired",session:{authenticated:!1,username:null,expiresAt:null,mode:"server",authRequired:!0},error:null});return}a({status:"unavailable",error:c instanceof Error?c.message:"Unable to check supervisor access."})}}n.useEffect(()=>{let i=!1;return r(()=>i),()=>{i=!0}},[]);async function o(i){await Il(i),a({status:"authenticated"})}function l(){a({status:"checking"}),r()}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-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-[var(--theme-shadow)] sm:p-6",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-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-fg-muted)]",children:s.error}),e.jsx("button",{className:"mt-5 h-11 rounded-lg 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:l,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-lg 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(An,{onLogin:o})]}):t}function eu({children:t}){var r;const[s,a]=n.useState({status:"checking"});return n.useEffect(()=>{let o=!1;return bt().then(l=>{o||a(l.authenticated?{status:"authenticated",session:l}:{status:"loginRequired"})}).catch(()=>{o||a({status:"loginRequired"})}),()=>{o=!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(os,{to:"/",replace:!0}):((r=s.session.user)==null?void 0:r.role)==="admin"?e.jsx(os,{to:"/relay-admin",replace:!0}):t}function tu({children:t}){return at()?e.jsx(eu,{children:t}):e.jsx(Qc,{children:t})}function Zn(){return at()?e.jsx(ec,{}):e.jsx(os,{to:"/workspaces",replace:!0})}function su({themeMode:t,setThemeMode:s,effectiveTheme:a}){return e.jsxs(an,{children:[e.jsx(je,{path:"/",element:e.jsx(Zn,{})}),e.jsxs(je,{element:e.jsx(Xc,{themeMode:t,setThemeMode:s,effectiveTheme:a}),children:[e.jsx(je,{path:"/workspaces",element:e.jsx(tn,{})}),e.jsx(je,{path:"/workspaces/new",element:e.jsx(Qr,{})}),e.jsx(je,{path:"/relay-account",element:e.jsx(ud,{})}),e.jsx(je,{path:"/relay-devices",element:e.jsx(Bd,{})}),e.jsx(je,{path:"/threads",element:e.jsx(Zr,{})}),e.jsx(je,{path:"/threads/import",element:e.jsx(Kr,{})}),e.jsx(je,{path:"/threads/new",element:e.jsx(Yr,{})}),e.jsx(je,{path:"/threads/:id",element:e.jsx(Jr,{})}),e.jsx(je,{path:"/devices/:relayDeviceId/workspaces",element:e.jsx(tn,{})}),e.jsx(je,{path:"/devices/:relayDeviceId/workspaces/new",element:e.jsx(Qr,{})}),e.jsx(je,{path:"/devices/:relayDeviceId/threads",element:e.jsx(Zr,{})}),e.jsx(je,{path:"/devices/:relayDeviceId/threads/import",element:e.jsx(Kr,{})}),e.jsx(je,{path:"/devices/:relayDeviceId/threads/new",element:e.jsx(Yr,{})}),e.jsx(je,{path:"/devices/:relayDeviceId/threads/:id",element:e.jsx(Jr,{})})]})]})}function au(){const[t,s]=n.useState(()=>Vc()),[a,r]=n.useState(()=>Zc()),o=t==="system"?a:t;return n.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const l=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>{r(l.matches?"dark":"light")};return i(),typeof l.addEventListener=="function"?l.addEventListener("change",i):l.addListener(i),()=>{typeof l.removeEventListener=="function"?l.removeEventListener("change",i):l.removeListener(i)}},[]),n.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Jn,t)},[t]),n.useEffect(()=>{const l=document.documentElement;l.dataset.themeMode=t,l.dataset.themeEffective=o,l.style.colorScheme=o},[o,t]),e.jsx("div",{className:"theme-shell theme-scrollbar",children:e.jsxs(Ho,{children:[e.jsx(Yc,{}),e.jsx(qc,{children:e.jsxs(an,{children:[e.jsx(je,{path:"/",element:e.jsx(Zn,{})}),e.jsx(je,{path:"/relay-guide",element:e.jsx(Qd,{})}),e.jsx(je,{path:"/relay-portal",element:e.jsx(tc,{})}),e.jsx(je,{path:"/relay-admin",element:e.jsx(md,{})}),e.jsx(je,{path:"/*",element:e.jsx(tu,{children:e.jsx(su,{themeMode:t,setThemeMode:s,effectiveTheme:o})})})]})})]})})}Bo.createRoot(document.getElementById("root")).render(e.jsx(Wo.StrictMode,{children:e.jsx(au,{})}));
|