remote-codex 0.11.49 → 0.11.50
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 +7 -5
- package/apps/supervisor-api/dist/index.js +5 -5
- package/apps/supervisor-web/dist/assets/index-BXypG9kl.js +22 -0
- package/apps/supervisor-web/dist/index.html +1 -1
- package/bin/remote-codex.mjs +4 -2
- package/package.json +1 -1
- package/packages/acp/src/catalog-runtime.test.ts +35 -0
- package/packages/acp/src/catalog-runtime.ts +5 -6
- package/scripts/service-manager.mjs +13 -0
- package/apps/supervisor-web/dist/assets/index-DZI1aSXo.js +0 -22
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import{j as e,r as n,L as Be,u as at,d as Wt,b as gn,e as ca,f as Xo,N as fs,B as Zo,h as vn,i as Ce,O as Qo,k as el,c as tl}from"./react-vendor-Dfg_6BLf.js";import{u as Ft,a as bn,t as sl,f as Ar,T as al,C as ua,b as rl,c as nl,d as ol,e as ll,g as il,L as dl,P as cl,h as ul,A as ml}from"./thread-ui-gcslNXur.js";import{l as q}from"./ui-vendor-CuR8GHb0.js";import"./graph-vendor-DVQUpZ8C.js";import"./terminal-vendor-C5bTa-Ka.js";import"./markdown-vendor-BG6PurxI.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 hl=["codex","claude","opencode","acp"],tt="codex",Ir={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"},acp:{displayName:"ACP Agent",description:"Agent Client Protocol runtime over stdio.",defaultTransport:"stdio",homeEnvVar:"ACP_HOME",commandEnvVar:"ACP_COMMAND",defaultHomeDir:".acp",defaultCommand:"grok agent stdio"}};function fl(t){return typeof t=="string"&&hl.includes(t)}function pl(t){return fl(t)?t:null}var Pr=15;function xl(t){return t.replace(/\s+/g," ").trim()}function gl(t){const s=xl(t);if(!s)return"";const a=Array.from(s);return a.length<=Pr?s:`${a.slice(0,Pr).join("")}...`}function vl(t,s){const a=new Set(t.map(r=>r.id));return[...s.filter(r=>!a.has(r.id)),...t]}function bl(t,s,a=null){var w;const r=new Set,o=s.reduceRight((d,h)=>(r.has(h.id)||(r.add(h.id),d.unshift(h)),d),[]),l=new Map(o.map(d=>[d.id,d])),i=o.filter(d=>d.items.some(h=>h.kind==="userMessage")),c=new Set,p=new Set,g=t.reduceRight((d,h)=>(p.has(h.id)||(p.add(h.id),d.unshift(h)),d),[]);for(const d of g){if(l.has(d.id)){c.add(d.id);continue}if(d.status!=="inProgress")continue;const h=(w=d.items.find(U=>U.kind==="userMessage"))==null?void 0:w.text.trim(),P=d.startedAt?Date.parse(d.startedAt):Number.NaN;if(!h||!Number.isFinite(P))continue;i.find(U=>{var z;const R=(z=U.items.find(te=>te.kind==="userMessage"))==null?void 0:z.text.trim(),L=U.startedAt?Date.parse(U.startedAt):Number.NaN;return R===h&&Number.isFinite(L)&&Math.abs(L-P)<=15e3})&&c.add(d.id)}const x=[...g.filter(d=>!l.has(d.id)&&!c.has(d.id)),...o];if(!a)return x;const k=x.find(d=>d.id===a);return k?[...x.filter(d=>d.id!==a),k]:x}const yl=["codex","claude","opencode","acp"],yn="codex",wn={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"},acp:{displayName:"ACP Agent",description:"Agent Client Protocol runtime over stdio.",defaultTransport:"stdio",homeEnvVar:"ACP_HOME",commandEnvVar:"ACP_COMMAND",defaultHomeDir:".acp",defaultCommand:"grok agent stdio"}},Or=15;function wl(t){return t.replace(/\s+/g," ").trim()}function jl(t){const s=wl(t);if(!s)return"";const a=Array.from(s);return a.length<=Or?s:`${a.slice(0,Or).join("")}...`}function $s(){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 Nl=[{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."}],jn={hostConfigFiles:[],toolboxItems:[],hookCommandTemplates:[],providerConfigFormat:"none",mcpConfigFormat:"none",configArchives:!1,buildRestart:!1},kl={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"},acp:{packageName:null,installCommand:null,updateCommand:null}};function Zs(t){const s=kl[t];return{packageName:s.packageName,installed:t==="codex",installedVersion:null,latestVersion:null,installCommand:s.installCommand,updateCommand:s.updateCommand,busy:!1,lastError:null}}function Sl(t,s){return{provider:t,displayName:s,description:`${s} backend descriptor is not available.`,enabled:!1,isDefault:t===yn,status:{state:"stopped",transport:wn[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:jn,installation:Zs(t)}}function Ds(t){const s=t.installation??Zs(t.provider);return{...t,installation:{...Zs(t.provider),...s}}}const kt=[...yl.map(t=>Sl(t,wn[t].displayName))];function Cl(t){var s;return((s=kt.find(a=>a.provider===t))==null?void 0:s.managementSchema)??jn}function Tl(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 El(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 Lt(t){return{path:t,exists:!1,originalContent:"",draftContent:"",loading:!1,saving:!1,error:null,saveMessage:null}}const Rl=/^\/devices\/([^/]+)(?:\/|$)/,Al=/^(?:\/devices\/[^/]+)?\/threads\/([^/?#]+)(?:[/?#]|$)/;function Nn(t){const s=Rl.exec(t);return s?decodeURIComponent(s[1]??""):null}function st(){return typeof window>"u"?null:Nn(window.location.pathname)}function Il(t){const s=Al.exec(t);return s?decodeURIComponent(s[1]??""):null}function Pl(){return typeof window>"u"?null:Il(window.location.pathname)}function qt(t,s){if(!s)return t;const a=t.startsWith("/")?t:`/${t}`;return`/devices/${encodeURIComponent(s)}${a}`}function Lr(t){return qt(t,st())}function Qs(t,s){return qt(`/threads/${encodeURIComponent(t)}`,s)}function Fe(t){return Qs(t,st())}function Ol(t,s){const a=t?`?workspaceId=${encodeURIComponent(t)}`:"";return qt(`/threads${a}`,s)}function Ht(t){return Ol(t,st())}function Ll(t,s){const a=t?`?workspaceId=${encodeURIComponent(t)}`:"";return qt(`/threads/new${a}`,s)}function ps(t){return Ll(t,st())}function ea(t){return qt("/workspaces",t)}function ws(){return ea(st())}class ie extends Error{constructor(s,a){super(a.message),this.statusCode=s,this.payload=a}}const ta="remote-codex-auth-token",sa="remote-codex-relay-token",aa="remote-codex-relay-admin-token",kn="remote-codex-relay-mode",ra="remote-codex-relay-device-id",na="remote-codex-relay-thread-id",oa="remote-codex:hosted-vm-wake";function Ur(t){typeof window<"u"&&window.dispatchEvent(new CustomEvent(oa,{detail:t}))}function Ul(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 Sn(){return typeof window>"u"?null:window.localStorage.getItem(ta)}function $l(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(ta,t);return}window.localStorage.removeItem(ta)}}function Cn(){return typeof window>"u"?null:window.localStorage.getItem(sa)}function Dl(){return typeof window>"u"?null:window.localStorage.getItem(aa)}function ma(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(sa,t);return}window.localStorage.removeItem(sa)}}function Tn(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(aa,t);return}window.localStorage.removeItem(aa)}}function St(){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(kn)==="true"}function Ye(){typeof window>"u"||window.localStorage.setItem(kn,"true")}function ut(){return St()}function En(){return typeof window>"u"?null:st()??window.localStorage.getItem(ra)}function cs(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(ra,t);return}window.localStorage.removeItem(ra)}}function Ml(){return typeof window>"u"?null:Pl()??window.localStorage.getItem(na)}function us(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(na,t);return}window.localStorage.removeItem(na)}}function ha(t){if(!St())return t;if(t.startsWith("/api/")){const s=En();return s?`/relay/devices/${encodeURIComponent(s)}${t}`:`/relay${t}`}return t}function Rn(t){return ha(t)}function _l(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 Hl(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 wt(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)??_l(t.status),message:r,...o?{details:o}:{}}}async function An(t){var o,l;const s=Hl(t.status,t.statusText),a=((l=(o=t.headers)==null?void 0:o.get)==null?void 0:l.call(o,"content-type"))??"",r=async()=>wt(t,await t.json(),s);if(a.includes("application/json"))try{return await r()}catch{return wt(t,null,s)}try{if(typeof t.text!="function")try{return await r()}catch{return wt(t,null,s)}const i=(await t.text()).trim();if(i.startsWith("{"))try{return wt(t,JSON.parse(i),s)}catch{}return wt(t,i?{message:`${s}
|
|
3
|
-
${i}`}:null,s)}catch{try{return await r()}catch{return wt(t,null,s)}}}async function I(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=Pn({...s,headers:r},a.auth);let l=0;for(;;){const c=await fetch(ha(String(t)),o);if(c.ok)return l>0&&Ur({state:"connected",attempt:l}),await c.json();const p=await An(c);if(!(c.status===503&&((i=p.details)==null?void 0:i.reason)==="hosted_sandbox_starting")||l>=60)throw new ie(c.status,p);l+=1,Ur({state:"starting",attempt:l}),await Ul(1500,o.signal)}}function Bl(t){const s=String(t);return s.includes("/exports/pdf")?s.includes("format=html")?"remote-codex-transcript.html":"remote-codex-transcript.pdf":"download"}function Wl(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 In(t,s){const a=await fetch(ha(String(t)),Pn(s));if(!a.ok){const o=await An(a);throw new ie(a.status,o)}const r=Wl(a.headers.get("content-disposition"))??Bl(t);return{blob:await a.blob(),filename:r}}function Pn(t={},s="default"){const a=new Headers(t.headers),r=St();if(s!=="none"&&!a.has("Authorization"))if(s==="relay-admin"){const o=Dl();o&&a.set("Authorization",`Bearer ${o}`)}else{const o=Cn(),l=Sn();r&&o?a.set("Authorization",`Bearer ${o}`):!r&&l&&a.set("Authorization",`Bearer ${l}`)}return{...t,credentials:t.credentials??"same-origin",headers:a}}function $r(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 Fl(){return I("/api/config/runtime")}function ql(){return I("/api/auth/session",{cache:"no-store"})}async function Vl(t){const s=await I("/api/auth/login",{method:"POST",body:JSON.stringify(t)});return $l(s.token??null),s}function Tt(){return I("/relay/auth/session",{cache:"no-store"})}async function zl(t){Ye();const s=await I("/relay/auth/login",{method:"POST",body:JSON.stringify(t)},{auth:"none"});return ma(s.token),s}function On(){return Ye(),I("/relay/auth/session",{cache:"no-store"},{auth:"relay-admin"})}async function Gl(t){Ye();const s=await I("/relay/auth/login",{method:"POST",body:JSON.stringify({identifier:t.username,password:t.password})},{auth:"none"});return Tn(s.token),s}async function Jl(){return Tn(null),On()}async function Kl(t){Ye();const s=await I("/relay/auth/register",{method:"POST",body:JSON.stringify(t)},{auth:"none"});return ma(s.token??null),s}async function Yl(){const t=await I("/relay/auth/logout",{method:"POST"});return ma(null),cs(null),us(null),t}function Ln(){return I("/relay/portal")}function Xl(t){const s=new URLSearchParams({deviceId:t.deviceId});return t.threadId&&s.set("threadId",t.threadId),t.workspaceId&&s.set("workspaceId",t.workspaceId),I(`/relay/access?${s.toString()}`)}function Zl(t){return I("/relay/devices",{method:"POST",body:JSON.stringify(t)})}function Ql(t){return I(`/relay/devices/${encodeURIComponent(t)}`,{method:"DELETE"})}function ei(t){return I("/relay/account",{method:"PATCH",body:JSON.stringify(t)})}function ti(t){return I("/relay/account/password",{method:"PATCH",body:JSON.stringify(t)})}function si(t){return I("/relay/shares",{method:"POST",body:JSON.stringify(t)})}function ai(t,s){return I(`/relay/shares/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(s)})}function Un(t){return I(`/relay/shares/${encodeURIComponent(t)}`,{method:"DELETE"})}function ri(t){return I("/relay/grants",{method:"POST",body:JSON.stringify(t)})}function ni(t,s){return I(`/relay/grants/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(s)})}function oi(t){return I(`/relay/grants/${encodeURIComponent(t)}`,{method:"DELETE"})}function li(t){const s=t?`?days=${encodeURIComponent(String(t))}`:"";return I(`/relay/admin${s}`,void 0,{auth:"relay-admin"})}function ii(){return I("/relay/admin/hosted-sandboxes/capability",void 0,{auth:"relay-admin"})}function di(){return I("/relay/admin/hosted-sandboxes",void 0,{auth:"relay-admin"})}function ci(){return I("/relay/admin/hosted-sandboxes/reconciliation",void 0,{auth:"relay-admin"})}function ui(){return I("/relay/admin/hosted-sandboxes/reconciliation/run",{method:"POST"},{auth:"relay-admin"})}function mi(t){return I(`/relay/admin/hosted-sandboxes/reconciliation/orphan-instances/${encodeURIComponent(t)}`,{method:"DELETE"},{auth:"relay-admin"})}function hi(t){return I(`/relay/admin/hosted-sandboxes/reconciliation/orphan-credentials/${encodeURIComponent(t)}`,{method:"DELETE"},{auth:"relay-admin"})}function fi(t){return I("/relay/admin/hosted-sandboxes",{method:"POST",body:JSON.stringify(t)},{auth:"relay-admin"})}function Dr(t,s){return I(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}/members`,{method:"PUT",body:JSON.stringify({assignedUserIds:s})},{auth:"relay-admin"})}function pi(t,s){return I(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}/settings`,{method:"PATCH",body:JSON.stringify(s)},{auth:"relay-admin"})}function Mr(t,s){return I(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}/${s}`,{method:"POST"},{auth:"relay-admin"})}function xi(t,s){return I(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}/snapshots`,{method:"POST",body:JSON.stringify({name:s})},{auth:"relay-admin"})}function gi(t){return I(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}/backends/codex/files`,void 0,{auth:"relay-admin"})}function vi(t,s){return I(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}/backends/codex/files`,{method:"PUT",body:JSON.stringify(s)},{auth:"relay-admin"})}function bi(t){return I(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}`,{method:"DELETE"},{auth:"relay-admin"})}function yi(t){return I("/relay/admin/settings/registration",{method:"PATCH",body:JSON.stringify(t)},{auth:"relay-admin"})}function wi(t,s){return I(`/relay/admin/users/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({enabled:s})},{auth:"relay-admin"})}function ji(t){return I(`/relay/admin/users/${encodeURIComponent(t)}`,{method:"DELETE"},{auth:"relay-admin"})}function Ni(t,s){return I(`/relay/admin/users/${encodeURIComponent(t)}/reset-password`,{method:"POST",body:JSON.stringify({password:s})},{auth:"relay-admin"})}function ki(t){return I(`/relay/admin/registrations/${encodeURIComponent(t)}/approve`,{method:"POST"},{auth:"relay-admin"})}function Si(t){return I(`/relay/admin/registrations/${encodeURIComponent(t)}/reject`,{method:"POST"},{auth:"relay-admin"})}function $n(){return I("/api/config/workspace-settings",{cache:"no-store"})}function Ci(t){return I("/api/config/workspace-settings",{method:"PATCH",body:JSON.stringify(t)})}function Ct(){return I("/api/agent-runtimes",{cache:"no-store"})}function Dn(t){return I(`/api/agent-runtimes/${encodeURIComponent(t)}/status`,{cache:"no-store"})}function Ti(t){return I(`/api/agent-runtimes/${encodeURIComponent(t)}/subscription-usage`,{cache:"no-store"})}function Ei(t){return I(`/api/agent-runtimes/${encodeURIComponent(t)}/restart`,{method:"POST"})}function la(t,s,a){return I(`/api/agent-runtimes/${encodeURIComponent(t)}/install`,{method:"POST",body:JSON.stringify({action:s,...a?{modelId:a}:{}})})}function ia(t){return fa(t)}function fa(t,s={}){const a=new URLSearchParams;s.agentId&&a.set("agentId",s.agentId),s.cwd&&a.set("cwd",s.cwd);const r=a.size>0?`?${a.toString()}`:"";return I(`/api/agent-runtimes/${encodeURIComponent(t)}/models${r}`,{cache:"no-store"})}function ms(t){return I(`/api/agent-runtimes/${encodeURIComponent(t)}/agents`,{cache:"no-store"})}function Mn(t,s){return I(`/api/config/providers/${encodeURIComponent(t)}/files/${encodeURIComponent(s)}`,{cache:"no-store"})}function _n(t,s,a){return I(`/api/config/providers/${encodeURIComponent(t)}/files/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function Ri(t){return I(`/api/config/providers/${encodeURIComponent(t)}/archives`,{cache:"no-store"})}function Ai(t,s={}){return I(`/api/config/providers/${encodeURIComponent(t)}/archives`,{method:"POST",body:JSON.stringify(s)})}function Ii(t,s,a){return I(`/api/config/providers/${encodeURIComponent(t)}/archives/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function Pi(t,s){return I(`/api/config/providers/${encodeURIComponent(t)}/archives/${encodeURIComponent(s)}/apply`,{method:"POST"})}function Oi(){return I("/api/service/build-restart",{method:"POST"})}function Li(){return I("/healthz",{cache:"no-store"})}function pa(){return I("/api/workspaces")}function Ui(t,s={}){const a=new URLSearchParams;s.path&&a.set("path",s.path);const r=a.size>0?`?${a.toString()}`:"";return I(`/api/workspaces/${encodeURIComponent(t)}/files/tree${r}`,{cache:"no-store"})}function $i(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)),I(`/api/workspaces/${encodeURIComponent(t)}/files/preview?${a.toString()}`,{cache:"no-store"})}function Di(t,s){const a=new URLSearchParams({path:s.path});return Rn(`/api/workspaces/${encodeURIComponent(t)}/files/raw?${a.toString()}`)}function Mi(t,s){const a=new URLSearchParams({path:s.path});return Rn(`/api/threads/${encodeURIComponent(t)}/assets/image?${a.toString()}`)}function _i(t,s){const a=new URLSearchParams({path:s.path});return In(`/api/workspaces/${encodeURIComponent(t)}/files/download?${a.toString()}`,{cache:"no-store"})}function Hi(t,s){const a=new FormData;return a.append("file",s.file,s.file.name),I(`/api/workspaces/${encodeURIComponent(t)}/files/upload`,{method:"POST",body:a})}function Bi(t,s){return I(`/api/workspaces/${encodeURIComponent(t)}/files`,{method:"PUT",body:JSON.stringify(s)})}function xa(){return I("/api/threads")}function _r(t,s={}){const a=new URLSearchParams;return s.limit!==void 0&&a.set("limit",String(s.limit)),s.beforeTurnId&&a.set("beforeTurnId",s.beforeTurnId),I(`/api/threads/${t}${a.size>0?`?${a.toString()}`:""}`)}function Wi(t,s){return I(`/api/threads/${t}/items/${encodeURIComponent(s)}/detail`)}function Fi(){return I("/api/plugins",{cache:"no-store"})}function qi(t){return I("/api/plugins/import",{method:"POST",body:JSON.stringify(t)})}function Vi(t,s){return I(`/api/plugins/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(s)})}function zi(t){return I(`/api/plugins/${encodeURIComponent(t)}`,{method:"DELETE"})}function Gi(t){return I(`/api/threads/${t}/export-turns`,{cache:"no-store"})}function Ji(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 Ki(t,s){return In(Ji(t,s),{cache:"no-store"})}function Yi(t){return I(`/api/threads/${t}/shell`)}function Xi(t){return I("/api/threads/start",{method:"POST",body:JSON.stringify(t)})}function Zi(t){return I("/api/threads/import",{method:"POST",body:JSON.stringify(typeof t=="string"?{sessionId:t}:t)})}function Qi(t,s={}){return I(`/api/threads/${t}/shell`,{method:"POST",...Object.keys(s).length>0?{body:JSON.stringify(s)}:{}})}function ed(t){return I(`/api/shells/${t}/terminate`,{method:"POST"})}function td(t,s){return I(`/api/shells/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Ms(t,s={}){return I(`/api/threads/${t}/resume`,{method:"POST",...Object.keys(s).length>0?{body:JSON.stringify(s)}:{}})}function sd(t){return I(`/api/threads/${t}/disconnect`,{method:"POST"})}function ad(t,s){const a=s.attachments??[];if(a.length===0)return I(`/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:$r(l,i),placeholder:l.placeholder}));r.append("attachmentManifest",JSON.stringify(o));for(const[l,i]of a.entries())r.append("attachments",i.file,$r(i,l));return I(`/api/threads/${t}/prompt`,{method:"POST",body:r})}function Hr(t,s={}){return I(`/api/threads/${t}/interrupt`,{method:"POST",body:JSON.stringify(s)})}function Hn(t,s){return I(`/api/threads/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Bn(t){return I(`/api/threads/${t}`,{method:"DELETE"})}function rd(t,s){return I(`/api/threads/${t}/pending-steers/${encodeURIComponent(s)}`,{method:"DELETE"})}function nd(t,s){return I(`/api/threads/${t}/pending-steers/${encodeURIComponent(s)}/steer`,{method:"POST"})}function od(t,s){return I(`/api/threads/${t}/settings`,{method:"PATCH",body:JSON.stringify(s)})}function ld(t){return I(`/api/threads/${t}/compact`,{method:"POST"})}function id(t){return I(`/api/threads/${t}/goal`,{cache:"no-store"})}function dd(t,s){return I(`/api/threads/${t}/goal`,{method:"PATCH",body:JSON.stringify(s)})}function cd(t){return I(`/api/threads/${t}/goal`,{method:"DELETE"})}function ud(t){return I(`/api/threads/${t}/fork-turns`,{cache:"no-store"})}function Br(t,s){return I(`/api/threads/${t}/fork`,{method:"POST",body:JSON.stringify(s)})}function md(t){return I(`/api/threads/${t}/skills`,{cache:"no-store"})}function hd(t){return I(`/api/threads/${t}/mcp-servers`,{cache:"no-store"})}function fd(t){return I(`/api/threads/${t}/hooks`,{cache:"no-store"})}function pd(t,s){return I(`/api/threads/${t}/hooks`,{method:"POST",body:JSON.stringify(s)})}function xd(t,s){return I(`/api/threads/${t}/hooks`,{method:"PUT",body:JSON.stringify(s)})}function gd(t,s){return I(`/api/threads/${t}/hooks/trust`,{method:"POST",body:JSON.stringify(s)})}function vd(t,s){return I(`/api/threads/${t}/hooks/untrust`,{method:"POST",body:JSON.stringify(s)})}function bd(t,s,a){return I(`/api/threads/${t}/requests/${encodeURIComponent(s)}/respond`,{method:"POST",body:JSON.stringify(a)})}function yd(t){return I("/api/workspaces",{method:"POST",body:JSON.stringify(t)})}function wd(t,s){return I(`/api/workspaces/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function jd(t,s){return I(`/api/workspaces/${t}`,{method:"DELETE",body:JSON.stringify(s)})}function Nd(t,s){return I(`/api/workspaces/${t}/favorite`,{method:"POST",body:JSON.stringify(s)})}function Wn(t){const s=window.location.protocol==="https:"?"wss:":"ws:",a=new WebSocket(Fn(s));return a.addEventListener("message",r=>{try{const o=JSON.parse(r.data);Sd(o)&&t(o)}catch{}}),a}function kd(t={}){const s=window.location.protocol==="https:"?"wss:":"ws:",a=new WebSocket(Fn(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 Fn(t){const s=new URL(`${t}//${window.location.host}/ws`);if(St()){const l=En();s.pathname=l?`/relay/devices/${encodeURIComponent(l)}/ws`:"/relay/ws"}const a=Sn(),r=Cn(),o=Ml();return St()&&r&&s.searchParams.set("relaySession",r),St()&&o&&s.searchParams.set("threadId",o),a&&s.searchParams.set("token",a),s.toString()}function Sd(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 _s(t){if(!t||typeof t!="object")return null;const s=t;return s.available===!1&&typeof s.unavailableReason=="string"?s.unavailableReason:null}function ga({embedded:t=!1}={}){const s=Ft(),a=bn(),[r,o]=n.useState(""),[l,i]=n.useState({busy:!1,message:null,error:null}),[c,p]=n.useState(!1),[g,N]=n.useState(null),[x,k]=n.useState({}),w=g?x[g]:null,[d,h]=n.useState({busy:!1,message:null,error:null}),[P,$]=n.useState([]),[U,R]=n.useState(kt),[L,z]=n.useState({loading:!1,saving:!1,error:null,operatingProvider:null,operatingAction:null,message:null}),[te,Q]=n.useState(null),[D,oe]=n.useState({devHomeDraft:"",loading:!1,saving:!1,message:null,error:null}),[Z,se]=n.useState({loading:!1,creating:!1,applyingId:null,renamingId:null,renameDraft:"",message:null,error:null}),u=(s==null?void 0:s.themeMode)??"system",K=t||!!(s!=null&&s.settingsOpen);async function Re(){const v=r.trim();if(!(!v||l.busy)){i({busy:!0,message:null,error:null});try{await a.importPluginManifest({manifestJson:v,enabled:!0}),o(""),i({busy:!1,message:"Plugin manifest imported.",error:null})}catch(C){i({busy:!1,message:null,error:C instanceof Error?C.message:"Unable to import plugin manifest."})}}}const ee=(s==null?void 0:s.effectiveTheme)??"dark",Ae=(s==null?void 0:s.autoCollapseCompletedTurns)??!0,Pe=(s==null?void 0:s.defaultBackend)??yn,Le=a.plugins.filter(v=>v.enabled).length,V=a.loading?"Loading...":`${Le}/${a.plugins.length} enabled`,M=U.find(v=>v.provider===Pe)??kt.find(v=>v.provider===Pe)??kt[0],ae=M.managementSchema??Cl(M.provider),O=ae.hostConfigFiles;n.useEffect(()=>{if(!K||t||!s||!ae.configArchives)return;const v=s;function C(H){H.key==="Escape"&&v.closeSettings()}return window.addEventListener("keydown",C),()=>{window.removeEventListener("keydown",C)}},[ae.configArchives,t,K,s]),n.useEffect(()=>{if(!K)return;let v=!1;return z(C=>({...C,loading:!0,error:null})),Ct().then(C=>{if(v)return;const H=[...C.map(Ds),...kt.filter(re=>!C.some(be=>be.provider===re.provider))];R(H),z(re=>({...re,loading:!1}))}).catch(C=>{v||(R(kt),z(H=>({...H,loading:!1,error:C instanceof ie?C.message:"Unable to load backend settings."})))}),()=>{v=!0}},[K]),n.useEffect(()=>{if(!K)return;let v=!1;return oe(C=>({...C,loading:!0,message:null,error:null})),$n().then(C=>{v||(Q(C),oe(H=>({...H,devHomeDraft:C.devHome,loading:!1})))}).catch(C=>{v||oe(H=>({...H,loading:!1,error:C instanceof ie?C.message:"Unable to load workspace settings."}))}),()=>{v=!0}},[K]),n.useEffect(()=>{if(!K||!M.capabilities.management.hostConfigFiles)return;let v=!1;async function C(){k(re=>{const be={...re};for(const Ue of O)be[Ue.name]={...Lt(Ue.name),...re[Ue.name],loading:!0,saving:!1,error:null,saveMessage:null};return be});const H=await Promise.allSettled(O.map(async re=>({name:re.name,result:await Mn(M.provider,re.name)})));v||k(re=>{var Ue,A;const be={...re};for(const T of H){if(T.status==="fulfilled"){const{name:we,result:ve}=T.value;be[we]={path:ve.path,exists:ve.exists,originalContent:ve.content,draftContent:ve.content,loading:!1,saving:!1,error:null,saveMessage:null};continue}const ne=T.reason instanceof ie?T.reason.message:"Unable to load the file.",ge=((Ue=O[H.indexOf(T)])==null?void 0:Ue.name)??((A=O[0])==null?void 0:A.name);ge&&(be[ge]={...Lt(ge),...be[ge],loading:!1,saving:!1,error:ne,saveMessage:null})}return be})}return C(),()=>{v=!0}},[M.capabilities.management.hostConfigFiles,M.provider,O,K]),n.useEffect(()=>{if(!K)return;let v=!1;async function C(){se(H=>({...H,loading:!0,error:null,message:null}));try{const H=await Ri(M.provider);if(v)return;$(H),se(re=>({...re,loading:!1}))}catch(H){if(v)return;se(re=>({...re,loading:!1,error:H instanceof ie?H.message:"Unable to load config archives."}))}}return C(),()=>{v=!0}},[M.provider,ae.configArchives,K]);async function F(){if(!(d.busy||L.saving)){h({busy:!0,message:null,error:null});try{const v=await Ei(M.provider),C=Ds(v);h({busy:!1,message:C.status.state==="ready"?`${C.displayName} backend restarted.`:`${C.displayName} backend state: ${C.status.state}`,error:null}),R(H=>H.map(re=>re.provider===C.provider?C:re))}catch(v){h({busy:!1,message:null,error:v instanceof ie?v.message:"Unable to restart the app server."})}}}async function G(v,C){if(d.busy||L.saving)return;const H=U.find(re=>re.provider===v);z(re=>({...re,saving:!0,operatingProvider:v,operatingAction:C,message:null,error:null}));try{const re=await la(v,C),be=Ds(re);R(Ue=>Ue.map(A=>A.provider===be.provider?be:A)),z(Ue=>({...Ue,saving:!1,operatingProvider:null,operatingAction:null,message:be.installation.lastError?`${be.displayName} ${C==="install"?"installed":"updated"}, but requires attention:
|
|
4
|
-
${be.installation.lastError}`:`${be.displayName} ${C==="install"?"installed":"updated"}.`,error:null}))}catch(re){z(be=>({...be,saving:!1,operatingProvider:null,operatingAction:null,message:null,error:re instanceof ie?El(re):`Unable to ${C} ${(H==null?void 0:H.displayName)??v}.`}))}}async function ye(){if(!(d.busy||L.saving)){h({busy:!0,message:null,error:null});try{await Oi(),h({busy:!1,message:"Build and restart launched. The page may disconnect briefly.",error:null})}catch(v){h({busy:!1,message:null,error:v instanceof ie?v.message:"Unable to launch build and restart."})}}}async function $e(){const v=D.devHomeDraft.trim();if(!(!v||D.saving)){oe(C=>({...C,saving:!0,message:null,error:null}));try{const C=await Ci({devHome:v});Q(C),oe(H=>({...H,devHomeDraft:C.devHome,saving:!1,message:"Workspace defaults saved."}))}catch(C){oe(H=>({...H,saving:!1,error:C instanceof ie?C.message:"Unable to save workspace settings."}))}}}async function Xe(v){const C=x[v];if(!(!C||C.saving)){k(H=>({...H,[v]:{...Lt(v),...H[v],saving:!0,error:null,saveMessage:null}}));try{const H=await _n(M.provider,v,{content:C.draftContent});k(re=>({...re,[v]:{path:H.path,exists:H.exists,originalContent:H.content,draftContent:H.content,loading:!1,saving:!1,error:null,saveMessage:"Saved"}}))}catch(H){k(re=>({...re,[v]:{...Lt(v),...re[v],saving:!1,error:H instanceof ie?H.message:"Unable to save the file.",saveMessage:null}}))}}}async function fe(){if(!Z.creating){se(v=>({...v,creating:!0,message:null,error:null}));try{const v=await Ai(M.provider);$(C=>[v,...C]),se(C=>({...C,creating:!1,message:"Backup created."}))}catch(v){se(C=>({...C,creating:!1,error:v instanceof ie?v.message:"Unable to create a config backup."}))}}}async function f(v){if(!Z.applyingId){se(C=>({...C,applyingId:v.id,message:null,error:null}));try{const C=await Pi(M.provider,v.id);se(H=>({...H,applyingId:null,message:C.status.state==="ready"?`Applied "${C.archive.label}" and restarted ${M.displayName}.`:`Applied "${C.archive.label}". ${M.displayName} state: ${C.status.state}.`}))}catch(C){se(H=>({...H,applyingId:null,error:C instanceof ie?C.message:"Unable to apply the config archive."}))}}}async function j(v){const C=Z.renameDraft.trim();if(!(!C||Z.renamingId!==v.id)){se(H=>({...H,message:null,error:null}));try{const H=await Ii(M.provider,v.id,{label:C});$(re=>re.map(be=>be.id===v.id?H:be)),se(re=>({...re,renamingId:null,renameDraft:"",message:"Backup renamed."}))}catch(H){se(re=>({...re,error:H instanceof ie?H.message:"Unable to rename the config backup."}))}}}if(!K)return null;const X=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-3 grid gap-2",children:[a.plugins.map(v=>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:v.name}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-[var(--theme-fg-muted)]",children:v.description}),e.jsx("span",{className:"mt-2 block text-[10px] uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:[...v.capabilities.artifactTypes.map(C=>C.type),...v.capabilities.threadPanels.map(C=>C.kind??C.id)].join(", ")||"utility"}),e.jsx("span",{className:"mt-1 block text-[10px] uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:v.source==="imported"?"Imported manifest":"Built-in module"}),_s(v)?e.jsx("span",{className:"mt-1 block text-xs leading-5 text-amber-300",children:_s(v)}):null]}),e.jsx("input",{type:"checkbox",checked:v.enabled,disabled:_s(v)!==null,"aria-label":`${v.name} enabled`,onChange:C=>void a.setPluginEnabled(v.id,C.currentTarget.checked),className:"mt-1 h-4 w-4 shrink-0 accent-[var(--theme-accent-solid)] disabled:cursor-not-allowed disabled:opacity-50"})]},v.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:v=>{o(v.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 Re(),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})]}),ke=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($s,{})})]})}),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:"," ",ee,"."]})]})}),e.jsx("div",{className:"mt-3 grid gap-2 sm:grid-cols-3",children:Nl.map(v=>{const C=u===v.value;return e.jsxs("button",{type:"button",onClick:()=>s==null?void 0:s.setThemeMode(v.value),className:`block rounded-[1rem] border px-3 py-2.5 text-left transition ${C?"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:v.label}),C?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:v.description})]},v.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:Ae,onChange:v=>{var C;return(C=s.setAutoCollapseCompletedTurns)==null?void 0:C.call(s,v.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:V}),e.jsx("button",{type:"button",onClick:()=>p(!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:(te==null?void 0:te.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&&!te?"Loading...":(te==null?void 0:te.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:v=>oe(C=>({...C,devHomeDraft:v.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 $e(),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 F(),disabled:d.busy||L.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:d.busy?"Restarting...":"Restart"}),e.jsx("button",{type:"button",onClick:()=>void ye(),disabled:d.busy||L.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:d.busy?"Working...":"Build and restart"})]})]}),e.jsx("div",{className:"mt-3 grid gap-2",children:U.map(v=>{const C=v.installation,H=!C.installed&&!!C.installCommand,re=C.installed&&!!C.updateCommand,be=L.saving&&L.operatingProvider===v.provider,Ue=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:v.displayName}),e.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${v.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:v.enabled?"Ready":C.installed?v.status.state:"Not installed"})]}),e.jsxs("p",{className:"mt-1 truncate text-xs text-[var(--theme-fg-muted)]",children:["Version:"," ",C.installedVersion??(C.installed?"Installed":"Unavailable"),C.latestVersion?` · Latest: ${C.latestVersion}`:""]}),C.lastError?e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-rose-300",children:C.lastError}):null]}),H||re?e.jsx("button",{type:"button","aria-label":`${H?"Install":"Update"} ${v.displayName}`,onClick:()=>void G(v.provider,H?"install":"update"),disabled:d.busy||L.saving||!H&&!re,className:"shrink-0 rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-panel)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:be?L.operatingAction==="install"?"Installing...":"Updating...":Ue}):null]},v.provider)})}),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}):L.message?e.jsx("p",{className:`mt-2 whitespace-pre-line text-xs ${L.message.includes("requires attention")?"text-[var(--status-warning-fg)]":"text-emerald-300"}`,children:L.message}):L.error?e.jsx("p",{className:"mt-2 whitespace-pre-line text-xs text-rose-300",children:L.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:[M.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(v=>{const C=x[v.name]??{path:v.name,exists:!1,originalContent:"",draftContent:"",loading:!1},H=C.draftContent!==C.originalContent;return e.jsx("button",{type:"button",onClick:()=>N(v.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:v.label}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:v.description})]}),e.jsx("div",{className:"shrink-0",children:C.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"}):C.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"})})]})},v.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]})]}),ae.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:Z.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:Z.creating?"Creating...":"Create backup"})]}),Z.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:Z.error}):Z.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:Z.message}):null,e.jsx("div",{className:"mt-3 space-y-2",children:Z.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..."}):P.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."}):P.map(v=>{const C=Z.renamingId===v.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:[C?e.jsxs("div",{className:"flex max-w-xl gap-2",children:[e.jsx("input",{"aria-label":`Rename ${v.label}`,value:Z.renameDraft,onChange:H=>se(re=>({...re,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 ${v.label}`,onClick:()=>void j(v),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:()=>se(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:v.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 ",Tl(v.createdAt)]}),O.map(H=>{var re;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,":"," ",(re=v.files[H.name])!=null&&re.exists?"saved":"missing"]},H.name)})]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:()=>se(H=>({...H,renamingId:v.id,renameDraft:v.label,message:null,error:null})),disabled:C,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 f(v),disabled:Z.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:Z.applyingId===v.id?"Applying...":"Apply"})]})]})},v.id)})})]}):null]})})]});return t?e.jsxs("div",{className:"flex min-h-0 flex-col overflow-hidden",children:[ke,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:()=>p(!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:V})]}),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:()=>p(!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($s,{})})]})]}),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:ke}),g&&w?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:g}),e.jsx("p",{className:"mt-1 break-all font-mono text-xs text-[var(--theme-fg-muted)]",children:w.path})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[w.error?e.jsx("span",{className:"text-xs text-rose-300",children:w.error}):w.saveMessage?e.jsx("span",{className:"text-xs text-emerald-300",children:w.saveMessage}):null,e.jsx("button",{type:"button","aria-label":`Save ${g}`,onClick:()=>void Xe(g),disabled:w.loading||w.saving||w.draftContent===w.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:w.saving?"Saving...":"Save"}),e.jsx("button",{type:"button","aria-label":"Close File Editor",onClick:()=>N(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($s,{})})]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-4 sm:p-5",children:e.jsx("textarea",{"aria-label":`Edit ${g}`,value:w.draftContent,onChange:v=>k(C=>({...C,[g]:{...Lt(g),...C[g],draftContent:v.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:w.loading?"Loading...":`Edit ${g} here`})})]})}):null]})}function qn({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,p]=n.useState(null),[g,N]=n.useState(!1);async function x(k){k.preventDefault(),p(null),N(!0);try{await a({username:r,password:l})}catch(w){w instanceof ie?p(w.payload.message):p("Unable to sign in.")}finally{N(!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:x,className:"space-y-4",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-[var(--theme-fg-soft)]",children:"Username"}),e.jsx("input",{autoComplete:"username",autoFocus:!0,className:"mt-2 h-11 w-full rounded-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:g,name:"username",onChange:k=>o(k.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:g,name:"password",onChange:k=>i(k.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:g||!r.trim()||!l,type:"submit",children:g?"Signing in...":"Sign in"})]})]})})}function Hs(t,s){return t instanceof ie?t.payload.message:t instanceof Error?t.message:s}function Vn({className:t=""}){var Z;const[s,a]=n.useState(null),[r,o]=n.useState(""),[l,i]=n.useState(""),[c,p]=n.useState(""),[g,N]=n.useState(""),[x,k]=n.useState(!0),[w,d]=n.useState(!1),[h,P]=n.useState(!1),[$,U]=n.useState(null),[R,L]=n.useState(null),[z,te]=n.useState(!1);async function Q(){var se;k(!0),L(null);try{Ye();const u=await Tt();a(u),o(((se=u.user)==null?void 0:se.username)??"")}catch(u){L(Hs(u,"Unable to load account."))}finally{k(!1)}}n.useEffect(()=>{Q()},[]);async function D(se){se.preventDefault(),d(!0),L(null),U(null);try{const u=await ei({username:r});a(K=>K!=null&&K.authenticated?{...K,user:u}:K),o(u.username),U("Account updated.")}catch(u){L(Hs(u,"Unable to update account."))}finally{d(!1)}}async function oe(se){se.preventDefault(),P(!0),L(null),U(null);try{if(c!==g){L("New passwords do not match.");return}await ti({currentPassword:l,newPassword:c}),i(""),p(""),N(""),U("Password changed.")}catch(u){L(Hs(u,"Unable to change password."))}finally{P(!1)}}return e.jsx("div",{className:`space-y-5 ${t}`.trim(),children:x?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:[R?e.jsx(Wr,{tone:"danger",children:R}):null,$?e.jsx(Wr,{tone:"success",children:$}):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:((Z=s.user)==null?void 0:Z.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:se=>o(se.target.value),value:r})]}),e.jsxs("button",{className:"relay-button-primary inline-flex h-10 items-center justify-center gap-2",disabled:w||!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:()=>te(!0),type:"button",children:[z?e.jsx(q.CheckCircle2,{className:"h-4 w-4"}):e.jsx(q.MailCheck,{className:"h-4 w-4"}),z?"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:oe,children:[e.jsx(Bs,{label:"Current password",value:l,onChange:i}),e.jsx(Bs,{label:"New password",value:c,onChange:p}),e.jsx(Bs,{label:"Confirm password",value:g,onChange:N}),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:h||!l||c.length<8||!g,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 Td(){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(Be,{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(Vn,{})]})})}function Bs({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 Wr({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 Je(t){return t instanceof ie?t.payload.message:t instanceof Error?t.message:"Unable to update relay admin state."}function Ed(){const[t,s]=n.useState(null),[a,r]=n.useState(!0),[o,l]=n.useState(null),[i,c]=n.useState(!1),[p,g]=n.useState(null),[N,x]=n.useState("overview"),[k,w]=n.useState(7),[d,h]=n.useState(null),[P,$]=n.useState(null),[U,R]=n.useState([]),[L,z]=n.useState(null),[te,Q]=n.useState(!1),[D,oe]=n.useState(null),[Z,se]=n.useState(null);async function u(O=k,F={}){F.showLoading!==!1&&r(!0),l(null);try{Ye();const G=await li(O);s(G),h(G.settings),w(G.conversationWindowDays),c(!1)}catch(G){G instanceof ie&&(G.statusCode===401||G.statusCode===403)?(s(null),c(!0),l(null)):l(Je(G))}finally{r(!1)}}n.useEffect(()=>{u()},[]);async function K(O={}){O.showLoading!==!1&&Q(!0),oe(null);const[F,G,ye]=await Promise.allSettled([ii(),di(),ci()]);F.status==="fulfilled"?$(F.value):($(null),oe(Je(F.reason))),G.status==="fulfilled"?R(G.value.sandboxes):oe($e=>$e??Je(G.reason)),ye.status==="fulfilled"?z(ye.value):(z(null),oe($e=>$e??Je(ye.reason))),O.showLoading!==!1&&Q(!1)}n.useEffect(()=>{N==="hosted"&&K()},[N]),n.useEffect(()=>{if(N!=="hosted")return;const O=U.some(G=>["requested","creating","starting","provisioning","stopping","deleting"].includes(G.status)),F=window.setInterval(()=>void K({showLoading:!1}),O?2e3:15e3);return()=>window.clearInterval(F)},[N,U]);async function Re(O,F){se(O),oe(null);try{await F(),await K(),window.setTimeout(()=>void K(),750)}catch(G){oe(Je(G))}finally{se(null)}}const ee=n.useMemo(()=>{const O=(t==null?void 0:t.users)??[],F=(t==null?void 0:t.devices)??[];return{users:O.length,enabledUsers:O.filter(G=>G.enabled).length,devices:F.length,onlineDevices:F.filter(G=>G.connected).length,conversations:O.reduce((G,ye)=>G+ye.conversationCount,0),shares:(t==null?void 0:t.shares.filter(G=>!G.revokedAt).length)??0}},[t]);async function Ae(O,F){g(O),l(null);try{const G=await wi(O,F);s(ye=>qr(ye,G))}catch(G){l(Je(G))}finally{g(null)}}async function Pe(O){g(`delete:${O}`),l(null);try{await ji(O),await u(k,{showLoading:!1})}catch(F){l(Je(F))}finally{g(null)}}async function Le(O,F){g(`reset:${O}`),l(null);try{const G=await Ni(O,F);s(ye=>qr(ye,G))}catch(G){l(Je(G))}finally{g(null)}}async function V(O){if(O.preventDefault(),!!d){g("settings"),l(null);try{const F=await yi(d);s(G=>G&&{...G,registrationEnabled:F.registrationEnabled,settings:F.settings}),h(F.settings)}catch(F){l(Je(F))}finally{g(null)}}}async function M(O,F){g(`${F}:${O}`),l(null);try{F==="approve"?await ki(O):await Si(O),await u(k,{showLoading:!1})}catch(G){l(Je(G))}finally{g(null)}}async function ae(O){await Gl(O),await u(k)}return i?e.jsx(qn,{description:"Use the relay admin credentials for this server. This does not replace your normal relay account.",eyebrow:"Relay Admin",onLogin:ae}):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($d,{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 u(Number(O.target.value)),value:k,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(Be,{className:"relay-button-secondary",to:"/",children:"Relay home"}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:()=>void u(k),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(ns,{icon:e.jsx(q.Users,{className:"h-5 w-5"}),label:"Users",value:ee.users,detail:`${ee.enabledUsers} enabled`}),e.jsx(ns,{icon:e.jsx(q.Database,{className:"h-5 w-5"}),label:"Devices",value:ee.devices,detail:`${ee.onlineDevices} online`}),e.jsx(ns,{icon:e.jsx(q.Clock3,{className:"h-5 w-5"}),label:`Conversations, ${t.conversationWindowDays}d`,value:ee.conversations,detail:"Relay prompt/start events"}),e.jsx(ns,{icon:e.jsx(q.Share2,{className:"h-5 w-5"}),label:"Active shares",value:ee.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 ${N===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:()=>x(O),type:"button",children:Jd(O)},O))}),N==="overview"?e.jsx(Dd,{summary:t}):null,N==="users"?e.jsx(Md,{busyKey:p,onDeleteUser:Pe,onResetPassword:Le,onUpdateUser:Ae,users:t.users}):null,N==="devices"?e.jsx(_d,{devices:t.devices,users:t.users}):null,N==="hosted"?e.jsx(Rd,{busyKey:Z,capability:P,error:D,loading:te,onAction:Re,onRefresh:K,sandboxes:U,reconciliation:L,users:t.users}):null,N==="shares"?e.jsx(Hd,{shares:t.shares}):null,N==="settings"&&d?e.jsx(Bd,{busy:p==="settings",draft:d,onChange:h,onReviewRegistration:M,onSave:V,pending:t.pendingRegistrations,reviewBusyKey:p}):null]}):null]})]})}function Rd({busyKey:t,capability:s,error:a,loading:r,onAction:o,onRefresh:l,reconciliation:i,sandboxes:c,users:p}){var Q;const g=p.filter(D=>D.role==="user"&&D.enabled),[N,x]=n.useState([]),[k,w]=n.useState("Hosted Codex"),[d,h]=n.useState("standard"),[P,$]=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
|
-
`),[U,R]=n.useState(""),L=(s==null?void 0:s.available)===!0&&N.length>0;async function z(D){if(D.preventDefault(),!L)return;const oe=d==="large"?{cpuCount:2,memoryMiB:2048,diskGiB:12}:{cpuCount:1,memoryMiB:1536,diskGiB:10};await o("hosted:create",()=>fi({assignedUserIds:N,deviceName:k,imageVersion:"ubuntu-24.04-v5",resources:oe,backends:["codex"],codexFiles:{configToml:P,authJson:U}})),R("")}const te=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(Mt,{tone:te,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,(Q=s==null?void 0:s.alerts)==null?void 0:Q.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(Ad,{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:z,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:g.length?g.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:N.includes(D.id),disabled:!(s!=null&&s.available),onChange:oe=>x(Z=>oe.target.checked?[...Z,D.id]:Z.filter(se=>se!==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:[N.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=>w(D.target.value),required:!0,value:k})]}),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=>h(D.target.value),value:d,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(xs,{filename:"config.toml",language:"TOML",onChange:$,value:P}),e.jsx(xs,{filename:"auth.json",language:"JSON",onChange:R,value:U})]})]}),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:!L||!P.trim()||!U.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(Id,{busyKey:t,onAction:o,sandbox:D,users:g},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 Ad({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(Mt,{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",ui),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}`,()=>mi(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}`,()=>hi(i.credentialRef)),type:"button",children:"Delete orphan credential"})]},i.credentialRef))]})}function Id({busyKey:t,onAction:s,sandbox:a,users:r}){const[o,l]=n.useState(!1),[i,c]=n.useState(!1),[p,g]=n.useState(""),[N,x]=n.useState(!1),[k,w]=n.useState(()=>Date.now()),d=(t==null?void 0:t.endsWith(a.id))??!1,h=Od(a.status),P=a.assignedUsers.map(R=>R.userId),$=p.trim().toLowerCase(),U=r.filter(R=>!P.includes(R.id)).filter(R=>$?[R.id,R.username,R.email].some(L=>L.toLowerCase().includes($)):!1).slice(0,6);return n.useEffect(()=>{if(!a.runningSince)return;const R=window.setInterval(()=>w(Date.now()),3e4);return()=>window.clearInterval(R)},[a.runningSince]),n.useEffect(()=>{if(!N)return;const R=L=>{L.key==="Escape"&&x(!1)};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[N]),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(Mt,{tone:h,children:Ld(a.status)}),a.activeTurnCount>0?e.jsxs(Mt,{tone:"warning",children:[a.activeTurnCount," active turn",a.activeTurnCount===1?"":"s"]}):null,a.workspaceIsolationEnabled?e.jsx(Mt,{tone:"success",children:"Private workspaces"}):null]}),e.jsxs("p",{className:"mt-1 text-sm text-[var(--theme-fg-soft)]",children:[a.assignedUsers.map(R=>R.username).join(", "),e.jsx("span",{className:"mx-2 text-[var(--theme-fg-muted)]",children:"·"}),a.resources.cpuCount," CPU ·"," ",Ud(a.resources.memoryMiB)," ·"," ",a.resources.diskGiB," GiB"]}),e.jsxs("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:["Updated ",Ke(a.updatedAt),a.runningSince?` · running for ${Xd(a.runningSince,k)}`:"",a.idleDeadlineAt?` · idle stop ${Ke(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:d,onClick:()=>void s(`start:${a.id}`,()=>Mr(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:d||a.activeTurnCount>0||a.status!=="online",onClick:()=>void s(`stop:${a.id}`,()=>Mr(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:d||a.status!=="online"||a.activeTurnCount>0,onClick:()=>void s(`snapshot:${a.id}`,()=>xi(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:d,onClick:()=>x(!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:d,onClick:()=>void s(`delete:${a.id}`,()=>bi(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:d||a.activeTurnCount>0,onClick:()=>l(!0),type:"button",children:"Delete"})]})]}),N?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:()=>x(!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:()=>x(!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:d,onChange:R=>void s(`settings:${a.id}`,()=>pi(a.id,{workspaceIsolationEnabled:R.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:d,onClick:()=>{c(R=>!R),g("")},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:R=>g(R.target.value),placeholder:"Account ID, username, or email",value:p}),$?e.jsx("div",{className:"mt-2 overflow-hidden rounded-md border border-[var(--theme-border)]",children:U.length?U.map(R=>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:d,onClick:()=>void s(`members:${a.id}`,async()=>{await Dr(a.id,[...P,R.id]),c(!1),g("")}),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:R.username}),e.jsxs("span",{className:"block truncate text-xs text-[var(--theme-fg-muted)]",children:[R.email," · ",R.id]})]}),e.jsx("span",{className:"text-xs font-medium text-[var(--theme-accent-strong)]",children:"Add"})]},R.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(R=>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:R.username}),e.jsx("span",{className:"block truncate text-xs text-[var(--theme-fg-muted)]",children:R.email})]}),e.jsx("button",{"aria-label":`Remove ${R.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:d||P.length===1,onClick:()=>void s(`members:${a.id}`,()=>Dr(a.id,P.filter(L=>L!==R.userId))),title:P.length===1?"A hosted VM must keep at least one authorized user.":void 0,type:"button",children:"Remove"})]},R.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(Pd,{busy:d,onAction:s,sandbox:a})]})]})]}):null]})}function Pd({busy:t,onAction:s,sandbox:a}){const[r,o]=n.useState(!1),[l,i]=n.useState(!1),[c,p]=n.useState(null),[g,N]=n.useState(""),[x,k]=n.useState("");async function w(){i(!0),p(null);try{const d=await gi(a.id);N(d.configToml),k(d.authJson)}catch(d){p(Je(d))}finally{i(!1)}}return e.jsxs("details",{className:"mt-3",onToggle:d=>{const h=d.currentTarget.open;o(h),h&&!g&&!l&&a.status==="online"&&w()},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(xs,{filename:"~/.codex/config.toml",language:"TOML",onChange:N,value:g}),e.jsx(xs,{filename:"~/.codex/auth.json",language:"JSON",onChange:k,value:x}),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 w(),type:"button",children:"Reload"}),e.jsx("button",{className:"relay-button-primary min-h-11",disabled:t||!g.trim()||!x.trim(),onClick:()=>void s(`backend:${a.id}`,()=>vi(a.id,{configToml:g,authJson:x})),type:"button",children:"Save to VM"})]})]})]}):null]})}function xs({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 Mt({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 Od(t){return t==="online"?"success":t==="error"?"danger":["creating","starting","provisioning","stopping","deleting"].includes(t)?"warning":"neutral"}function Ld(t){return t.replace("_"," ").replace(/^./,s=>s.toUpperCase())}function Ud(t){return t%1024===0?`${t/1024} GiB`:`${(t/1024).toFixed(1)} GiB`}function ns({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 $d({onLogout:t}){const[s,a]=n.useState(null),[r,o]=n.useState(!1);n.useEffect(()=>{let c=!1;return On().then(p=>{c||a(p.authenticated?p:null)}).catch(()=>{c||a(null)}),()=>{c=!0}},[]);const l=(s==null?void 0:s.user)??null;if(!l)return null;async function i(){await Jl(),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:Zd(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 Dd({summary:t}){const s=[...t.users].sort(Yd("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(gt,{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:Ke(r.lastSeenAt)}),e.jsxs("p",{children:[r.conversationCount," conversations"]})]})]},r.id))})}),e.jsx(gt,{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(Wd,{device:r},r.id))}):e.jsx(js,{children:"No supervisors are connected."})})]})}function Md({busyKey:t,onDeleteUser:s,onResetPassword:a,onUpdateUser:r,users:o}){const[l,i]=n.useState(""),[c,p]=n.useState({key:"lastSeenAt",direction:"desc"}),[g,N]=n.useState(null),[x,k]=n.useState(null),w=n.useMemo(()=>{const h=Fr(l);return o.filter(P=>h?Fr(`${P.username} ${P.email}`).includes(h):!0).sort((P,$)=>Vd(P,$,c))},[l,c,o]);function d(h){p(P=>({key:h,direction:P.key===h&&P.direction==="desc"?"asc":"desc"}))}return e.jsxs(e.Fragment,{children:[e.jsxs(gt,{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:h=>i(h.target.value),placeholder:"Search username or email",value:l})]}),e.jsxs("p",{className:"text-sm text-[var(--theme-fg-muted)]",children:[w.length.toLocaleString()," of"," ",o.length.toLocaleString()," users"]})]}),e.jsxs(va,{minWidth:"68rem",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx(Ut,{active:c.key==="username",direction:c.direction,onClick:()=>d("username"),children:"User"}),e.jsx(Ut,{active:c.key==="enabled",direction:c.direction,onClick:()=>d("enabled"),children:"Status"}),e.jsx(Ut,{active:c.key==="lastSeenAt",direction:c.direction,onClick:()=>d("lastSeenAt"),children:"Last used"}),e.jsx(Ut,{active:c.key==="conversationCount",direction:c.direction,onClick:()=>d("conversationCount"),children:"Conversations"}),e.jsx(Ut,{active:c.key==="deviceCount",direction:c.direction,onClick:()=>d("deviceCount"),children:"Devices"}),e.jsx(_e,{children:"Role"}),e.jsx(_e,{children:"Actions"})]})}),e.jsx("tbody",{children:w.map(h=>e.jsxs("tr",{children:[e.jsxs(Ee,{strong:!0,children:[h.username,e.jsx("div",{className:"text-xs font-normal text-[var(--theme-fg-muted)]",children:h.email})]}),e.jsx(Ee,{children:e.jsx(zn,{active:h.enabled,children:h.enabled?"Enabled":"Disabled"})}),e.jsx(Ee,{children:Ke(h.lastSeenAt)}),e.jsx(Ee,{children:h.conversationCount.toLocaleString()}),e.jsx(Ee,{children:h.deviceCount.toLocaleString()}),e.jsx(Ee,{children:h.role}),e.jsx(Ee,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{className:"relay-button-secondary",disabled:t===h.id||h.role==="admin",onClick:()=>r(h.id,!h.enabled),type:"button",children:h.enabled?"Disable":"Enable"}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",disabled:t===`reset:${h.id}`||h.role==="admin",onClick:()=>N(h),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:${h.id}`||h.role==="admin",onClick:()=>k(h),type:"button",children:[e.jsx(q.Trash2,{className:"h-4 w-4"}),"Delete"]})]})})]},h.id))})]}),w.length?null:e.jsx(js,{children:"No users match the current search."})]}),g?e.jsx(Fd,{busy:t===`reset:${g.id}`,onClose:()=>N(null),onSubmit:async h=>{await a(g.id,h),N(null)},user:g}):null,x?e.jsx(qd,{busy:t===`delete:${x.id}`,confirmLabel:"Delete user",description:`Delete ${x.username}, their devices, shares, and access history. This cannot be undone.`,onClose:()=>k(null),onConfirm:async()=>{await s(x.id),k(null)},title:"Delete relay user"}):null]})}function _d({devices:t,users:s}){const[a,r]=n.useState("all"),[o,l]=n.useState("all"),[i,c]=n.useState("all"),[p,g]=n.useState("lastActivity"),[N,x]=n.useState("desc"),k=n.useMemo(()=>s.filter(d=>t.some(h=>h.ownerUserId===d.id)),[t,s]),w=n.useMemo(()=>t.filter(d=>a==="all"||d.ownerUserId===a).filter(d=>o==="all"||(o==="online"?d.connected:!d.connected)).filter(d=>i==="all"||Gd(vs(d),i)).sort((d,h)=>zd(d,h,p,N)),[i,t,N,a,p,o]);return e.jsxs(gt,{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:d=>r(d.target.value),value:a,children:[e.jsx("option",{value:"all",children:"All users"}),k.map(d=>e.jsx("option",{value:d.id,children:d.username},d.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:d=>l(d.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:d=>c(d.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:d=>g(d.target.value),value:p,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:d=>x(d.target.value),value:N,children:[e.jsx("option",{value:"desc",children:"Descending"}),e.jsx("option",{value:"asc",children:"Ascending"})]})]})]}),e.jsxs(va,{minWidth:"74rem",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx(_e,{children:"Device"}),e.jsx(_e,{children:"Owner"}),e.jsx(_e,{children:"Status"}),e.jsx(_e,{children:"Last activity"}),e.jsx(_e,{children:"Inventory"}),e.jsx(_e,{children:"Network"})]})}),e.jsx("tbody",{children:w.map(d=>{var h,P;return e.jsxs("tr",{children:[e.jsxs(Ee,{strong:!0,children:[d.name,e.jsx("div",{className:"text-xs font-normal text-[var(--theme-fg-muted)]",children:d.tokenPreview})]}),e.jsxs(Ee,{children:[e.jsx("span",{className:"font-medium text-[var(--theme-fg-soft)]",children:d.ownerUsername}),e.jsx("div",{className:"text-xs text-[var(--theme-fg-muted)]",children:d.ownerEmail})]}),e.jsx(Ee,{children:e.jsx(zn,{active:d.connected,children:d.connected?"Online":"Offline"})}),e.jsxs(Ee,{children:[Ke(vs(d)),e.jsxs("div",{className:"text-xs text-[var(--theme-fg-muted)]",children:["created ",Ke(d.createdAt)]})]}),e.jsxs(Ee,{children:[e.jsxs("span",{children:[d.workspaces.length.toLocaleString()," workspaces"]}),e.jsx("span",{className:"mx-2 text-[var(--theme-fg-muted)]",children:"·"}),e.jsxs("span",{children:[d.threads.length.toLocaleString()," threads"]}),e.jsx("div",{className:"mt-1 truncate text-xs text-[var(--theme-fg-muted)]",children:((h=d.workspaces[0])==null?void 0:h.label)??"No workspace metadata"}),e.jsx("div",{className:"truncate text-xs text-[var(--theme-fg-muted)]",children:((P=d.threads[0])==null?void 0:P.title)??"No thread metadata"})]}),e.jsxs(Ee,{children:[d.ipAddress??"IP unavailable",e.jsxs("div",{className:"text-xs text-[var(--theme-fg-muted)]",children:["heartbeat ",Ke(d.lastHeartbeatAt)]})]})]},d.id)})})]}),w.length?null:e.jsx(js,{children:"No devices match the selected filters."})]})}function Hd({shares:t}){return e.jsx(gt,{title:"Share relationships",detail:"Thread grants between relay users. Revoked grants remain visible for audit.",children:e.jsxs(va,{minWidth:"62rem",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx(_e,{children:"Owner"}),e.jsx(_e,{children:"Target"}),e.jsx(_e,{children:"Thread"}),e.jsx(_e,{children:"Device"}),e.jsx(_e,{children:"Permissions"}),e.jsx(_e,{children:"Last access"}),e.jsx(_e,{children:"Status"})]})}),e.jsx("tbody",{children:t.map(s=>e.jsxs("tr",{children:[e.jsx(Ee,{strong:!0,children:s.ownerUsername}),e.jsx(Ee,{children:s.targetUsername}),e.jsxs(Ee,{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(Ee,{children:s.deviceName}),e.jsxs(Ee,{children:[s.threadAccess," /"," ",Kd(s.workspaceAccess)]}),e.jsx(Ee,{children:Ke(s.lastAccessedAt)}),e.jsx(Ee,{children:s.revokedAt?"Revoked":s.expiresAt&&s.expiresAt<=new Date().toISOString()?"Expired":"Active"})]},s.id))})]})})}function Bd({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(gt,{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($t,{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($t,{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($t,{checked:s.googleAuthEnabled,disabled:!s.googleAuthAvailable,label:"Enable Google authentication",onChange:c=>a({...s,googleAuthEnabled:c})}),e.jsx($t,{checked:s.githubAuthEnabled,disabled:!s.githubAuthAvailable,label:"Enable GitHub authentication",onChange:c=>a({...s,githubAuthEnabled:c})}),e.jsx($t,{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(gt,{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," · ",Ke(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(js,{children:"No pending applications."})})]})}function Wd({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:Ke(t.connectedAt)})]}),e.jsxs("p",{children:["Heartbeat:"," ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children:Ke(t.lastHeartbeatAt)})]})]})}function gt({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 va({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 _e({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 Ut({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 Ee({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 $t({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 zn({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 js({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 Fd({busy:t,onClose:s,onSubmit:a,user:r}){const[o,l]=n.useState(""),[i,c]=n.useState(null);async function p(g){if(g.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:p,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:g=>l(g.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 qd({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 Fr(t){return t.trim().toLowerCase()}function Vd(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=gs(t.lastSeenAt,s.lastSeenAt):a.key==="conversationCount"?o=t.conversationCount-s.conversationCount:a.key==="deviceCount"?o=t.deviceCount-s.deviceCount:o=gs(t.createdAt,s.createdAt),o*r||t.username.localeCompare(s.username)}function zd(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=gs(vs(t),vs(s)):a==="createdAt"?l=gs(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 gs(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 vs(t){return t.lastHeartbeatAt??t.connectedAt??t.createdAt}function Gd(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 qr(t,s){return t&&{...t,users:t.users.map(a=>a.id===s.id?{...a,...s}:a)}}function Jd(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 Kd(t){switch(t){case"write":return"workspace write";case"read":return"workspace read";case"none":default:return"no workspace"}}function Yd(t){return(s,a)=>Date.parse(a[t]??"")-Date.parse(s[t]??"")}function Ke(t){return t?new Date(t).toLocaleString():"never"}function Xd(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 Zd(t){const s=(t==null?void 0:t.trim())??"";return s?Array.from(s).slice(0,2).join("").toUpperCase():"??"}function Qd(t){const s=(t==null?void 0:t.trim())??"";return s?Array.from(s).slice(0,2).join("").toUpperCase():"??"}function ba({className:t="",menuAlign:s="left"}){const a=at(),r=Wt(),[o,l]=n.useState(null),[i,c]=n.useState(!1),[p,g]=n.useState(!1);n.useEffect(()=>{if(!ut())return;let d=!1;return Tt().then(h=>{d||l(h.authenticated?h:null)}).catch(()=>{d||l(null)}),()=>{d=!0}},[r.pathname]),n.useEffect(()=>{c(!1),g(!1)},[r.pathname]);const N=(o==null?void 0:o.user)??null,x=n.useMemo(()=>Qd(N==null?void 0:N.username),[N==null?void 0:N.username]),k=p&&typeof document<"u"?gn.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:()=>g(!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(Vn,{})})]})}),document.body):null;if(!ut()||!N)return null;async function w(){await Yl(),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 ${N.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(d=>!d),type:"button",children:x}),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:N.username}),e.jsx("p",{className:"truncate text-xs text-[var(--theme-fg-muted)]",children:N.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),g(!0)},role:"menuitem",type:"button",children:[e.jsx(q.Settings,{className:"h-4 w-4"}),"Account settings"]}),e.jsxs(Be,{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 w(),role:"menuitem",type:"button",children:[e.jsx(q.LogOut,{className:"h-4 w-4"}),"Logout"]})]}):null,k]})}const ec=3e3,tc={unix:45679,windows:45680};function dt(t,s){return t instanceof ie?t.payload.message:t instanceof Error?t.message:s}function sc(t,s){return t?{...s,sharedWithMe:Vr(t.sharedWithMe,s.sharedWithMe),sharedByMe:Vr(t.sharedByMe,s.sharedByMe),sharedDevicesWithMe:Ws(t.sharedDevicesWithMe??[],s.sharedDevicesWithMe??[]),sharedThreadsWithMe:Ws(t.sharedThreadsWithMe??[],s.sharedThreadsWithMe??[]),grantsByMe:Ws(t.grantsByMe??[],s.grantsByMe??[])}:ac(s)}function ac(t){return{...t,sharedWithMe:t.sharedWithMe.map(da),sharedByMe:t.sharedByMe.map(da),sharedDevicesWithMe:(t.sharedDevicesWithMe??[]).map(hs),sharedThreadsWithMe:(t.sharedThreadsWithMe??[]).map(hs),grantsByMe:(t.grantsByMe??[]).map(hs)}}function Vr(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 da(r);const l=bs(r),i=bs(o);return{...r,threadTitle:l??i,workspaceLabel:r.workspaceLabel??o.workspaceLabel}})}function da(t){return{...t,threadTitle:bs(t)}}function Ws(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 hs(r);const l=Bt(r),i=Bt(o);return{...r,threadTitle:l??i,workspaceLabel:r.workspaceLabel??o.workspaceLabel,deviceName:((c=r.deviceName)==null?void 0:c.trim())||o.deviceName}})}function hs(t){return{...t,threadTitle:Bt(t)}}function rc(){const t=at(),[s,a]=ca(),[r,o]=n.useState(null),[l,i]=n.useState(""),[c,p]=n.useState(null),[g,N]=n.useState(null),[x,k]=n.useState(!0),[w,d]=n.useState(null),[h,P]=n.useState(null),[$,U]=n.useState(null),[R,L]=n.useState(null),[z,te]=n.useState(null),[Q,D]=n.useState(null),[oe,Z]=n.useState(null),[se,u]=n.useState(!1),K=n.useRef(!1),Re=n.useRef(null),ee=n.useCallback(async f=>{const j=(f==null?void 0:f.showLoading)??!0,X=(f==null?void 0:f.clearError)??!0;j&&k(!0),X&&P(null);try{Ye();const ke=await Ln();K.current=!0,o(v=>sc(v,ke))}catch(ke){(j||!K.current)&&P(dt(ke,"Unable to load devices."))}finally{j&&k(!1)}},[]);n.useEffect(()=>{ee();const f=window.setInterval(()=>{ee({showLoading:!1,clearError:!1})},ec);return()=>{window.clearInterval(f)}},[ee]),n.useEffect(()=>{const f=s.get("shareDevice");if(!f||!r||Re.current===f)return;const j=r.devices.find(ke=>ke.id===f);if(!j)return;Re.current=f,Z(j);const X=new URLSearchParams(s);X.delete("shareDevice"),a(X,{replace:!0})},[r,s,a]);async function Ae(f){f.preventDefault(),d("create"),P(null);try{const j=await Zl({name:l});p(j),i(""),u(!1),await ee({showLoading:!1})}catch(j){P(dt(j,"Unable to create device."))}finally{d(null)}}async function Pe(f){if(window.confirm(`Delete relay device "${f.name}"?`)){d(f.id),P(null);try{await Ql(f.id),(c==null?void 0:c.device.id)===f.id&&p(null),await ee({showLoading:!1})}catch(j){P(dt(j,"Unable to delete device."))}finally{d(null)}}}function Le(f){cs(f.id),us(null),t(ea(f.id))}function V(f){cs(f.deviceId),us(f.threadId),t(Qs(f.threadId,f.deviceId))}function M(f){if(cs(f.deviceId),us(f.threadId),f.threadId){t(Qs(f.threadId,f.deviceId));return}t(ea(f.deviceId))}async function ae(f,j){d(`grant:create:${f.id}`),P(null);try{await ri({...j,deviceId:f.id,scope:"device",workspaceScope:"all",workspaceIds:[]}),Z(null),await ee({showLoading:!1})}catch(X){P(dt(X,"Unable to share device."))}finally{d(null)}}async function O(f,j){d(`grant:${f.id}`),P(null);try{await ni(f.id,{...j,workspaceId:f.workspaceId,workspaceScope:f.workspaceScope,workspaceIds:f.workspaceIds}),D(null),await ee({showLoading:!1})}catch(X){P(dt(X,"Unable to update shared access."))}finally{d(null)}}async function F(f){if(window.confirm(`Remove sharing access for "${wa(f)}"?`)){d(`grant:${f.id}`),P(null);try{await oi(f.id),L(j=>j===f.id?null:j),await ee({showLoading:!1})}catch(j){P(dt(j,"Unable to remove shared access."))}finally{d(null)}}}async function G(f,j){d(`share:${f.id}`),P(null);try{await ai(f.id,{...j,workspaceId:f.workspaceId}),te(null),await ee({showLoading:!1})}catch(X){P(dt(X,"Unable to update shared thread."))}finally{d(null)}}async function ye(f){if(window.confirm(`Remove sharing access for "${ya(f)}"?`)){d(`share:${f.id}`),P(null);try{await Un(f.id),U(j=>j===f.id?null:j),await ee({showLoading:!1})}catch(j){P(dt(j,"Unable to remove shared thread access."))}finally{d(null)}}}async function $e(f,j){var ke;const X=f.token;if(!X){P("This device token is not available. Create a new device token for devices created before token storage was enabled.");return}try{await((ke=navigator.clipboard)==null?void 0:ke.writeText(Gn(X,j))),N(f.id),window.setTimeout(()=>{N(v=>v===f.id?null:v)},1600)}catch{}}const Xe=(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(ba,{}),e.jsx(Be,{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"})]}),h?e.jsx(uc,{tone:"danger",children:h}):null,c?e.jsx(cc,{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:()=>u(!0),type:"button",children:[e.jsx(q.Plus,{className:"h-4 w-4"}),"Add"]})]}),x?e.jsx("p",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-4 text-sm text-[var(--theme-fg-muted)]",children:"Loading devices..."}):r!=null&&r.devices.length?e.jsx("div",{className:"space-y-3",children:r.devices.map(f=>e.jsx(dc,{busy:w===f.id,copiedSetup:g===f.id,device:f,onConnect:()=>Le(f),onCopySetup:j=>void $e(f,j),onDelete:()=>void Pe(f),onShare:()=>Z(f),setupTokenAvailable:!!f.token},f.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(zr,{count:(r==null?void 0:r.sharedWithMe.length)??0,emptyText:"No sessions have been shared with this account yet.",loading:x,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:f=>e.jsx(Jr,{mode:"incoming",share:f,onOpen:()=>V(f)},f.id)}),e.jsx(Gr,{count:Xe.length,emptyText:"No devices have been shared with this account yet.",grants:Xe,loading:x,loadingText:"Loading shared devices...",title:"Shared devices",subtitle:"Devices another relay user has shared with this account.",renderGrant:f=>e.jsx(Kr,{grant:f,mode:"incoming",onOpen:()=>M(f)},f.id)}),e.jsx(Gr,{count:fe.length,emptyText:"No devices have been shared by this account yet.",grants:fe,loading:x,loadingText:"Loading shared devices...",title:"Shared devices by me",subtitle:"Devices this relay account has shared with other users.",renderGrant:f=>e.jsx(Kr,{busy:w===`grant:${f.id}`,expanded:R===f.id,grant:f,mode:"outgoing",onOpen:()=>M(f),onEdit:()=>D(f),onRevoke:()=>void F(f),onToggleAccess:()=>{L(j=>j===f.id?null:f.id)}},f.id)}),e.jsx(zr,{count:(r==null?void 0:r.sharedByMe.length)??0,emptyText:"No threads have been shared by this account yet.",loading:x,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:f=>e.jsx(Jr,{busy:w===`share:${f.id}`,expanded:$===f.id,mode:"outgoing",share:f,onOpen:()=>V(f),onEdit:()=>te(f),onRevoke:()=>void ye(f),onToggleAccess:()=>{U(j=>j===f.id?null:f.id)}},f.id)})]})]})]}),se?e.jsx(nc,{busy:w==="create",deviceName:l,onChangeDeviceName:i,onClose:()=>u(!1),onSubmit:Ae}):null,z?e.jsx(oc,{busy:w===`share:${z.id}`,share:z,onClose:()=>te(null),onSave:f=>void G(z,f)}):null,Q?e.jsx(ic,{busy:w===`grant:${Q.id}`,grant:Q,onClose:()=>D(null),onSave:f=>void O(Q,f)}):null,oe?e.jsx(lc,{busy:w===`grant:create:${oe.id}`,device:oe,onClose:()=>Z(null),onShare:f=>void ae(oe,f)}):null]})}function nc({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 zr({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(p=>o(p))}):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 Gr({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(p=>l(p))}):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 Jr({busy:t=!1,expanded:s=!1,mode:a,onEdit:r,onRevoke:o,onToggleAccess:l,share:i,onOpen:c}){var w,d;const p=ya(i),g=p,N=((w=i.label)==null?void 0:w.trim())||null,x=((d=i.workspaceLabel)==null?void 0:d.trim())||"Workspace unavailable",k=i.lastAccessedAt?`${i.lastAccessedByUsername??"unknown"} at ${Et(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:p}),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:x})]}),e.jsxs("p",{className:"truncate",children:["Thread:"," ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children:g})]}),N?e.jsxs("p",{className:"truncate",children:["Label:"," ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children:N})]}):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: ",k]}):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:Yn(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(h=>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:Xn(h.kind)}),e.jsx("span",{className:"block truncate",children:h.username})]}),e.jsx("span",{children:Et(h.accessedAt)})]},h.id))}):e.jsx("p",{className:"text-xs text-[var(--theme-fg-muted)]",children:"This shared thread has not been accessed yet."})}):null]})}function Kr({busy:t=!1,expanded:s=!1,grant:a,mode:r,onEdit:o,onOpen:l,onRevoke:i,onToggleAccess:c}){var d,h;const p=wa(a),g=fc(a),N=((d=a.workspaceLabel)==null?void 0:d.trim())||(a.scope==="device"?"All workspaces":"Workspace unavailable"),x=a.scope==="thread"?Bt(a)??"Thread unavailable":a.scope==="workspace"?"Workspace access":"Whole device",k=((h=a.label)==null?void 0:h.trim())||null,w=a.lastAccessedAt?`${a.lastAccessedByUsername??"unknown"} at ${Et(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:p}),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:g})]}),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:N})]}),e.jsxs("p",{className:"truncate",children:[a.scope==="thread"?"Thread":"Access",":"," ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children:x})]}),k?e.jsxs("p",{className:"truncate",children:["Label:"," ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children:k})]}):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: ",w]}):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:Yn(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(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:Xn(P.kind)}),e.jsx("span",{className:"block truncate",children:P.username})]}),e.jsx("span",{children:Et(P.accessedAt)})]},P.id))}):e.jsx("p",{className:"text-xs text-[var(--theme-fg-muted)]",children:"This shared access has not been used yet."})}):null]})}function oc({busy:t,onClose:s,onSave:a,share:r}){const[o,l]=n.useState(r.label??""),[i,c]=n.useState(r.threadAccess),[p,g]=n.useState(r.workspaceAccess),[N,x]=n.useState(Jn(r.expiresAt)),k=!r.workspaceId;function w(d){d.preventDefault(),a({label:o.trim()||null,threadAccess:i,workspaceAccess:k?"none":p,expiresAt:Kn(N)})}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:w,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 ",ya(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:d=>l(d.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:d=>c(d.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:k,onChange:d=>g(d.target.value),value:k?"none":p,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"})]})]}),k?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:d=>x(d.target.value),type:"datetime-local",value:N}),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 lc({busy:t,device:s,onClose:a,onShare:r}){const[o,l]=n.useState(""),[i,c]=n.useState(""),[p,g]=n.useState("read"),[N,x]=n.useState("read"),[k,w]=n.useState(!1);function d(h){h.preventDefault(),r({targetIdentifier:o.trim(),label:i.trim()||null,threadAccess:p,workspaceAccess:N,canCreateThreads:k})}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:d,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:h=>l(h.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:h=>c(h.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:h=>g(h.target.value),value:p,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:h=>x(h.target.value),value:N,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:k,className:"h-4 w-4 accent-[var(--theme-accent)]",onChange:h=>w(h.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 ic({busy:t,grant:s,onClose:a,onSave:r}){const[o,l]=n.useState(s.label??""),[i,c]=n.useState(s.threadAccess),[p,g]=n.useState(s.workspaceAccess),[N,x]=n.useState(s.canCreateThreads),[k,w]=n.useState(Jn(s.expiresAt)),d=s.scope!=="thread",h=s.scope==="thread"&&!s.workspaceId;function P($){$.preventDefault(),r({label:o.trim()||null,threadAccess:i,workspaceAccess:h?"none":p,canCreateThreads:d?N:!1,expiresAt:Kn(k)})}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:P,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 ",wa(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:$=>l($.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:$=>c($.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:h,onChange:$=>g($.target.value),value:h?"none":p,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"})]})]})]}),d?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:N,className:"h-4 w-4 accent-[var(--theme-accent)]",onChange:$=>x($.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:$=>w($.target.value),type:"datetime-local",value:k}),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 dc({device:t,busy:s,copiedSetup:a,onConnect:r,onCopySetup:o,onDelete:l,onShare:i,setupTokenAvailable:c}){const[p,g]=n.useState(!1),N=n.useRef(null),x=t.hostedStatus??null,k=t.connected||x==="stopped",w=x?hc(x):t.connected?"Online":"Offline";n.useEffect(()=>{if(!p)return;function h($){var U;(U=N.current)!=null&&U.contains($.target)||g(!1)}function P($){$.key==="Escape"&&g(!1)}return document.addEventListener("mousedown",h),document.addEventListener("keydown",P),()=>{document.removeEventListener("mousedown",h),document.removeEventListener("keydown",P)}},[p]);function d(h){g(!1),o(h)}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}),x?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 · ",w]}):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:x==="stopped"?"Stopped. Connect to wake this VM.":x&&x!=="online"?`${w}. The hosted supervisor is not ready yet.`:t.connected?`Online since ${Et(t.connectedAt)}`:`Offline. Last heartbeat: ${Et(t.lastHeartbeatAt)}`})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-2 sm:flex-nowrap",children:[e.jsxs("div",{className:"relative",ref:N,children:[e.jsxs("button",{"aria-expanded":p,"aria-haspopup":"menu",className:"relay-button-secondary inline-flex h-10 items-center gap-2 whitespace-nowrap",onClick:()=>g(h=>!h),title:c?"Choose a platform and copy the relay supervisor setup command":"Device token is not available. Create a new device token for devices created before token storage was enabled.",disabled:!c||!!x,type:"button",children:[e.jsx(q.Copy,{className:"h-4 w-4"}),a?"Copied":"Copy setup",e.jsx(q.ChevronDown,{className:"h-3.5 w-3.5"})]}),p?e.jsxs("div",{"aria-label":`Setup platform for ${t.name}`,className:"absolute left-0 top-full z-20 mt-1 w-52 rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-1 shadow-[var(--theme-shadow)] sm:left-auto sm:right-0",role:"menu",children:[e.jsx("button",{className:"flex min-h-10 w-full items-center rounded-md px-3 py-2 text-left text-sm text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--theme-accent-ring)]",onClick:()=>d("unix"),role:"menuitem",type:"button",children:"macOS & Linux"}),e.jsx("button",{className:"flex min-h-10 w-full items-center rounded-md px-3 py-2 text-left text-sm text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--theme-accent-ring)]",onClick:()=>d("windows"),role:"menuitem",type:"button",children:"Windows (PowerShell)"})]}):null]}),e.jsxs("button",{className:"relay-button-primary inline-flex h-10 items-center gap-2 whitespace-nowrap",disabled:!k,onClick:r,type:"button",children:[e.jsx(q.Plug,{className:"h-4 w-4"}),x==="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||!!x,onClick:l,title:x?"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 cc({result:t}){const[s,a]=n.useState("unix"),r=Gn(t.token,s);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(Xr,{label:"Device token",value:t.token}),e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"mb-1 flex flex-wrap 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:"Supervisor command"}),e.jsxs("div",{"aria-label":"Supervisor command platform",className:"inline-flex rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-0.5",role:"group",children:[e.jsx(Yr,{active:s==="unix",onClick:()=>a("unix"),children:"macOS & Linux"}),e.jsx(Yr,{active:s==="windows",onClick:()=>a("windows"),children:"Windows"})]})]}),e.jsx(Xr,{copyLabel:`Copy ${s==="windows"?"Windows PowerShell":"macOS and Linux"} supervisor command`,label:s==="windows"?"PowerShell":"Shell",nested:!0,value:r})]})]})}function Yr({active:t,children:s,onClick:a}){return e.jsx("button",{"aria-pressed":t,className:`min-h-8 rounded-md px-2.5 text-xs font-medium transition focus:outline-none focus:ring-2 focus:ring-[var(--theme-accent-ring)] ${t?"bg-[var(--theme-surface-strong)] text-[var(--theme-fg)] shadow-sm":"text-[var(--theme-fg-muted)] hover:bg-[var(--theme-hover)] hover:text-[var(--theme-fg)]"}`,onClick:a,type:"button",children:s})}function Xr({copyLabel:t="Copy",label:s,nested:a=!1,value:r}){async function o(){var l;try{await((l=navigator.clipboard)==null?void 0:l.writeText(r))}catch{}}return e.jsxs("div",{className:a?"":"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:s}),e.jsxs("button",{"aria-label":t,className:"relay-button-secondary inline-flex items-center gap-1 px-2 py-1 text-xs",onClick:()=>void o(),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:r})]})}function uc({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 Gn(t,s="unix"){const a=mc(),r=tc[s];return s==="windows"?["Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force",`$env:REMOTE_CODEX_RELAY_SERVER_URL=${Fs(a)}`,`$env:REMOTE_CODEX_RELAY_AGENT_TOKEN=${Fs(t)}`,`$env:REMOTE_CODEX_RELAY_SUPERVISOR_PORT=${Fs(String(r))}`,"remote-codex relay-supervisor"].join(`
|
|
20
|
-
`):[`REMOTE_CODEX_RELAY_SERVER_URL=${Zr(a)} \\`,`REMOTE_CODEX_RELAY_AGENT_TOKEN=${Zr(t)} \\`,`REMOTE_CODEX_RELAY_SUPERVISOR_PORT=${r} \\`,"remote-codex relay-supervisor"].join(`
|
|
21
|
-
`)}function Fs(t){return`'${t.replace(/'/g,"''")}'`}function Zr(t){return/^[A-Za-z0-9_./:@%+=,~-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function mc(){return typeof window>"u"?"wss://relay.example.com":window.location.origin.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://")}function Et(t){return t?new Date(t).toLocaleString():"never"}function hc(t){return t.replace("_"," ").replace(/^./,s=>s.toUpperCase())}function Jn(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 Kn(t){const s=t.trim();if(!s)return null;const a=new Date(s);return Number.isNaN(a.getTime())?null:a.toISOString()}function ya(t){return bs(t)??"Thread unavailable"}function bs(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 wa(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":Bt(t)??"Thread unavailable"}function Bt(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 fc(t){switch(t.scope){case"device":return"Device";case"workspace":return"Workspace";case"thread":default:return"Thread"}}function Yn(t){switch(t){case"write":return"Workspace write";case"read":return"Workspace read";case"none":default:return"No workspace"}}function Xn(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 pc=["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(`
|
|
22
|
-
`);function xc(){return n.useEffect(()=>{Ye()},[]),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(Be,{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(qs,{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(qs,{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(qs,{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(jt,{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(jt,{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(jt,{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(jt,{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(jt,{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(jt,{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:pc})})]}),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 qs({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 jt({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 gc(){const[t,s]=n.useState(null),[a,r]=n.useState(!0);n.useEffect(()=>{let l=!1;return Ye(),Tt().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(Be,{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(Be,{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(Be,{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(Be,{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(Be,{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(Gs,{label:"Mode",value:"Relay"}),e.jsx(Gs,{label:"Client",value:"Web, Android, iOS"}),e.jsx(Gs,{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(Vs,{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(Vs,{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(Vs,{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(zs,{title:"Local stays local",detail:"Workspace files and agent execution remain on the supervisor device."}),e.jsx(zs,{title:"Shared sessions",detail:"Share a thread as view-only or collaborator access, with workspace permissions."}),e.jsx(zs,{title:"Mobile first",detail:"Resume threads, monitor long turns, and open shared sessions from Android or iOS."})]})]})})}function Vs({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 zs({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 Gs({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 Zn(t,s){return t instanceof ie?t.payload.message:t instanceof Error?t.message:s}function vc(){const t=at(),s=Wt(),[a,r]=n.useState(null),[o,l]=n.useState(!0),[i,c]=n.useState(null);async function p(){var N;l(!0),c(null);try{Ye();const x=await Tt();if(r(x),x.authenticated){if(((N=x.user)==null?void 0:N.role)==="admin"){t("/relay-admin",{replace:!0});return}t("/relay-devices",{replace:!0});return}}catch(x){c(Zn(x,"Unable to load relay portal."))}finally{l(!1)}}n.useEffect(()=>{p()},[]);async function g(){var x;if(Ye(),((x=(await Tt()).user)==null?void 0:x.role)==="admin"){t("/relay-admin",{replace:!0});return}t("/relay-devices",{replace:!0})}return o?e.jsx(Js,{children:"Checking relay session..."}):a!=null&&a.authenticated?e.jsx(Js,{children:"Opening relay devices..."}):e.jsx(Js,{children:e.jsx(bc,{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:g})})}function bc({registrationEnabled:t,settings:s,oauthNotice:a,oauthError:r,initialError:o,onAuthenticated:l}){const[i,c]=n.useState("login"),[p,g]=n.useState(""),[N,x]=n.useState(""),[k,w]=n.useState(""),[d,h]=n.useState(""),[P,$]=n.useState(""),[U,R]=n.useState(o??r),[L,z]=n.useState(a),[te,Q]=n.useState(!1);async function D(oe){oe.preventDefault(),Q(!0),R(null),z(null);try{if(i==="login")await zl({identifier:p,password:d});else{if(d.length<8){R("Password must be at least 8 characters.");return}if(k.trim().length<3){R("Username must be at least 3 characters.");return}if((await Kl({email:N,username:k,password:d,registrationPassword:P})).pendingApproval){z("Registration request sent. An admin must approve it before you can sign in."),c("login");return}}await l()}catch(Z){R(Zn(Z,"Unable to authenticate with relay."))}finally{Q(!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(Dt,{autoComplete:"username",label:"Email or username",onChange:g,value:p}):e.jsxs(e.Fragment,{children:[e.jsx(Dt,{autoComplete:"email",label:"Email",onChange:x,required:!0,type:"email",value:N}),e.jsx(Dt,{autoComplete:"username",label:"Username",minLength:3,onChange:w,required:!0,value:k}),e.jsx(Dt,{autoComplete:"one-time-code",label:"Registration password",onChange:$,required:!0,type:"password",value:P})]}),e.jsx(Dt,{autoComplete:i==="login"?"current-password":"new-password",label:"Password",onChange:h,required:!0,type:"password",value:d,...i==="register"?{description:"Use at least 8 characters.",minLength:8}:{}}),U?e.jsx(Qr,{tone:"danger",children:U}):null,L?e.jsx(Qr,{tone:"accent",children:L}):null,e.jsx("button",{className:"relay-button-primary h-11 w-full",disabled:te,type:"submit",children:te?"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 Js({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(ba,{}),e.jsx("div",{className:"flex min-h-[calc(100vh-3rem)] items-center justify-center",children:t})]})}function Dt({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:p=>a(p.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 Qr({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 yc(t,s){return vl(t,s)}function xt(t,s,a=null){return bl(t,s,a)}function wc(t,s){return!s||s.items.length===0?t:t.map(a=>{if(a.id!==s.turnId)return a;const r=s.items.filter(p=>p.kind==="agentMessage"&&p.createdAt);if(r.length===0)return a;const o=new Map(r.map(p=>[p.id,p])),l=new Set;let i=!1;const c=a.items.map(p=>{if(p.kind!=="agentMessage"||p.createdAt&&p.createdAt!==a.startedAt)return p;let g=o.get(p.id);return g||(g=r.find(N=>!l.has(N.id)&&N.text.trim().length>=8&&p.text.trim().includes(N.text.trim()))),!(g!=null&&g.createdAt)||g.createdAt===a.startedAt?p:(l.add(g.id),i=!0,{...p,createdAt:g.createdAt})});return i?{...a,items:c}:a})}function jc(t,s){return{...t,pendingRequests:[...t.pendingRequests.filter(a=>a.id!==s.id),s]}}function Nc(t,s){const a=t.pendingRequests.filter(r=>r.id!==s);return a.length===t.pendingRequests.length?t:{...t,pendingRequests:a}}function en(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(p=>p.id===c.id))].sort((c,p)=>c.createdAt.localeCompare(p.createdAt))}function kc(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 Qn(t,s){var l,i;if(!t||t.kind!==s.kind)return s;const a=c=>{let p=c;const g=typeof s.sequence=="number"&&Number.isFinite(s.sequence)?s.sequence:typeof t.sequence=="number"&&Number.isFinite(t.sequence)?t.sequence:null;g!==null&&p.sequence!==g&&(p={...p,sequence:g});const N=typeof s.transcriptOrder=="number"&&Number.isFinite(s.transcriptOrder)?s.transcriptOrder:typeof t.transcriptOrder=="number"&&Number.isFinite(t.transcriptOrder)?t.transcriptOrder:null;return N!==null&&p.transcriptOrder!==N&&(p={...p,transcriptOrder:N}),p};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 Sc(t,s,a){if(!t||s&&s.turnId!==t.turnId)return s;const r=a.find(x=>x.id===t.turnId),o=new Map((r==null?void 0:r.items.map(x=>[x.id,x]))??[]),l=(r==null?void 0:r.items.filter(x=>x.kind==="agentMessage").map(x=>x.text.trim()).filter(Boolean))??[],i=x=>x.kind==="agentMessage"&&x.text.trim().length>0&&l.some(k=>k.includes(x.text.trim()));if(!s){const x=t.items.filter(k=>{const w=o.get(k.id);return w?w.kind!==k.kind||typeof k.sequence=="number"&&Number.isFinite(k.sequence)&&w.sequence!==k.sequence:!i(k)});return x.length===0?null:{...t,items:x}}const c=new Map(t.items.map(x=>[x.id,x])),p=new Map(s.items.map(x=>[x.id,x])),N=[...t.items.map(x=>x.id),...s.items.map(x=>x.id).filter(x=>!c.has(x))].map(x=>{const k=p.get(x),w=c.get(x);if(!k){const d=o.get(x);return!d&&w&&i(w)||d&&d.kind===(w==null?void 0:w.kind)&&!(w&&typeof w.sequence=="number"&&Number.isFinite(w.sequence)&&d.sequence!==w.sequence)?null:w??null}return Qn(w,k)}).filter(x=>!!x);return N.length===0?null:{turnId:s.turnId,items:N,updatedAt:s.updatedAt.localeCompare(t.updatedAt)>=0?s.updatedAt:t.updatedAt}}function _t(t,s){const a=t.filter(r=>r.id!==s.id);return[s,...a]}function Cc(t){return`${t.threadId}:${t.objective}:${t.createdAt}`}function Tc(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 eo(t){const s=new Map;for(const a of t){const r=Cc(a),o=s.get(r);s.set(r,o?Tc(o,a):a)}return[...s.values()].sort((a,r)=>Date.parse(r.updatedAt)-Date.parse(a.updatedAt))}function ys(t,s){return eo([s,...t])}function Ks(t,s){if(!s)return null;const a=t.find(r=>r.model===s);return a?a.supportedReasoningEfforts.length>1:null}function Ec(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`client-${Date.now()}-${Math.random().toString(16).slice(2,10)}`}function ja(t,s){return(t==null?void 0:t.items.some(a=>a.kind==="userMessage"&&a.text.trim()===s.trim()))??!1}const Rc=/\s*\[(?:PHOTO\s+[^\]]+|localImage)\]\s*/g;function Na(t){return/\[(?:PHOTO\s+[^\]]+|localImage)\]/.test(t)}function tn(t){return t.replace(Rc," ").replace(/\s+/g," ").trim()}function to(t,s){const a=tn(s);return a?(t==null?void 0:t.items.some(r=>r.kind==="userMessage"&&tn(r.text)===a))??!1:!1}function so(t){return(t==null?void 0:t.items.some(s=>s.kind==="userMessage"&&/\[(?:PHOTO\s+\.\/\.temp\/threads\/[^\]]+|localImage)\]/.test(s.text)))??!1}function Ac(t,s){return t.find(a=>ja(a,s))??(Na(s)?t.find(a=>to(a,s))??null:null)}function Ic(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:ja(a,s.prompt)||Na(s.prompt)&&(to(a,s.prompt)||so(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 Oc({activeView:t,composerHostRef:s,threadId:a}){const[r,o]=n.useState(!1),[l,i]=n.useState(0),[c,p]=n.useState(0),[g,N]=n.useState(0),[x,k]=n.useState(!1);n.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const U=window.matchMedia("(max-width: 639px)"),R=()=>o(U.matches);return R(),U.addEventListener("change",R),()=>{U.removeEventListener("change",R)}},[]),n.useEffect(()=>{var R,L;if(typeof window>"u")return;const U=()=>{const z=window.visualViewport,te=z?Math.max(0,Math.round(window.innerHeight-z.height-z.offsetTop)):0;N(te),document.documentElement.style.setProperty("--thread-detail-keyboard-inset",`${te}px`)};return U(),(R=window.visualViewport)==null||R.addEventListener("resize",U),(L=window.visualViewport)==null||L.addEventListener("scroll",U),window.addEventListener("resize",U),()=>{var z,te;(z=window.visualViewport)==null||z.removeEventListener("resize",U),(te=window.visualViewport)==null||te.removeEventListener("scroll",U),window.removeEventListener("resize",U),document.documentElement.style.removeProperty("--thread-detail-keyboard-inset")}},[]),n.useEffect(()=>{if(typeof document>"u")return;const U=()=>{const R=document.activeElement,L=s.current,z=L==null?void 0:L.querySelector('[aria-label="Prompt"]');k(!!(R&&z&&(R===z||z.contains(R))))};return U(),document.addEventListener("focusin",U),document.addEventListener("focusout",U),()=>{document.removeEventListener("focusin",U),document.removeEventListener("focusout",U)}},[t,s,r,a]),n.useEffect(()=>{const U=s.current;if(!U||typeof ResizeObserver>"u")return;const R=U.querySelector("form")??U,L=()=>{i(Math.max(U.getBoundingClientRect().height,R.getBoundingClientRect().height))};L();const z=new ResizeObserver(()=>{L()});return z.observe(R),()=>{z.disconnect()}},[t,s,r]),n.useEffect(()=>{var z,te;const U=s.current;if(!U||!r||t!=="chat"){p(0);return}const R=()=>{const Q=U.getBoundingClientRect();p(Math.max(0,Math.ceil(window.innerHeight-Q.top)))};R(),window.addEventListener("resize",R),(z=window.visualViewport)==null||z.addEventListener("resize",R),(te=window.visualViewport)==null||te.addEventListener("scroll",R);let L=null;return typeof ResizeObserver<"u"&&(L=new ResizeObserver(R),L.observe(U)),()=>{var Q,D;window.removeEventListener("resize",R),(Q=window.visualViewport)==null||Q.removeEventListener("resize",R),(D=window.visualViewport)==null||D.removeEventListener("scroll",R),L==null||L.disconnect()}},[t,s,r,g,x,a]);const w=r&&t==="chat",d=w&&x?g:0,h=Math.max(l,144),P=Math.max(c,h+d),$=w?P+12:0;return{floatingMobileComposerBottomOffset:d,timelineBottomSpacer:$,useFloatingMobileComposer:w}}const Ve=()=>({status:"idle",data:null,error:null});function Lc({detailRef:t,id:s,navigate:a,setDetail:r,setError:o,setThreads:l}){const[i,c]=n.useState(Ve),[p,g]=n.useState(Ve),[N,x]=n.useState(Ve),[k,w]=n.useState(Ve),[d,h]=n.useState(Ve),[P,$]=n.useState(!1),[U,R]=n.useState(!1),[L,z]=n.useState(()=>new Set),[te,Q]=n.useState(!1),[D,oe]=n.useState(!1),[Z,se]=n.useState(Ve);n.useEffect(()=>{c(Ve),g(Ve),x(Ve),w(Ve),h(Ve),$(!1),z(new Set),Q(!1),se(Ve)},[s]);const u=n.useCallback(async()=>{if(s){se(f=>({status:"loading",data:f.data,error:null}));try{const f=await Gi(s);se({status:"ready",data:f,error:null})}catch(f){const j=f instanceof ie?f.payload.message:"Unable to load export turns.";se(X=>({status:"failed",data:X.data,error:j}))}}},[s]);async function K(f){if(s){o(null),oe(!0);try{const{blob:j,filename:X}=await Ki(s,f),ke=URL.createObjectURL(j),v=document.createElement("a");v.href=ke,v.download=X,document.body.append(v),v.click(),v.remove(),window.setTimeout(()=>URL.revokeObjectURL(ke),3e4),Q(!1)}catch(j){const X=j instanceof ie?j.payload.message:"Unable to export transcript.";o(X)}finally{oe(!1)}}}async function Re(){if(s){h(f=>{var j;return{status:"loading",data:f.data??((j=t.current)==null?void 0:j.goal)??null,error:null}});try{const f=await id(s);h({status:"ready",data:f.goal,error:null}),r(j=>j&&(f.goal?{...j,goal:f.goal,goalHistory:ys(j.goalHistory??[],f.goal)}:{...j,goal:f.goal}))}catch(f){h(j=>({status:"failed",data:j.data,error:f instanceof ie?f.payload.message:"Unable to load goal."}))}}}async function ee(f){if(s){h(j=>{var X;return{status:"loading",data:j.data??((X=t.current)==null?void 0:X.goal)??null,error:null}});try{const j=await dd(s,f);h({status:"ready",data:j.goal,error:null}),r(X=>X&&(j.goal?{...X,goal:j.goal,goalHistory:ys(X.goalHistory??[],j.goal)}:{...X,goal:j.goal}))}catch(j){throw h(X=>({status:"failed",data:X.data,error:j instanceof ie?j.payload.message:"Unable to update goal."})),j}}}async function Ae(){if(s){h(f=>{var j;return{status:"loading",data:f.data??((j=t.current)==null?void 0:j.goal)??null,error:null}});try{const f=await cd(s);h({status:"ready",data:null,error:null}),r(j=>j&&(f.goalHistory?{...j,goal:null,goalHistory:f.goalHistory}:{...j,goal:null}))}catch(f){throw h(j=>({status:"failed",data:j.data,error:f instanceof ie?f.payload.message:"Unable to clear goal."})),f}}}async function Pe(f){R(!0);try{await ee({status:f})}finally{R(!1)}}async function Le(){R(!0);try{await Ae()}finally{R(!1)}}async function V(){if(s){c(f=>({status:"loading",data:f.data,error:null}));try{const f=await md(s);c({status:"ready",data:f,error:null})}catch(f){c(j=>({status:"failed",data:j.data,error:f instanceof ie?f.payload.message:"Unable to load skills."}))}}}async function M(){if(s){g(f=>({status:"loading",data:f.data,error:null}));try{const f=await hd(s);g({status:"ready",data:f,error:null})}catch(f){g(j=>({status:"failed",data:j.data,error:f instanceof ie?f.payload.message:"Unable to load MCP servers."}))}}}async function ae(){if(s){x(f=>({status:"loading",data:f.data,error:null}));try{const f=await fd(s);x({status:"ready",data:f,error:null})}catch(f){x(j=>({status:"failed",data:j.data,error:f instanceof ie?f.payload.message:"Unable to load hooks."}))}}}async function O(f){if(s){x(j=>({status:"loading",data:j.data,error:null}));try{const j=await pd(s,f);x({status:"ready",data:j,error:null})}catch(j){throw x(X=>({status:"failed",data:X.data,error:j instanceof ie?j.payload.message:"Unable to create hook."})),j}}}async function F(f){if(s){x(j=>({status:"loading",data:j.data,error:null}));try{const j=await xd(s,f);x({status:"ready",data:j,error:null})}catch(j){throw x(X=>({status:"failed",data:X.data,error:j instanceof ie?j.payload.message:"Unable to update hook."})),j}}}async function G(f){if(s){x(j=>({status:"loading",data:j.data,error:null}));try{const j=await gd(s,f);x({status:"ready",data:j,error:null})}catch(j){throw x(X=>({status:"failed",data:X.data,error:j instanceof ie?j.payload.message:"Unable to trust hook."})),j}}}async function ye(f){if(s){x(j=>({status:"loading",data:j.data,error:null}));try{const j=await vd(s,f);x({status:"ready",data:j,error:null})}catch(j){throw x(X=>({status:"failed",data:X.data,error:j instanceof ie?j.payload.message:"Unable to untrust hook."})),j}}}async function $e(){if(s){w(f=>({status:"loading",data:f.data,error:null}));try{const f=await ud(s);w({status:"ready",data:f,error:null})}catch(f){w(j=>({status:"failed",data:j.data,error:f instanceof ie?f.payload.message:"Unable to load turns for forking."}))}}}async function Xe(){if(!s)return;const f=await Br(s,{mode:"latest"});l(j=>_t(j,f.thread.thread)),a(Fe(f.thread.thread.id))}async function fe(f){if(!s)return;const j=await Br(s,{mode:"turn",turnId:f});l(X=>_t(X,j.thread.thread)),a(Fe(j.thread.thread.id))}return{expandedGoalIds:L,exportBusy:D,exportDialogOpen:te,exportTurnsState:Z,forkTurnOptionsState:k,goalActionBusy:U,goalMonitorOpen:P,goalState:d,handleCreateHook:O,handleExportTranscript:K,handleForkLatest:Xe,handleForkTurn:fe,handleGoalStatusAction:Pe,handleOpenForkTurns:$e,handleOpenGoal:Re,handleOpenHooks:ae,handleOpenMcp:M,handleOpenSkills:V,handleTerminateGoal:Le,handleTrustHook:G,handleUntrustHook:ye,handleUpdateGoal:ee,handleUpdateHook:F,hooksState:N,loadExportTurns:u,mcpState:p,setExpandedGoalIds:z,setExportDialogOpen:Q,setGoalMonitorOpen:$,setGoalState:h,skillsState:i}}const Uc=5e3;function sn(t){return JSON.stringify(t)}function $c(t,s){return sn(t)===sn(s)}function Dc(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 p;const c=a.get(l.id);return c&&$c(c,l)?(((p=t[i])==null?void 0:p.id)!==l.id&&(r=!0),c):(r=!0,l)});return r?o:t}function ao(t){const{enabled:s,setThreads:a,intervalMs:r=Uc}=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 xa();a(c=>Dc(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 Mc({setError:t,workspaceId:s,access:a="write"}){return n.useMemo(()=>!s||a==="none"?null:{listTree:r=>Ui(s,{path:r.path??""}),readFile:r=>$i(s,{path:r.path,...r.offset!==void 0?{offset:r.offset}:{},...r.limit!==void 0?{limit:r.limit}:{}}),getRawFileUrl:r=>Di(s,{path:r.path}),...a==="write"?{uploadFile:r=>Hi(s,{file:r.file}),writeFile:async r=>{await Bi(s,{path:r.path,content:r.content})}}:{},downloadNode:async r=>{t(null);try{const o=await _i(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 ie?o.payload.message:o instanceof Error?o.message:"Workspace download failed.")}}},[a,t,s])}function ct(t){return t.enabled&&t.capabilities.sessions.resume&&t.capabilities.turns.start}function an(t,s){var r;const a=t.find(o=>o.provider===s);return a&&ct(a)?a.provider:((r=t.find(ct))==null?void 0:r.provider)??tt}function ka({initialWorkspaceId:t,initialTitle:s="",onCreated:a,onCancel:r,variant:o="panel"}){var Ue;const l=Ft(),i=n.useId(),[c,p]=n.useState([]),[g,N]=n.useState([]),[x,k]=n.useState([]),[w,d]=n.useState([]),[h,P]=n.useState((l==null?void 0:l.defaultBackend)??tt),[$,U]=n.useState(""),[R,L]=n.useState(""),[z,te]=n.useState(""),[Q,D]=n.useState(null),[oe,Z]=n.useState(()=>s??""),[se,u]=n.useState("yolo"),[K,Re]=n.useState(!0),[ee,Ae]=n.useState(!1),[Pe,Le]=n.useState(null),[V,M]=n.useState(null),[ae,O]=n.useState(null),F=(l==null?void 0:l.defaultBackend)??tt,G=g.find(A=>A.provider===h),ye=c.find(A=>A.id===$)??null,$e=w.find(A=>A.model===z)??null,Xe=h==="acp"&&x.some(A=>A.selectionKind==="agent"),fe=x.find(A=>A.model===R)??null,f=!!$e,j=o==="dialog",X=j?"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",ke=j?"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",v=j?"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(()=>{Z(s??"")},[s]),n.useEffect(()=>{let A=!1;return Promise.all([pa(),Ct()]).then(([T,ne])=>{var je;if(A)return;const ge=an(ne,F);P(ge),N(ne),p(T);const we=t??null,ve=T.some(rt=>rt.id===we)?we:((je=T[0])==null?void 0:je.id)??"";U(ve)}).catch(T=>{A||O(T instanceof Error?T.message:"Unable to load creation form data.")}).finally(()=>{A||Re(!1)}),()=>{A=!0}},[F,t]),n.useEffect(()=>{if(!h)return;let A=!1;if($)return d([]),te(""),D(null),O(null),h==="acp"?(ms(h).then(T=>{A||(k(T),L(ne=>{const we=T.find(ve=>{var je;return ve.model===ne&&((je=ve.acpAgent)==null?void 0:je.availability)==="ready"})??T.find(ve=>{var je;return ve.isDefault&&((je=ve.acpAgent)==null?void 0:je.availability)==="ready"})??T.find(ve=>{var je;return((je=ve.acpAgent)==null?void 0:je.availability)==="ready"})??null;return(we==null?void 0:we.model)??""}))}).catch(T=>{A||(k([]),L(""),O(T instanceof Error?T.message:"Unable to load ACP agents."))}),()=>{A=!0}):(k([]),L(""),ia(h).then(T=>{if(A)return;d(T);const ne=T.find(ge=>ge.isDefault)??T[0]??null;te((ne==null?void 0:ne.model)??""),D((ne==null?void 0:ne.defaultReasoningEffort)??null)}).catch(T=>{A||(d([]),te(""),O(T instanceof Error?T.message:"Unable to load backend models."))}),()=>{A=!0})},[h,$]),n.useEffect(()=>{if(h!=="acp"||!R||!ye)return;let A=!1;return d([]),te(""),D(null),fa("acp",{agentId:R,cwd:ye.absPath}).then(T=>{if(A)return;d(T);const ne=T.find(ge=>ge.isDefault)??T[0]??null;te((ne==null?void 0:ne.model)??""),D((ne==null?void 0:ne.defaultReasoningEffort)??null)}).catch(T=>{A||O(T instanceof Error?T.message:"Unable to load agent models.")}),()=>{A=!0}},[R,h,ye]);async function C(A=h){const T=await Ct();N(T);const ne=T.find(je=>je.provider===A),ge=ne&&ct(ne)?A:an(T,F);if(P(ge),ge==="acp"){const je=await ms("acp");k(je);const rt=je.find(nt=>{var mt;return nt.isDefault&&((mt=nt.acpAgent)==null?void 0:mt.availability)==="ready"})??je.find(nt=>{var mt;return((mt=nt.acpAgent)==null?void 0:mt.availability)==="ready"})??null;L((rt==null?void 0:rt.model)??"");return}const we=await ia(ge);d(we);const ve=we.find(je=>je.isDefault)??we[0]??null;te((ve==null?void 0:ve.model)??""),D((ve==null?void 0:ve.defaultReasoningEffort)??null)}async function H(A){const T=A.installation.installed?"update":"install";Le(A.provider),O(null);try{await la(A.provider,T),await C(A.provider)}catch(ne){ne instanceof ie?O(ne.payload.message):O(ne instanceof Error?ne.message:`Unable to ${T} ${A.displayName}.`);try{await C(h)}catch{}}finally{Le(null)}}async function re(A){var T;M(A.id),O(null);try{await la("acp","install",A.id);const ne=await ms("acp");k(ne);const ge=ne.find(we=>we.id===A.id);((T=ge==null?void 0:ge.acpAgent)==null?void 0:T.availability)==="ready"&&L(ge.model),N(await Ct())}catch(ne){O(ne instanceof Error?ne.message:`Unable to install ${A.displayName}.`)}finally{M(null)}}async function be(A){A.preventDefault(),Ae(!0),O(null);try{const T=await Xi(oe.trim()?{workspaceId:$,provider:h,...h==="acp"?{agentId:R}:{},model:z,...Q?{reasoningEffort:Q}:{},approvalMode:se,title:oe.trim()}:{workspaceId:$,provider:h,...h==="acp"?{agentId:R}:{},model:z,...Q?{reasoningEffort:Q}:{},approvalMode:se});a(T)}catch(T){T instanceof ie?O(T.payload.message):O(T instanceof Error?T.message:"Unable to create thread.")}finally{Ae(!1)}}return K?e.jsx("div",{className:"host-empty-state rounded-lg border px-6 py-12 text-center",children:"Loading creation form..."}):e.jsxs("form",{onSubmit:be,className:j?"max-h-[min(76vh,36rem)] space-y-3 overflow-y-auto pr-1 text-sm":"space-y-5",children:[j?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, agent, 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:h,onChange:A=>{const T=A.target.value;P(T)},className:X,children:g.map(A=>e.jsxs("option",{value:A.provider,disabled:!ct(A),children:[A.displayName,ct(A)?"":" (not available)"]},A.provider))}),j?G&&!ct(G)?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:g.map(A=>{const T=ct(A),ne=A.provider===h,ge=A.installation.installed?!!A.installation.updateCommand:!!A.installation.installCommand,we=A.installation.installed?"Update":"Install",ve=Pe===A.provider||A.installation.busy;return e.jsxs("div",{className:`rounded-lg border px-4 py-3 transition ${ne?"host-surface-strong":"host-surface"} ${T?"":"opacity-75"}`,children:[e.jsxs("div",{className:"flex flex-wrap items-start gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>{T&&P(A.provider)},disabled:!T||ee||ve,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:A.displayName}),ne?e.jsx("span",{className:"host-pill rounded-full px-2 py-0.5 text-xs",children:"Selected"}):null,T?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:A.installation.installed?`Installed${A.installation.installedVersion?`: ${A.installation.installedVersion}`:""}`:A.installation.lastError??A.status.lastError??"Runtime is not installed."}),!T&&A.installation.lastError?e.jsx("p",{className:"mt-1 text-xs opacity-70",children:A.installation.lastError}):null]}),ge?e.jsx("button",{type:"button",onClick:()=>H(A),disabled:ee||ve||Pe!==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":`${we} ${A.displayName}`,children:ve?`${we}ing...`:we}):null]}),!T&&ge?e.jsx("p",{className:"mt-2 text-xs opacity-70",children:"Relay connections install or update the runtime on the selected device."}):null]},A.provider)})}),!j&&G&&!ct(G)?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:$,onChange:A=>U(A.target.value),className:X,children:c.map(A=>e.jsxs("option",{value:A.id,children:[A.label," · ",A.absPath]},A.id))})]}),Xe?e.jsxs("fieldset",{children:[e.jsx("legend",{className:"host-form-label text-xs font-medium",children:"Agent"}),e.jsx("div",{className:"mt-2 max-h-64 divide-y divide-[var(--theme-border)] overflow-y-auto rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)]",role:"radiogroup","aria-label":"Agent",children:x.map(A=>{const T=A.acpAgent,ne=(T==null?void 0:T.availability)==="ready",ge=(T==null?void 0:T.availability)==="adapter_missing",we=V===A.id||(T==null?void 0:T.busy)===!0,ve=A.model===R,je=(T==null?void 0:T.availability)==="base_missing"?"Base agent missing":ge?"Adapter needed":(T==null?void 0:T.availability)==="server_unavailable"?"ACP unavailable":"Ready",rt=(T==null?void 0:T.transport)==="native"?"Native ACP":(T==null?void 0:T.transport)==="adapter"?"ACP adapter":"Custom ACP",nt=`${i}-acp-agent-${A.id}-tooltip`;return e.jsxs("div",{className:"group/agent relative flex min-w-0 items-stretch gap-2 px-2 py-2",title:T==null?void 0:T.statusMessage,children:[e.jsxs("button",{type:"button",role:"radio","aria-checked":ve,"aria-disabled":!ne||ee||V!==null,"aria-describedby":nt,onClick:()=>{ne&&!ee&&V===null&&L(A.model)},className:`min-w-0 flex-1 rounded-md px-2.5 py-2 text-left outline-none transition focus-visible:ring-2 focus-visible:ring-[var(--theme-accent-solid)] ${ve?"bg-[var(--theme-surface-strong)] text-[var(--theme-fg)]":ne?"text-[var(--theme-fg)] hover:bg-[var(--theme-hover)]":"cursor-not-allowed text-[var(--theme-fg-muted)] opacity-70"}`,children:[e.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsx("span",{className:"truncate font-medium",children:A.displayName}),e.jsx("span",{className:"host-pill rounded-full px-2 py-0.5 text-[0.68rem]",children:je}),e.jsx("span",{className:"text-[0.68rem] text-[var(--theme-fg-muted)]",children:rt})]}),e.jsxs("span",{className:"mt-1 block truncate font-mono text-[0.68rem] text-[var(--theme-fg-muted)]",children:["Probe: ",(T==null?void 0:T.baseProbeCommand)??"Unavailable"]}),e.jsxs("span",{className:"mt-0.5 block truncate font-mono text-[0.68rem] text-[var(--theme-fg-muted)]",children:["ACP: ",(T==null?void 0:T.serverCommand)??"Unavailable"]})]}),ge&&(T!=null&&T.installCommand)?e.jsx("button",{type:"button",onClick:()=>void re(A),disabled:ee||we||V!==null,className:"host-secondary-button my-auto shrink-0 rounded-lg border px-3 py-2 text-xs font-medium transition disabled:cursor-not-allowed disabled:opacity-60","aria-label":`Install ACP adapter for ${A.displayName}`,children:we?"Installing...":"Install adapter"}):null,e.jsxs("span",{id:nt,role:"tooltip",className:"pointer-events-none absolute inset-x-2 bottom-[calc(100%-0.2rem)] z-20 invisible rounded-md border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-2 text-xs leading-5 text-[var(--theme-fg)] opacity-0 shadow-[var(--theme-shadow)] transition group-hover/agent:visible group-hover/agent:opacity-100 group-focus-within/agent:visible group-focus-within/agent:opacity-100",children:[T==null?void 0:T.statusMessage,e.jsxs("span",{className:"mt-1 block font-mono text-[0.68rem] text-[var(--theme-fg-muted)]",children:["Base probe: ",T==null?void 0:T.baseProbeCommand]}),e.jsxs("span",{className:"block font-mono text-[0.68rem] text-[var(--theme-fg-muted)]",children:["ACP probe: ",T==null?void 0:T.serverProbeCommand]})]})]},A.id)})})]}):null,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:z,onChange:A=>{const T=w.find(ne=>ne.model===A.target.value)??null;te(A.target.value),D(ne=>ne&&(T!=null&&T.supportedReasoningEfforts.some(ge=>ge.reasoningEffort===ne))?ne:(T==null?void 0:T.defaultReasoningEffort)??null)},disabled:w.length===0,className:X,children:[w.length===0?e.jsx("option",{value:"",children:"No models available"}):null,w.map(A=>e.jsx("option",{value:A.model,children:A.displayName},A.id))]})]}),$e&&$e.supportedReasoningEfforts.length>0?e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-xs font-medium",htmlFor:`${i}-thread-effort`,children:"Reasoning effort"}),e.jsx("select",{id:`${i}-thread-effort`,value:Q??"",onChange:A=>D(A.target.value||null),className:X,children:$e.supportedReasoningEfforts.map(A=>e.jsx("option",{value:A.reasoningEffort,children:A.reasoningEffort},A.reasoningEffort))})]}):null,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:oe,onChange:A=>Z(A.target.value),placeholder:"Optional. Falls back to first prompt.",className:X})]}),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:se,onChange:A=>u(A.target.value),className:X,children:[e.jsx("option",{value:"yolo",children:"yolo"}),e.jsx("option",{value:"guarded",children:"guarded"})]})]}),ae&&e.jsx("div",{className:"host-error rounded-lg border px-4 py-3 text-sm",children:ae}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[e.jsx("button",{type:"submit",disabled:ee||!$||!z||!f||h==="acp"&&((Ue=fe==null?void 0:fe.acpAgent)==null?void 0:Ue.availability)!=="ready",className:v,children:ee?"Creating...":"Create Thread"}),r?e.jsx("button",{type:"button",onClick:r,disabled:ee,className:ke,children:"Cancel"}):null]})]})}const rn=3,_c=3,Hc=1e3,Bc=2e3,Ys=5500,Wc=3e3,Xs=0,Nt=1,os=3,Fc=[],qc=[],Vc=[],zc={workspace:!0,toolUsage:!1,guide:!1,threadGraph:!1,extensions:!1,defaultTab:"workspace"};function ls(t,s){return t instanceof ie?t.payload.message:t instanceof Error?t.message:s}function nn(t){return t==="read"?"View only":"Collaborator"}function on(t){switch(t){case"write":return"Workspace write";case"read":return"Workspace read";case"none":default:return"No workspace"}}function Gc(t){var s,a;return((a=(s=t.match(/^\[PHOTO\s+([^\]]+)\]$/))==null?void 0:s[1])==null?void 0:a.trim())??null}function ln(t){return!(t!=null&&t.length)||typeof URL.createObjectURL!="function"?[]:t.flatMap(s=>{if(s.kind!=="photo")return[];const a=Gc(s.placeholder);return a?[{path:a,url:URL.createObjectURL(s.file)}]:[]})}function Jc(t){if(typeof URL.revokeObjectURL=="function")for(const s of t)URL.revokeObjectURL(s.url)}function Kc(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 Yc(){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 is({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 Xc(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 dn(){var Tr,Er;const{id:t=""}=Xo(),s=n.useRef(t);s.current=t;const a=Wt(),r=at(),o=Ft(),l=bn(),i=n.useRef(""),c=n.useRef(null),p=n.useRef(null),g=n.useRef(null),N=n.useRef(!1),x=n.useRef(null),k=n.useRef(null),w=n.useRef(typeof navigator>"u"?!0:navigator.onLine),d=n.useRef(!1),h=n.useRef(null),P=n.useRef(null),$=n.useRef(0),U=n.useRef(0),R=n.useRef(Promise.resolve()),L=n.useRef(!1),z=n.useRef(0),te=n.useRef(null),Q=n.useRef(null),D=n.useRef(null),oe=n.useRef(!1),Z=n.useRef(null),se=n.useRef(new Set),[u,K]=n.useState(null),[Re,ee]=n.useState([]),[Ae,Pe]=n.useState([]),[Le,V]=n.useState([]),[M,ae]=n.useState(null),[O,F]=n.useState(null),[G,ye]=n.useState(null),[$e,Xe]=n.useState(0),[fe,f]=n.useState(null),[j,X]=n.useState(""),[ke,v]=n.useState(null),[C,H]=n.useState(null),re=n.useRef(null),[be,Ue]=n.useState(!0),[A,T]=n.useState(0),[ne,ge]=n.useState(0),[we,ve]=n.useState(0),[je,rt]=n.useState(!1),[nt,mt]=n.useState(!1),[Sa,Ns]=n.useState(!0),[Vt,ks]=n.useState(!1),[ht,lt]=n.useState(!1),[ze,Ca]=n.useState("chat"),[mo,ho]=n.useState(null),Ta=l.getThreadPanels().some(m=>m.kind==="terminal");n.useEffect(()=>{re.current=C},[C]);const Ea=n.useMemo(()=>({fetchState:Yi,createShell:Qi,terminateShell:ed,updateShell:td,connectSocket:kd}),[]),Ra=n.useCallback(m=>Fe(m),[]),zt=n.useCallback(m=>{r(Fe(m))},[r]),Aa=n.useCallback(m=>ps(m),[]),Ia=n.useCallback(({close:m,closeNavigation:y,currentWorkspaceId:b})=>e.jsx(ka,{variant:"dialog",initialWorkspaceId:b,onCancel:m,onCreated:E=>{m(),y(),r(Fe(E.id))}}),[r]),Pa=n.useCallback(({threadId:m,path:y})=>Mi(m,{path:y}),[]),[Oa,Ss]=n.useState({prompt:"",attachments:[]}),[ue,La]=n.useState(null),[Ua,Rt]=n.useState(!1),[fo,$a]=n.useState(!1),[po,Da]=n.useState(!1),[Ma,_a]=n.useState(null),[ft,Gt]=n.useState("idle"),[it,Ha]=n.useState({status:w.current?"checking":"offline",browserOnline:w.current,healthOk:!1,socketOpen:!1,lastHealthyAt:null}),[Ne,We]=n.useState(null),[Jt,vt]=n.useState([]);n.useEffect(()=>{const m=(Ne==null?void 0:Ne.attachmentPreviews)??[];return()=>{Jc(m)}},[Ne]);const[Ze,Cs]=n.useState(null),[Ts,Ba]=n.useState(!1),[xo,le]=n.useState(null),Es=((Tr=fe==null?void 0:fe.hostConfigFiles.find(m=>{var y;return(y=m.roles)==null?void 0:y.includes("mcp")}))==null?void 0:Tr.name)??null,{exportBusy:Rs,exportDialogOpen:Kt,exportTurnsState:Wa,forkTurnOptionsState:go,goalState:Fa,handleCreateHook:vo,handleExportTranscript:qa,handleForkLatest:bo,handleForkTurn:yo,handleOpenForkTurns:wo,handleOpenGoal:jo,handleOpenHooks:No,handleOpenMcp:ko,handleOpenSkills:So,handleTrustHook:Co,handleUntrustHook:To,handleUpdateGoal:Eo,handleUpdateHook:Ro,hooksState:Ao,loadExportTurns:Va,mcpState:Io,setExportDialogOpen:As,setGoalState:Is,skillsState:Po}=Lc({detailRef:D,id:t,navigate:r,setDetail:K,setError:le,setThreads:ee}),[Ps,Yt]=n.useState(!1),[za,Qe]=n.useState({status:"idle",shares:[],error:null}),[Xt,Zt]=n.useState({status:"idle",access:null,error:null}),Ga=Nn(a.pathname),pt=ut()&&!!Ga,ce=Xt.access,At=!pt||(ce==null?void 0:ce.kind)==="owner",He=At||(ce==null?void 0:ce.kind)==="shared"&&ce.threadAccess==="control",Ja=pt&&(ce==null?void 0:ce.kind)==="owner",Oo=(u==null?void 0:u.workspace.id)??(u==null?void 0:u.thread.workspaceId)??null,Lo=pt?(ce==null?void 0:ce.kind)==="owner"?"write":(ce==null?void 0:ce.kind)==="shared"&&ce.workspaceId&&ce.workspaceId===Oo?ce.workspaceAccess:"none":"write",bt=n.useCallback(async()=>{const m=D.current,y=st();if(!ut()||!m||!y){Qe({status:"ready",shares:[],error:null});return}Qe(b=>({...b,status:"loading",error:null}));try{const E=(await Ln()).sharedByMe.filter(B=>B.deviceId===y&&B.threadId===m.thread.id).map(B=>({id:B.id,targetUsername:B.targetUsername,label:B.label,threadAccess:B.threadAccess,workspaceAccess:B.workspaceAccess,createdAt:B.createdAt}));Qe({status:"ready",shares:E,error:null})}catch(b){Qe(E=>({...E,status:"failed",error:ls(b,"Unable to load active shares.")}))}},[D]),Ka=n.useCallback(async m=>{const y=D.current,b=st();if(!ut()||!y||!b){Qe(B=>({...B,status:"failed",error:"Relay sharing is only available from a relay device route."}));return}const E=m.workspaceAccess==="none"?null:y.workspace.id??y.thread.workspaceId??null;if(m.workspaceAccess!=="none"&&!E){Qe(B=>({...B,status:"failed",error:"This thread is not attached to a workspace."}));return}Yt(!0),Qe(B=>({...B,error:null}));try{await si({targetIdentifier:m.targetIdentifier,deviceId:b,threadId:y.thread.id,workspaceId:E,label:m.label??null,threadAccess:m.threadAccess,workspaceAccess:m.workspaceAccess}),await bt()}catch(B){const J=ls(B,"Unable to create share.");Qe(he=>({...he,status:"failed",error:J})),le(J)}finally{Yt(!1)}},[D,bt]),Ya=n.useCallback(async m=>{Yt(!0),Qe(y=>({...y,error:null}));try{await Un(m),await bt()}catch(y){const b=ls(y,"Unable to revoke share.");Qe(E=>({...E,status:"failed",error:b})),le(b)}finally{Yt(!1)}},[bt]),Xa=n.useCallback(()=>{const m=st();m&&(As(!1),r(`/relay-devices?shareDevice=${encodeURIComponent(m)}`))},[r]);n.useEffect(()=>{Kt&&bt()},[Kt,bt]),n.useEffect(()=>{const m=D.current,y=st();if(!ut()||!m||!y){Zt({status:"idle",access:null,error:null});return}let b=!1;return Zt(E=>({...E,status:"loading",error:null})),Xl({deviceId:y,threadId:m.thread.id}).then(E=>{b||Zt({status:"ready",access:E,error:null})}).catch(E=>{b||Zt({status:"failed",access:null,error:ls(E,"Unable to verify relay permissions.")})}),()=>{b=!0}},[u==null?void 0:u.thread.id,u==null?void 0:u.workspace.id,D]),ao({enabled:!!t,setThreads:ee});const Za=n.useCallback(()=>{const m=i.current;i.current="",c.current=null,m&&n.startTransition(()=>{X(y=>y+m)})},[]),Qa=n.useCallback(m=>{i.current+=m,c.current===null&&(c.current=window.requestAnimationFrame(()=>{Za()}))},[Za]),er=n.useCallback((m,y)=>{H(b=>{const E=(b==null?void 0:b.turnId)===m?b.items:[],B=E.findIndex(de=>de.id===y.id),J=Qn(E[B],y),he=B>=0?E.map((de,xe)=>xe===B?J:de):[...E,J];return{turnId:m,items:he,updatedAt:new Date().toISOString()}})},[]),tr=n.useCallback((m,y,b,E,B)=>{H(J=>{const he=(J==null?void 0:J.turnId)===m?J.items:[],de=he.find(Te=>Te.id===y),xe=(de==null?void 0:de.kind)==="agentMessage"?{...de,text:`${de.text}${b}`,sequence:E??de.sequence??null}:{id:y,createdAt:B??new Date().toISOString(),kind:"agentMessage",text:b,sequence:E},W=he.findIndex(Te=>Te.id===y),Oe=W>=0?he.map((Te,Ie)=>Ie===W?xe:Te):[...he,xe];return{turnId:m,items:Oe,updatedAt:new Date().toISOString()}})},[]),et=n.useCallback(()=>{i.current="",c.current!==null&&(window.cancelAnimationFrame(c.current),c.current=null)},[]),Qt=n.useCallback(m=>{const y=Z.current,b=y&&Object.keys(y).length>0?{...m,thread:{...m.thread,...y}}:m,E={...b,turns:wc(b.turns,re.current)},B=D.current;v(E.livePlan??null);const J=xt((B==null?void 0:B.turns)??[],E.turns,E.thread.activeTurnId);D.current={...E,turns:J},H(W=>Sc(W,E.liveItems??null,J)),Is(W=>W.status==="idle"?W:{...W,data:E.goal??null});const he=E.thread.activeTurnId===null&&E.thread.status!=="running";K(W=>W&&!E.goalHistory?{...E,turns:xt(W.turns,E.turns,E.thread.activeTurnId),pendingRequests:en(W.pendingRequests,E.pendingRequests,se.current),...W.goalHistory?{goalHistory:W.goalHistory}:{}}:W?{...E,turns:xt(W.turns,E.turns,E.thread.activeTurnId),pendingRequests:en(W.pendingRequests,E.pendingRequests,se.current)}:{...E,turns:J}),ee(W=>_t(W,E.thread));const de=new Map(E.turns.map(W=>[W.id,W])),xe=new Set((E.pendingSteers??[]).map(W=>W.clientRequestId).filter(W=>!!W));vt(W=>W.filter(Oe=>{if(xe.has(Oe.clientRequestId))return!1;const Te=de.get(Oe.turnId);return!(!Te||ja(Te,Oe.prompt)||E.thread.activeTurnId!==Oe.turnId&&Te.status!=="inProgress")})),We(W=>{var Y;if(!W)return W;if(W.id.startsWith("optimistic-goal-")&&((Y=E.activityNotes)!=null&&Y.some(me=>me.kind==="goal"&&me.text===W.prompt)))return null;const Oe=W.serverTurnId??W.id,Te=E.turns.some(me=>me.id===Oe),Ie=de.get(Oe)??null,S=Ac(E.turns,W.prompt),_=!!S;if(S&&!W.serverTurnId)return{...W,id:S.id,serverTurnId:S.id,status:W.status==="failed"?W.status:S.status==="inProgress"?"inProgress":W.status};if(Ie&&W.serverTurnId)return Ie.items.some(pe=>pe.kind==="userMessage")?Ie.status==="inProgress"?{...W,id:Ie.id,serverTurnId:Ie.id,status:W.status==="failed"?W.status:"inProgress"}:null:{...W,id:Ie.id,serverTurnId:Ie.id,status:W.status==="failed"?W.status:Ie.status==="inProgress"?"inProgress":Ie.status==="failed"?"failed":"completed"};if(!W.serverTurnId&&Na(W.prompt)&&E.thread.activeTurnId&&E.thread.status==="running"){const me=de.get(E.thread.activeTurnId);if(me&&so(me))return{...W,id:me.id,serverTurnId:me.id,status:W.status==="failed"?W.status:"inProgress"}}return Te||he&&_?null:W}),(he||Q.current&&E.turns.some(W=>W.id===Q.current))&&(Q.current=null,et(),X(""),v(null),H(null))},[et]);n.useEffect(()=>{D.current=u},[u]),n.useEffect(()=>{u!=null&&u.thread.title&&(document.title=u.thread.title)},[u==null?void 0:u.thread.title]),n.useEffect(()=>{const m=u==null?void 0:u.thread.provider;if(!m||m!=="codex"&&m!=="claude"){ye(null);return}let y=!1;const b=async()=>{var B;try{const J=await Ti(m);y||ye(((B=J.usage)==null?void 0:B.authKind)==="subscription"&&J.usage.windows.length>0?J.usage:null)}catch{y||ye(J=>J?{...J,stale:!0}:null)}};b();const E=window.setInterval(b,6e4);return()=>{y=!0,window.clearInterval(E)}},[u==null?void 0:u.thread.lastTurnCompletedAt,u==null?void 0:u.thread.provider,$e]);const sr=n.useCallback(async({seedThread:m}={})=>{var Te,Ie,S;const y=z.current+1;z.current=y;const b=(m==null?void 0:m.provider)??((Te=D.current)==null?void 0:Te.thread.provider)??"codex",E=(m==null?void 0:m.agentId)??((Ie=D.current)==null?void 0:Ie.thread.agentId)??null,B=((S=D.current)==null?void 0:S.workspace.absPath)??null,J=b==="acp"&&E&&B?fa(b,{agentId:E,cwd:B}):ia(b),he=b==="acp"?ms(b):Promise.resolve([]),[de,xe,W,Oe]=await Promise.allSettled([xa(),Dn(b),J,he]);z.current===y&&(de.status==="fulfilled"?ee(m?_t(de.value,m):de.value):m&&ee(_=>_t(_,m)),xe.status==="fulfilled"&&(te.current=b,ae(xe.value.status),F(xe.value.capabilities),f(xe.value.managementSchema)),W.status==="fulfilled"&&(te.current=b,Pe(W.value)),Oe.status==="fulfilled"&&V(Oe.value))},[]),ot=n.useCallback(async({showLoading:m=!0,clearError:y=!0,reportError:b=!0,limit:E=rn}={})=>{if(U.current>0){L.current=!0;return}const B=$.current+1;$.current=B,m&&Ns(!0),y&&le(null);try{const J=await _r(t,{limit:E});if($.current!==B)return;Qt(J),te.current!==J.thread.provider&&sr({seedThread:J.thread})}catch(J){if($.current!==B||!b)return;le(J instanceof Error?J.message:"Unable to load thread detail.")}finally{$.current===B&&Ns(!1)}},[Qt,t,sr]),yt=n.useCallback(m=>{const y=R.current.then(async()=>{U.current+=1,$.current+=1;try{const b=await m();return b.thread.id===s.current&&Qt(b),b}finally{U.current-=1,window.setTimeout(()=>{U.current===0&&L.current&&(L.current=!1,ot({showLoading:!1,clearError:!1,reportError:!1}))},0)}});return R.current=y.then(()=>{},()=>{}),y},[Qt,ot]),De=n.useCallback(()=>{var de;const m=((de=p.current)==null?void 0:de.readyState)??os,y=m===Nt,b=w.current,E=Date.now(),B=x.current!==null&&E-Date.parse(x.current)<=Ys,J=k.current!==null&&E-k.current<=Ys;let he;b?y&&J?he="connected":m===Xs||g.current!==null||B||J||N.current?he="reconnecting":he="checking":he="offline",Ha(xe=>xe.status===he&&xe.browserOnline===b&&xe.healthOk===B&&xe.socketOpen===y&&xe.lastHealthyAt===x.current?xe:{status:he,browserOnline:b,healthOk:B,socketOpen:y,lastHealthyAt:x.current})},[]);n.useEffect(()=>{$.current+=1,z.current+=1,K(null),le(null),Ns(!0),Ss({prompt:"",attachments:[]}),ks(!1),Gt("idle"),We(null),vt([]),H(null),Z.current=null,Q.current=null,se.current=new Set,x.current=null,k.current=null,d.current=!1,w.current=typeof navigator>"u"?!0:navigator.onLine,Ha({status:w.current?"checking":"offline",browserOnline:w.current,healthOk:!1,socketOpen:!1,lastHealthyAt:null})},[t,Ga]),n.useEffect(()=>{if(ft==="idle")return;const m=window.setTimeout(()=>{Gt("idle")},ft==="copied"?1200:1600);return()=>{window.clearTimeout(m)}},[ft]),n.useEffect(()=>{if(typeof document>"u")return;const{documentElement:m,body:y}=document;return m.classList.add("thread-detail-scroll-locked"),y.classList.add("thread-detail-scroll-locked"),()=>{m.classList.remove("thread-detail-scroll-locked"),y.classList.remove("thread-detail-scroll-locked")}},[]),n.useEffect(()=>{ot({showLoading:!0,limit:rn})},[ot]),n.useEffect(()=>{let m=!1,y=null;const b=()=>{ot({showLoading:!1,clearError:!1,reportError:!1})},E=()=>{g.current!==null&&(window.clearTimeout(g.current),g.current=null)},B=()=>{m||!w.current||g.current!==null||(g.current=window.setTimeout(()=>{g.current=null,!m&&xe()},Hc),De())},J=()=>{const S=p.current;if(p.current=null,S)try{S.close()}catch{}},he=S=>{if(S.threadId===t){if(S.type==="thread.output.delta"&&typeof S.payload.delta=="string"){const _=typeof S.payload.turnId=="string"?S.payload.turnId:null,Y=typeof S.payload.itemId=="string"?S.payload.itemId:null,me=typeof S.payload.sequence=="number"&&Number.isFinite(S.payload.sequence)?S.payload.sequence:null;_&&Y?tr(_,Y,S.payload.delta,me,S.payload.createdAt??S.timestamp):Qa(S.payload.delta),_&&We(pe=>pe&&(pe.serverTurnId===null||pe.serverTurnId===_)?{...pe,serverTurnId:_,id:_,status:pe.status==="failed"?pe.status:"inProgress",tokenUsage:pe.tokenUsage}:pe)}if(S.type==="thread.context.updated"){const _=S.payload.contextUsage&&typeof S.payload.contextUsage=="object"?S.payload.contextUsage:null;if(_){const Y=_;K(me=>me&&{...me,thread:{...me.thread,contextUsage:Y}}),ee(me=>me.map(pe=>pe.id===t?{...pe,contextUsage:Y}:pe))}}if(S.type==="thread.turn.token.updated"&&typeof S.payload.turnId=="string"&&S.payload.tokenUsage&&typeof S.payload.tokenUsage=="object"){const _=S.payload.turnId,Y=S.payload.tokenUsage,me=S.payload.priceEstimate&&typeof S.payload.priceEstimate=="object"?S.payload.priceEstimate:null;K(pe=>{if(!pe)return pe;const Ot=Pc(pe.turns,_,Y,me);return Ot===pe.turns?pe:{...pe,turns:Ot}}),We(pe=>pe&&(pe.serverTurnId===_||pe.id===_)?{...pe,tokenUsage:Y,priceEstimate:me}:pe)}if(S.type==="thread.turn.started"||S.type==="thread.turn.completed"||S.type==="thread.turn.failed"||S.type==="thread.updated"||S.type==="thread.goal.updated"||S.type==="thread.goal.cleared"||S.type==="thread.request.created"||S.type==="thread.request.resolved"){if(S.type==="thread.goal.updated"){const _=S.payload.goal&&typeof S.payload.goal=="object"?S.payload.goal:null,Y=Array.isArray(S.payload.goalHistory)?S.payload.goalHistory:null;Is({status:"ready",data:_,error:null}),K(me=>me&&(Y?{...me,goal:_,goalHistory:Y}:_?{...me,goal:_,goalHistory:ys(me.goalHistory??[],_)}:{...me,goal:_}))}if(S.type==="thread.goal.cleared"){const _=Array.isArray(S.payload.goalHistory)?S.payload.goalHistory:null;Is({status:"ready",data:null,error:null}),K(Y=>Y&&(_?{...Y,goal:null,goalHistory:_}:{...Y,goal:null}))}if(b(),S.type==="thread.turn.started"){et(),X(""),H(null),Q.current=null;const _=typeof S.payload.turnId=="string"?S.payload.turnId:null;_&&We(Y=>Y&&{...Y,serverTurnId:_,id:_,status:Y.status==="failed"?Y.status:"inProgress",error:null,tokenUsage:Y.tokenUsage})}if(S.type==="thread.turn.completed"||S.type==="thread.turn.failed"){et(),X("");const _=typeof S.payload.turnId=="string"?S.payload.turnId:null;_&&(Q.current=_,S.type==="thread.turn.failed"&&We(Y=>Y&&(Y.serverTurnId===_||Y.id===_)?{...Y,status:"failed",error:typeof S.payload.error=="string"?S.payload.error:"Unable to complete the turn.",tokenUsage:Y.tokenUsage}:Y))}}if(S.type==="thread.request.created"&&kc(S.payload.request)&&(se.current.delete(S.payload.request.id),K(_=>_&&jc(_,S.payload.request))),S.type==="thread.request.resolved"&&typeof S.payload.requestId=="string"){const _=S.payload.requestId;se.current.add(_),K(Y=>Y&&Nc(Y,_))}if((S.type==="thread.item.started"||S.type==="thread.item.completed")&&S.payload.item&&typeof S.payload.item=="object"&&typeof S.payload.turnId=="string"){const _=S.payload.turnId,Y=S.payload.item;typeof Y.id=="string"&&typeof Y.text=="string"&&er(_,Y)}S.type==="thread.plan.updated"&&Array.isArray(S.payload.plan)&&v({turnId:String(S.payload.turnId??""),explanation:typeof S.payload.explanation=="string"?S.payload.explanation:null,plan:S.payload.plan})}},de=()=>{const S=p.current;if(!(!S||S.readyState!==Nt))try{S.send(JSON.stringify({type:"supervisor.ping",timestamp:new Date().toISOString()}))}catch{d.current=!0,J(),B(),De()}},xe=()=>{var Y;if(m||!w.current){De();return}const S=((Y=p.current)==null?void 0:Y.readyState)??os;if(S===Xs||S===Nt){De();return}const _=Wn(he);p.current=_,De(),_.addEventListener("message",me=>{if(p.current===_)try{const pe=JSON.parse(me.data);(pe.type==="supervisor.connected"||pe.type==="supervisor.pong")&&(k.current=Date.now(),De())}catch{}}),_.addEventListener("open",()=>{p.current===_&&(d.current=!0,Xe(me=>me+1),b(),de(),De())}),_.addEventListener("close",()=>{p.current===_&&(p.current=null),d.current=!0,B(),De()}),_.addEventListener("error",()=>{p.current===_&&(p.current=null),d.current=!0,B(),De()})},W=async()=>{var S;if(!(m||!w.current||N.current)){N.current=!0,De();try{await Li();const _=d.current;x.current=new Date().toISOString(),_&&(d.current=!1,b()),(((S=p.current)==null?void 0:S.readyState)??os)!==Nt&&xe()}catch{x.current=null,d.current=!0,B()}finally{N.current=!1,De()}}},Oe=()=>{w.current=!0,d.current=!0,De(),xe(),W()},Te=()=>{w.current=!1,x.current=null,k.current=null,d.current=!0,E(),J(),De()},Ie=()=>{var Y;if(m||!w.current){De();return}const S=((Y=p.current)==null?void 0:Y.readyState)??os,_=k.current===null?null:Date.now()-k.current;S===Nt&&_!==null&&_>Ys?(d.current=!0,J(),B()):S===Nt?de():S!==Xs&&xe(),W(),De()};return window.addEventListener("online",Oe),window.addEventListener("offline",Te),xe(),W(),y=window.setInterval(Ie,Bc),()=>{m=!0,window.removeEventListener("online",Oe),window.removeEventListener("offline",Te),E(),y!==null&&window.clearInterval(y),et(),J()}},[tr,et,t,ot,Qa,De,er]),n.useEffect(()=>{if(!((u==null?void 0:u.thread.activeTurnId)!==null||(u==null?void 0:u.thread.status)==="running"||Ne!==null||Jt.length>0||j.length>0||ke!==null||C!==null))return;const y=window.setInterval(()=>{ot({showLoading:!1,clearError:!1,reportError:!1})},Wc);return()=>{window.clearInterval(y)}},[u==null?void 0:u.thread.activeTurnId,u==null?void 0:u.thread.status,j.length,C,ke,ot,Jt.length,Ne]);const ar=n.useCallback(async()=>{var m;if(!(!u||u.turns.length===0||Vt)){ks(!0),le(null);try{const y=(m=u.turns[0])==null?void 0:m.id,b=await _r(t,{limit:_c,...y?{beforeTurnId:y}:{}});K(E=>E?{...E,turns:yc(E.turns,b.turns),totalTurnCount:Math.max(E.totalTurnCount??E.turns.length,b.totalTurnCount??b.turns.length)}:b)}catch(y){le(y instanceof Error?y.message:"Unable to load earlier turns.")}finally{ks(!1)}}},[u,t,Vt]);async function Uo(m){var Oe,Te,Ie;if(ze==="shell"){if((u==null?void 0:u.thread.isLoaded)===!1)return await Os({attachShell:!0}),!1;let S=!1;if((ue==null?void 0:ue.shellInputEnabled)!==!0&&((ue==null?void 0:ue.loading)===!1&&(ue==null?void 0:ue.isConnecting)!==!0&&(ue==null?void 0:ue.status)!=="creating"&&(ue==null?void 0:ue.status)!=="workspace_missing"&&(await((Oe=h.current)==null?void 0:Oe.toggleConnection()),S=!0),(ue==null?void 0:ue.isConnecting)===!0))return le("Connecting to the shell. Try again after it attaches."),!1;if(((Te=h.current)==null?void 0:Te.sendCommand(m.prompt))??!1)le(null);else return le(S?"Shell is still attaching. Try again after it connects.":"Connect the shell before sending commands."),!1;return!0}if(It)return le(It),!1;lt(!0),le(null),T(S=>S+1);const y=D.current,b=y?{...y.thread,...Z.current??{}}:null,E=(b==null?void 0:b.model)??null,B=(b==null?void 0:b.reasoningEffort)??null,J=Ec(),he=`optimistic-${Date.now()}`,de=`optimistic-steer-${J}`,xe=new Date().toISOString();let W=[];try{let S=D.current;if(S&&!S.thread.isLoaded){const Se={...S.thread,...Z.current??{}},qe=await Ms(t,{...S.thread.model?{model:S.thread.model}:{}}),Me={...qe,thread:{...qe.thread,model:Se.model??qe.thread.model,reasoningEffort:Se.reasoningEffort??qe.thread.reasoningEffort,collaborationMode:Se.collaborationMode??qe.thread.collaborationMode}};S=Me,D.current=Me,K(rs=>rs?{...Me,turns:xt(rs.turns,Me.turns,Me.thread.activeTurnId)}:Me),ee(rs=>rs.map(Rr=>Rr.id===Me.thread.id?Me.thread:Rr))}const _=S?{...S.thread,...Z.current??{}}:null,Y=(_==null?void 0:_.status)==="running"?_.activeTurnId:null,me=ze==="chat"&&!!Y;me&&Y?vt(Se=>[...Se,{id:de,clientRequestId:J,turnId:Y,prompt:m.prompt,createdAt:xe,status:"steering"}]):(W=ln(m.attachments),et(),X(""),We({id:he,serverTurnId:null,startedAt:xe,status:"sending",error:null,prompt:m.prompt,attachmentPreviews:W,model:E,reasoningEffort:B,reasoningEffortAvailable:Ks(Ae,E),tokenUsage:null,priceEstimate:null}));const pe={prompt:m.prompt,clientRequestId:J,..._!=null&&_.model?{model:_.model}:{},..._!=null&&_.reasoningEffort?{reasoningEffort:_.reasoningEffort}:{},..._!=null&&_.collaborationMode?{collaborationMode:_.collaborationMode}:{},...(Ie=m.attachments)!=null&&Ie.length?{attachments:m.attachments}:{}},Ot=await ad(t,pe),Ge=Z.current&&Object.keys(Z.current).length>0?{...Ot,...Z.current}:Ot;K(Se=>Se&&{...Se,thread:Ge}),ee(Se=>Se.map(qe=>qe.id===Ge.id?Ge:qe)),me&&Y?Ge.activeTurnId!==null&&Ge.activeTurnId!==Y&&Ge.lastTurnStartedAt!==(_==null?void 0:_.lastTurnStartedAt)?(W=ln(m.attachments),et(),X(""),v(null),vt(qe=>qe.filter(Me=>Me.id!==de)),We({id:he,serverTurnId:Ge.activeTurnId,startedAt:Ge.lastTurnStartedAt??xe,status:"inProgress",error:null,prompt:m.prompt,attachmentPreviews:W,model:E,reasoningEffort:B,reasoningEffortAvailable:Ks(Ae,E),tokenUsage:null,priceEstimate:null})):vt(qe=>qe.map(Me=>Me.id===de?{...Me,turnId:Ge.activeTurnId??Me.turnId,status:"accepted"}:Me)):(We(Se=>Se&&Se.id===he?{...Se,id:Ge.activeTurnId??Se.id,serverTurnId:Ge.activeTurnId??Se.serverTurnId,status:"inProgress",error:null,tokenUsage:Se.tokenUsage,priceEstimate:Se.priceEstimate}:Se),v(null)),Ss({prompt:"",attachments:[]})}catch(S){const _=S instanceof ie?S.payload.message:S instanceof Error?S.message:"Unable to send prompt.";S instanceof ie?le(S.payload.message):le(_),vt(Y=>Y.filter(me=>me.clientRequestId!==J)),We(Y=>Y&&Y.id===he?{...Y,status:"failed",error:_}:Y)}finally{lt(!1)}}async function rr(m){if(oe.current)return!1;oe.current=!0;try{return await Uo(m)}finally{oe.current=!1}}async function $o(){const m=D.current;if(!m)return le("Thread detail is still loading."),!1;if(m.thread.isLoaded)return!0;lt(!0),le(null);try{const y=await Ms(t,{...m.thread.model?{model:m.thread.model}:{}});return K(b=>b?{...y,turns:xt(b.turns,y.turns,y.thread.activeTurnId)}:y),ee(b=>b.map(E=>E.id===y.thread.id?y.thread:E)),!0}catch(y){return le(y instanceof Error?y.message:"Unable to connect this thread before setting its goal."),!1}finally{lt(!1)}}async function Do(m){var he;const y=((he=m.objective)==null?void 0:he.trim())??"",b=y?`optimistic-goal-${Date.now()}`:null,E=new Date().toISOString(),B=D.current,J=(B==null?void 0:B.thread)??null;b&&(T(de=>de+1),We({id:b,serverTurnId:null,startedAt:E,status:"sending",error:null,prompt:y,attachmentPreviews:[],model:(J==null?void 0:J.model)??null,reasoningEffort:(J==null?void 0:J.reasoningEffort)??null,reasoningEffortAvailable:Ks(Ae,(J==null?void 0:J.model)??null),tokenUsage:null,priceEstimate:null}));try{await Eo(m),await ot({showLoading:!1,clearError:!1,reportError:!1}),b&&We(de=>de&&de.id===b?{...de,status:"completed",error:null}:de)}catch(de){const xe=de instanceof ie?de.payload.message:de instanceof Error?de.message:"Unable to set goal.";throw le(xe),b&&We(W=>W&&W.id===b?{...W,status:"failed",error:xe}:W),de}}async function Mo(){const m=u==null?void 0:u.thread.providerSessionId;if(m)try{await navigator.clipboard.writeText(m),Gt("copied")}catch{Gt("failed")}}async function Os(m){if(u){lt(!0),le(null),et(),X("");try{if(u.thread.isLoaded){const b=await sd(t);K(E=>E?{...b,turns:xt(E.turns,b.turns,b.thread.activeTurnId)}:b),La(null),ee(E=>E.map(B=>B.id===b.thread.id?b.thread:B)),Rt(!1);return}const y=await Ms(t,{...u.thread.model?{model:u.thread.model}:{}});K(b=>b?{...y,turns:xt(b.turns,y.turns,y.thread.activeTurnId)}:y),ee(b=>b.map(E=>E.id===y.thread.id?y.thread:E)),m!=null&&m.attachShell&&ze==="shell"&&Rt(!0)}catch(y){le(y instanceof Error?y.message:"Unable to change connection state.")}finally{lt(!1)}}}async function es(){var m;if(ze==="shell"){const y=((m=h.current)==null?void 0:m.sendControl("ctrl_c"))??!1;le(y?null:"Connect the shell before sending Ctrl-C.");return}lt(!0),le(null);try{const y=u!=null&&u.thread.activeTurnId?await Hr(t,{turnId:u.thread.activeTurnId}):await Hr(t);K(b=>b&&{...b,thread:y}),ee(b=>b.map(E=>E.id===y.id?y:E)),et(),X("")}catch(y){le(y instanceof Error?y.message:"Unable to interrupt turn.")}finally{lt(!1)}}async function Ls(m){if(!u)return;const y=u,b={...Z.current??{},...m.model!==void 0?{model:m.model}:{},...m.reasoningEffort!==void 0?{reasoningEffort:m.reasoningEffort}:{},...m.fastMode!==void 0?{fastMode:m.fastMode}:{},...m.collaborationMode!==void 0?{collaborationMode:m.collaborationMode}:{},...m.sandboxMode!==void 0?{sandboxMode:m.sandboxMode}:{}},E={...u.thread,...b};$a(!0),Z.current=b,D.current={...u,thread:E},K(B=>B&&{...B,thread:E}),ee(B=>B.map(J=>J.id===E.id?{...J,...E}:J));try{const B=await od(t,{...m.model!==void 0?{model:m.model}:{},...m.reasoningEffort!==void 0?{reasoningEffort:m.reasoningEffort}:{},...m.fastMode!==void 0?{fastMode:m.fastMode}:{},...m.collaborationMode!==void 0?{collaborationMode:m.collaborationMode}:{},...m.sandboxMode!==void 0?{sandboxMode:m.sandboxMode}:{}});Z.current=null,D.current=y?{...y,thread:B}:null,K(J=>J&&{...J,thread:B}),ee(J=>J.map(he=>he.id===B.id?B:he))}catch(B){Z.current=null,D.current=y,K(y),ee(J=>J.map(he=>he.id===y.thread.id?y.thread:he)),le(B instanceof Error?B.message:"Unable to update thread settings.")}finally{$a(!1)}}const nr=n.useCallback(async(m,y)=>{if((ce==null?void 0:ce.kind)==="shared"&&ce.threadAccess==="read"){le("This shared session is view only.");return}_a(m),le(null);try{await yt(async()=>{const b=await bd(t,m,y);return se.current.add(m),b})}catch(b){le(b instanceof Error?b.message:"Unable to answer this request.")}finally{_a(null)}},[t,ce,yt]),or=n.useCallback(m=>Wi(t,m),[t]),lr=n.useCallback(async(m,y)=>{le(null);try{await yt(()=>rd(m,y))}catch(b){throw le(b instanceof Error?b.message:"Unable to cancel queued prompt."),b}},[yt]),ir=n.useCallback(async(m,y)=>{le(null);try{await yt(()=>nd(m,y))}catch(b){throw le(b instanceof Error?b.message:"Unable to steer queued prompt."),b}},[yt]);async function Us(){if(u){Da(!0),le(null);try{const m=await ld(t);K(y=>y&&{...y,thread:m}),ee(y=>y.map(b=>b.id===m.id?m:b))}catch(m){le(m instanceof Error?m.message:"Unable to compact this thread context.")}finally{Da(!1)}}}async function dr(m,y){try{const b=await Hn(m,{title:y});ee(E=>E.map(B=>B.id===b.id?{...B,title:b.title,updatedAt:b.updatedAt}:B)),K(E=>E&&E.thread.id===b.id?{...E,thread:{...E.thread,title:b.title,updatedAt:b.updatedAt}}:E)}catch(b){throw le(b instanceof Error?b.message:"Unable to rename thread."),b}}async function cr(){if(Ze){Ba(!0),le(null);try{await Bn(Ze.id),ee(y=>y.filter(b=>b.id!==Ze.id));const m=Ze.id===(u==null?void 0:u.thread.id);if(Cs(null),m){const y=Re.find(b=>b.id!==Ze.id&&b.workspaceId===(u==null?void 0:u.thread.workspaceId))??Re.find(b=>b.id!==Ze.id);r(y?Fe(y.id):Ht())}}catch(m){le(m instanceof Error?m.message:"Unable to delete thread.")}finally{Ba(!1)}}}function ur(){Ca(m=>m==="chat"?(u!=null&&u.thread.isLoaded&&Rt(!0),"shell"):"chat")}async function mr(){var y;const m=await((y=h.current)==null?void 0:y.copyLastCommandOutput());le(m?null:"Unable to copy the last shell command output.")}function hr(m){var b,E;const y=m==="clear"?((b=h.current)==null?void 0:b.sendCommand("clear"))??!1:((E=h.current)==null?void 0:E.sendControl(m))??!1;le(y?null:"Connect the shell before sending control input.")}n.useEffect(()=>{if(!(!Ua||ze!=="shell"||!h.current||(u==null?void 0:u.thread.isLoaded)===!1||(ue==null?void 0:ue.loading)!==!1)){if((ue==null?void 0:ue.status)==="attached"){Rt(!1);return}Rt(!1),h.current.toggleConnection()}},[ze,u==null?void 0:u.thread.isLoaded,Ua,ue==null?void 0:ue.loading,ue==null?void 0:ue.status]),n.useEffect(()=>{if(ze!=="shell")return;const m=window.requestAnimationFrame(()=>{var y;(y=h.current)==null||y.refreshLayout({syncBackendSize:!1})});return()=>{window.cancelAnimationFrame(m)}},[ze]);const It=u?u.workspacePathStatus==="missing"?"Restore this workspace path on the current machine before continuing.":pt&&Xt.status==="loading"?"Checking relay permissions...":pt&&Xt.status==="failed"?Xt.error??"Unable to verify relay permissions.":(ce==null?void 0:ce.kind)==="shared"&&ce.threadAccess==="read"?"This shared session is view only.":null:null,{floatingMobileComposerBottomOffset:_o,timelineBottomSpacer:fr,useFloatingMobileComposer:Ho}=Oc({activeView:ze,composerHostRef:P,threadId:(u==null?void 0:u.thread.id)??t}),Bo=u?e.jsxs("dl",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"relative pr-9",children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Session ID"}),e.jsx("dd",{className:"mt-1 break-all text-[var(--theme-fg)]",children:u.thread.providerSessionId??"Unavailable"}),u.thread.providerSessionId&&e.jsx("button",{type:"button","aria-label":"Copy session ID",title:ft==="copied"?"Copied":ft==="failed"?"Copy failed":"Copy session ID",onClick:()=>void Mo(),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 ${ft==="copied"?"ui-status-info":ft==="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(Yc,{})})})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Source"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:u.thread.source==="local_codex_import"?`Imported local ${u.thread.provider} session`:`${u.thread.provider} supervisor thread`})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Status"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:sl(u.thread.status)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Created"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:Ar(u.thread.createdAt)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Workspace"}),e.jsx("dd",{className:"mt-1 break-words text-[var(--theme-fg)]",children:u.workspace.absPath})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Workspace path"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:u.workspacePathStatus==="present"?"Present":"Missing on this machine"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Active turn"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:u.thread.activeTurnId??"None"})]})]}):null,Wo=null,pr=Ne&&u?Ic(u.turns,Ne):null,xr=n.useMemo(()=>Ne&&!pr?{id:Ne.id,startedAt:Ne.startedAt,status:Ne.status,error:Ne.error,model:Ne.model,reasoningEffort:Ne.reasoningEffort,reasoningEffortAvailable:Ne.reasoningEffortAvailable,tokenUsage:Ne.tokenUsage,priceEstimate:Ne.priceEstimate,items:[{id:`${Ne.id}-user-message`,kind:"userMessage",text:Ne.prompt,attachmentPreviewUrls:Object.fromEntries(Ne.attachmentPreviews.map(m=>[m.path,m.url]))}]}:null,[pr,Ne]),Pt=(u==null?void 0:u.thread.isLoaded)??!1,ts=Pt?it.status==="connected"?"ui-action-success shadow-[var(--theme-shadow)]":it.status==="reconnecting"?"thread-live-connection-reconnecting ui-status-success shadow-[var(--theme-shadow)]":it.status==="offline"?"ui-status-danger shadow-[var(--theme-shadow)]":"ui-status-warning shadow-[var(--theme-shadow)]":"host-icon-button border shadow-[var(--theme-shadow)]",gr=Xc(Pt,it),ss=[gr,Pt?null:"Tap to connect this thread",it.lastHealthyAt?`Last healthy ${Ar(it.lastHealthyAt)}`:null].filter(Boolean).join(" · "),vr=Pt?e.jsx("div",{role:"status","aria-live":"polite","aria-label":gr,title:ss,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition ${ts}`,children:e.jsx(is,{status:it.status})}):e.jsx("button",{type:"button",onClick:()=>void Os(),disabled:ht||!u,"aria-label":ht?"Connecting thread":"Connect thread",title:ht?"Connecting thread":ss,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition ${ts}`,children:e.jsx(is,{status:"detached"})}),br=Pt?e.jsx("div",{title:ss,className:`hidden lg:inline-flex h-9 w-9 items-center justify-center rounded-full transition ${ts}`,children:e.jsx(is,{status:it.status})}):e.jsx("button",{type:"button",onClick:()=>void Os(),disabled:ht||!u,title:ht?"Connecting thread":ss,className:`hidden lg:inline-flex h-9 w-9 items-center justify-center rounded-full transition ${ts}`,children:e.jsx(is,{status:"detached"})}),yr=Fa.data??(u==null?void 0:u.goal)??null,wr=(u==null?void 0:u.goalHistory)??[],Fo=yr?ys(wr,yr):eo(wr),as=n.useMemo(()=>(ce==null?void 0:ce.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:`${nn(ce.threadAccess)} / ${on(ce.workspaceAccess)}`,children:[e.jsx("span",{children:nn(ce.threadAccess)}),e.jsx("span",{className:"host-muted",children:"/"}),e.jsx("span",{className:"truncate",children:on(ce.workspaceAccess)})]}):null,[ce]),qo=n.useMemo(()=>e.jsx("button",{type:"button","aria-label":"Thread actions",title:"Thread actions",onClick:()=>As(!0),disabled:!u,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"})}),[u]),Vo=n.useMemo(()=>e.jsxs("div",{className:"relative flex items-center justify-end gap-1.5",children:[as,vr]}),[vr,as]),zo=n.useMemo(()=>e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[as,br]}),[br,as]),Go=n.useMemo(()=>({livePlan:ke,liveItems:C,respondingRequestId:Ma,onRespondToRequest:nr,scrollRequestKey:A,previousTurnScrollRequestKey:ne,nextTurnScrollRequestKey:we,bottomSpacer:fr,className:"thread-timeline-surface min-h-0 flex-1",onTailVisibilityChange:Ue,onPreviousTurnAvailabilityChange:rt,onNextTurnAvailabilityChange:mt,loadingEarlier:Vt,onLoadEarlier:ar,onOpenThread:zt,answeredRequestNotes:(u==null?void 0:u.answeredRequestNotes)??Fc,activityNotes:(u==null?void 0:u.activityNotes)??qc,pendingSteers:(u==null?void 0:u.pendingSteers)??Vc,optimisticSteers:Jt,optimisticTurn:xr}),[u==null?void 0:u.answeredRequestNotes,u==null?void 0:u.activityNotes,u==null?void 0:u.pendingSteers,ar,nr,C,ke,Vt,zt,Jt,Ma,A,ne,we,fr,xr]),jr=u?{busy:ze==="chat"?ht:!1,settingsBusy:fo,error:null,model:u.thread.model,agentLabel:((Er=Le.find(m=>m.model===u.thread.agentId))==null?void 0:Er.displayName)??u.thread.agentId??null,reasoningEffort:u.thread.reasoningEffort,fastMode:u.thread.fastMode??!1,collaborationMode:u.thread.collaborationMode,sandboxMode:u.thread.sandboxMode??null,modelOptions:Ae,contextUsage:u.thread.contextUsage,subscriptionUsage:G,capabilities:O,toolboxItems:(fe==null?void 0:fe.toolboxItems)??[],hookCommandTemplates:(fe==null?void 0:fe.hookCommandTemplates)??[],mcpConfigFormat:(fe==null?void 0:fe.mcpConfigFormat)??"none",followTail:be,threadConnected:u.thread.isLoaded,shellAvailable:Ta,disabled:!!It,...It?{disabledPlaceholder:It}:{},shellControlState:ue,draftPrompt:Oa.prompt,draftAttachments:Oa.attachments,onDraftChange:Ss,canInterrupt:!!(u.thread.activeTurnId&&He),...He?{onInterrupt:es}:{},...He?{onCompact:Us,onOpenForkTurns:wo,onForkLatest:bo,onForkTurn:yo,onOpenSkills:So,onOpenMcp:ko,onOpenHooks:No,onCreateHook:vo,onUpdateHook:Ro,onTrustHook:Co,onUntrustHook:To}:{},goalState:Fa,goalHistory:Fo,...He?{onOpenGoal:jo,onPrepareGoalSubmit:$o,onUpdateGoal:Do}:{},...Es?{...At?{onReadProviderConfig:()=>Mn(u.thread.provider,Es),onWriteProviderConfig:m=>_n(u.thread.provider,Es,{content:m})}:{}}:{},onToggleFollow:()=>T(m=>m+1),canJumpToPreviousTurn:je,onJumpToPreviousTurn:()=>ge(m=>m+1),canJumpToNextTurn:nt,onJumpToNextTurn:()=>ve(m=>m+1),...He?{onUpdateSettings:Ls}:{},onToggleView:ur,onShellCopy:mr,...He?{onShellControl:hr}:{},compactBusy:po,skillsState:Po,mcpState:Io,hooksState:Ao,forkTurnOptionsState:go}:null,Nr=u?{busy:ht,settingsBusy:!1,error:u.thread.isLoaded?(ue==null?void 0:ue.error)??null:null,followTail:!1,capabilities:O,toolboxItems:(fe==null?void 0:fe.toolboxItems)??[],hookCommandTemplates:(fe==null?void 0:fe.hookCommandTemplates)??[],mcpConfigFormat:(fe==null?void 0:fe.mcpConfigFormat)??"none",threadConnected:u.thread.isLoaded,shellAvailable:Ta,shellControlState:ue,canInterrupt:!!(u.thread.isLoaded&&(ue!=null&&ue.isCommandRunning)&&He),...He?{onInterrupt:es}:{},onToggleView:ur,onShellCopy:mr,...He?{onShellControl:hr}:{}}:null,kr=n.useCallback(m=>u?Pa({threadId:u.thread.id,path:m}):"",[u==null?void 0:u.thread.id,Pa]),Sr=Mc({setError:le,workspaceId:(u==null?void 0:u.workspace.id)??null,access:Lo}),Cr=n.useCallback(m=>{const y=D.current;if(!y)return;const b=Kc(m.path,y.workspace.absPath);if(b===null){le(`Cannot open ${m.path}; it is outside this workspace.`);return}Ca("chat"),ho(E=>({path:b,...m.line!==void 0?{line:m.line}:{},requestId:((E==null?void 0:E.requestId)??0)+1}))},[]),Jo=n.useMemo(()=>({openThread:zt,getThreadHref:Ra,getNewThreadHref:Aa,renderNewThreadDialogContent:Ia,...At?{renameThread:dr}:{},...At?{deleteThread:Cs}:{},cancelPendingSteer:lr,...He?{steerPendingPrompt:ir}:{},sendPrompt:rr,...He?{interrupt:es}:{},...He?{compact:Us}:{},...He?{updateSettings:Ls}:{},loadHistoryItemDetail:or,getImageAssetUrl:kr,openWorkspaceFile:Cr,workspace:Sr,shell:Ea}),[kr,Aa,Ra,Ia,Us,lr,ir,es,or,Cr,rr,dr,Ls,Ea,zt,He,At,Sr]),Ko=u!=null&&u.thread.workspaceId?Ht(u.thread.workspaceId):ws(),Yo=n.useMemo(()=>e.jsxs(e.Fragment,{children:[e.jsx(al,{open:Kt,busy:Rs||Ps,turnsState:Wa,shareAvailable:Ja,...pt&&(ce==null?void 0:ce.kind)==="shared"?{shareUnavailableMessage:"Only the owner can share this session."}:{},shareState:za,onCancel:()=>{!Rs&&!Ps&&As(!1)},onLoadTurns:Va,onExport:qa,...Ja?{onCreateShare:Ka,onOpenDeviceSharing:Xa,onRevokeShare:Ya}:{}}),e.jsx(ua,{open:Ze!==null,title:"Delete Thread",description:Ze?`Delete ${jl(Ze.title)} from supervisor. The backend session id will no longer appear in this workspace list.`:"",confirmLabel:"Delete Thread",busy:Ts,onCancel:()=>{Ts||Cs(null)},onConfirm:()=>void cr()})]}),[Ze,Ts,Rs,Kt,Wa,Ka,cr,qa,Xa,Ya,Va,pt,Ps,za]);return e.jsx(rl,{threads:Re,detail:u,status:M,loading:Sa,error:Sa?null:xo,plugins:l,adapter:Jo,metaContent:Bo,settingsContent:Wo,globalSettingsContent:e.jsx(ga,{embedded:!0}),mobileHeaderAction:Vo,workspaceReturnHref:Ko,onCloseAppNavigation:(o==null?void 0:o.closeNav)??(()=>{}),threadActionsButton:qo,surfaceActions:zo,workspaceFeatures:zc,workspaceFocusPathRequest:mo,activeView:ze,liveOutput:j,timelineProps:Go,timelineComponent:ol,useFloatingMobileComposer:Ho,floatingMobileComposerBottomOffset:_o,composerHostRef:P,shellPanelRef:h,shellPanelComponent:nl,shellEffectiveTheme:(o==null?void 0:o.effectiveTheme)??"dark",shellThemeMode:(o==null?void 0:o.themeMode)??"system",...o!=null&&o.setThemeMode?{onShellThemeModeChange:o.setThemeMode}:{},onShellStateChange:La,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:Yo,...jr?{composerProps:jr}:{},...Nr?{shellComposerProps:Nr}:{}})}function cn(){const t=at(),[s,a]=n.useState(""),[r,o]=n.useState(tt),[l,i]=n.useState([]),[c,p]=n.useState(!0),[g,N]=n.useState(!1),[x,k]=n.useState(null);n.useEffect(()=>{let h=!1;return p(!0),Ct().then(P=>{var U,R;if(h)return;i(P);const $=((U=P.find(L=>L.isDefault&&L.enabled))==null?void 0:U.provider)??((R=P.find(L=>L.enabled))==null?void 0:R.provider)??tt;o($)}).catch(()=>{h||i([])}).finally(()=>{h||p(!1)}),()=>{h=!0}},[]);const w=n.useMemo(()=>l.length>0?l:[{provider:tt,displayName:Ir[tt].displayName,enabled:!0}],[l]);async function d(h){h.preventDefault();const P=s.trim();if(!P){k("Session ID is required.");return}N(!0),k(null);try{const $=await Zi({sessionId:P,provider:r});t(Fe($.thread.id))}catch($){$ instanceof ie?k($.payload.message):k($ instanceof Error?$.message:"Unable to import session.")}finally{N(!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:d,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:h=>o(h.target.value),disabled:g||c,className:"host-form-control mt-2 w-full rounded-lg border px-4 py-3 outline-none transition",children:w.map(h=>e.jsxs("option",{value:h.provider,children:[h.displayName||Ir[h.provider].displayName,h.enabled?"":" (not ready)"]},h.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:h=>a(h.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"})]}),x&&e.jsx("div",{className:"host-error rounded-lg border px-4 py-3 text-sm",children:x}),e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:e.jsx("button",{type:"submit",disabled:g,className:"ui-action-primary rounded-lg px-5 py-3 font-medium transition disabled:cursor-not-allowed",children:g?"Importing...":"Import Session"})})]})]})}function ro({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 un(){const t=at(),[s]=ca(),a=s.get("workspaceId"),r=s.get("title");function o(){if(window.history.length>1){t(-1);return}if(a){t(Ht(a));return}t(ws())}return e.jsx(ro,{eyebrow:"New Thread",title:"Start a backend session",description:"Choose the workspace, agent or model, and approval mode for the new thread.",maxWidthClassName:"max-w-3xl",children:e.jsx(ka,{initialWorkspaceId:a,initialTitle:r,onCancel:o,onCreated:l=>t(Fe(l.id))})})}function Zc(t){return ps(t)}function Qc({getThreadHref:t,onOpenThread:s,getNewThreadHref:a,renderThreadLink:r,onCloseAppNavigation:o,...l}){const i=at(),c=Ft(),p=o??(c==null?void 0:c.closeNav),g=l.effectiveTheme??(c==null?void 0:c.effectiveTheme),N=l.themeMode??(c==null?void 0:c.themeMode),x=l.onThemeModeChange??(c==null?void 0:c.setThemeMode);return e.jsx(ll,{...l,workspaceReturnHref:l.workspaceReturnHref??ws(),globalSettingsContent:l.globalSettingsContent??e.jsx(ga,{embedded:!0}),...g?{effectiveTheme:g}:{},...N?{themeMode:N}:{},...x?{onThemeModeChange:x}:{},getThreadHref:t??(k=>Fe(k)),onOpenThread:s??(k=>i(Fe(k))),getNewThreadHref:a??Zc,renderNewThreadDialogContent:l.renderNewThreadDialogContent??(({close:k,closeNavigation:w,currentWorkspaceId:d})=>e.jsx(ka,{variant:"dialog",initialWorkspaceId:d,onCancel:k,onCreated:h=>{k(),w(),i(Fe(h.id))}})),renderThreadLink:r??(({thread:k,children:w,className:d,onClick:h})=>e.jsx(Be,{to:Fe(k.id),className:d,onClick:h,children:w})),...p?{onCloseAppNavigation:p}:{}})}function no({open:t,title:s,label:a,value:r,busy:o=!1,onChange:l,onCancel:i,onSubmit:c}){if(n.useEffect(()=>{if(!t)return;function g(N){N.key==="Escape"&&!o&&i()}return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[o,i,t]),!t)return null;function p(g){g.preventDefault(),c()}return gn.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:p,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:g=>l(g.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 mn(){const[t]=ca(),s=at(),a=Ft(),r=t.get("workspaceId"),[o,l]=n.useState([]),[i,c]=n.useState([]),[p,g]=n.useState(null),[N,x]=n.useState(!0),[k,w]=n.useState(null),[d,h]=n.useState(null),[P,$]=n.useState(""),[U,R]=n.useState(null),[L,z]=n.useState(null),[te,Q]=n.useState(!1),D=(a==null?void 0:a.defaultBackend)??tt,oe=n.useCallback(async()=>{try{return(await Dn(D)).status}catch(M){const O=(await Ct()).find(F=>F.enabled&&F.capabilities.sessions.resume&&F.capabilities.turns.start);if(O)return O.status;throw M}},[D]),Z=n.useCallback(async()=>{x(!0),w(null);try{const[M,ae,O]=await Promise.all([oe(),xa(),pa()]);g(M),l(ae),c(O)}catch(M){w(M instanceof Error?M.message:"Unable to load threads.")}finally{x(!1)}},[oe]);n.useEffect(()=>{if(r===null)return;Z();const M=Wn(ae=>{l(O=>O.map(F=>F.id===ae.threadId?{...F,status:ae.type==="thread.updated"&&typeof ae.payload.status=="string"?ae.payload.status:F.status,lastError:(ae.type==="thread.turn.failed"||ae.type==="thread.turn.completed")&&typeof ae.payload.error=="string"?ae.payload.error:F.lastError,title:ae.type==="thread.updated"&&typeof ae.payload.title=="string"?ae.payload.title:F.title}:F))});return()=>{M.close()}},[Z,r]);const se=Object.fromEntries(i.map(M=>[M.id,M.label])),u=i.find(M=>M.id===r)??null,K=n.useMemo(()=>r?o.filter(M=>M.workspaceId===r):[],[r,o]),Re=K.filter(M=>M.status==="running").length,ee=r?ps(r):ps();if(ao({enabled:r!==null,setThreads:l}),r===null)return e.jsx(fs,{to:ws(),replace:!0});function Ae(){switch(p==null?void 0:p.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 Pe(M,ae){try{const O=await Hn(M,{title:ae});l(F=>F.map(G=>G.id===O.id?{...G,title:O.title,updatedAt:O.updatedAt}:G))}catch(O){throw w(O instanceof Error?O.message:"Unable to rename thread."),O}}async function Le(){if(!d)return;const M=P.trim();if(M){R(d);try{await Pe(d,M),h(null),$("")}finally{R(null)}}}async function V(){if(L){Q(!0);try{await Bn(L.id),l(M=>M.filter(ae=>ae.id!==L.id)),z(null)}catch(M){w(M instanceof Error?M.message:"Unable to delete thread.")}finally{Q(!1)}}}return e.jsx(Qc,{threads:o,workspaceLabels:se,status:p,loading:N,error:k,viewportConstrained:r!==null,showMobileAppMenu:!0,showMobileThreadNavToggle:!1,showMobileNewThreadShortcut:!1,currentWorkspaceId:r,currentWorkspaceLabel:(u==null?void 0:u.label)??null,onRenameThread:Pe,onDeleteThread:z,children:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"host-panel flex min-h-0 flex-1 flex-col overflow-hidden rounded-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:u?`${u.label} threads`:"All threads",children:u?u.label:"All Threads"}),e.jsx(Be,{to:ee,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 ${Ae()}`}),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:(p==null?void 0:p.lastError)??((p==null?void 0:p.state)==="ready"?"Ready":(p==null?void 0:p.state)??"Checking")})]})]})}),!N&&!k&&K.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:[K.length," total"]}),Re>0&&e.jsxs("span",{className:"host-muted text-xs",children:["· ",Re," running"]})]}),e.jsx("div",{className:"mt-3 min-h-0 flex-1",children:e.jsx(il,{threads:K,currentWorkspaceId:r,workspaceLabels:se,onOpenThread:M=>s(Fe(M)),onBeginRenameThread:M=>{h(M.id),$(M.title)},onDeleteThread:M=>z(M),scrollable:!0,maxHeightClassName:"max-h-full",showDeleteButton:!0,showSessionCopyButton:!0})})]}),!N&&!k&&K.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(no,{open:d!==null,title:"Rename Thread",label:"Thread Title",value:P,busy:U!==null,onChange:$,onCancel:()=>{h(null),$("")},onSubmit:()=>void Le()}),e.jsx(ua,{open:L!==null,title:"Delete Thread",description:L?`Delete ${gl(L.title)} from supervisor. The backend session id will no longer appear in this workspace list.`:"",confirmLabel:"Delete Thread",busy:te,onCancel:()=>{te||z(null)},onConfirm:()=>void V()})]})})}function hn(t){const s=t.trim(),a=s.replace(/[\\/]+$/,"");if(!a)return"";if(oo(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 oo(t){const s=t.trim();return/^https?:\/\/.+/i.test(s)||/^ssh:\/\/.+/i.test(s)||/^git@[^:]+:.+/.test(s)}function eu({initialPath:t="",initialLabel:s="",submitLabel:a="Save Workspace",error:r,busy:o=!1,surface:l=!0,onSubmit:i}){const c=hn(t),[p,g]=n.useState(t),[N,x]=n.useState(s||c),[k,w]=n.useState(null),d=n.useRef(c);n.useEffect(()=>{const $=hn(p);x(U=>!U.trim()||U===d.current?$:U),d.current=$},[p]);async function h($){$.preventDefault();const U=p.trim();if(!U){w("Workspace path or Git URL is required.");return}w(null);const R=N.trim(),L=oo(U)?"gitUrl":"absPath";await i(R?{[L]:U,label:R}:{[L]:U})}const P=l?"host-panel space-y-5 rounded-lg border p-5 sm:p-6":"space-y-5";return e.jsxs("form",{onSubmit:h,className:P,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:p,onChange:$=>g($.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:N,onChange:$=>x($.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."})]}),(k||r)&&e.jsx("div",{className:"host-error rounded-lg border px-4 py-3 text-sm",children:k??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 fn(){const t=at(),[s,a]=n.useState(null),[r,o]=n.useState(!1),[l,i]=n.useState(null);n.useEffect(()=>{$n().then(p=>i(p.devHome)).catch(()=>i(null))},[]);async function c(p){o(!0),a(null);try{const g="absPath"in p&&l&&/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(p.absPath)?{...p,absPath:`${l.replace(/\/$/,"")}/${p.absPath}`}:p,N=await yd(g);t(Ht(N.id))}catch(g){g instanceof ie?a(g.payload.message):a(g instanceof Error?g.message:"Unable to create workspace.")}finally{o(!1)}}return e.jsx(ro,{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(eu,{busy:r,error:s,submitLabel:"Create Workspace",surface:!1,onSubmit:c})})}function pn(t){return Date.parse(t.lastOpenedAt??t.createdAt)}function tu(t,s){return t.isFavorite!==s.isFavorite?t.isFavorite?-1:1:pn(s)-pn(t)}function su(t){return t?new Date(t).toLocaleString():"Never opened"}function au(t,s=28){return t.length<=s?t:`...${t.slice(-(s-3))}`}function ru({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 nu(){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 xn(){const t=at(),[s,a]=n.useState([]),[r,o]=n.useState(!0),[l,i]=n.useState(null),[c,p]=n.useState(null),[g,N]=n.useState(null),[x,k]=n.useState(null),[w,d]=n.useState(""),[h,P]=n.useState(null),[$,U]=n.useState(null),[R,L]=n.useState(null),[z,te]=n.useState(!1),[Q,D]=n.useState(!1),[oe,Z]=n.useState(0);n.useEffect(()=>{let V=!1,M=null;const ae=F=>{var G;return F.reason instanceof ie&&((G=F.reason.payload.details)==null?void 0:G.reason)==="hosted_sandbox_starting"},O=async()=>{const[F,G]=await Promise.allSettled([pa(),Fl()]);if(!V){if(F.status==="rejected"&&ae(F)||G.status==="rejected"&&ae(G)){D(!0),o(!0),N(null),p(null),Z(ye=>ye+1),M=setTimeout(()=>void O(),1500);return}D(!1),o(!1),F.status==="fulfilled"?(a(F.value),N(null)):N(F.reason instanceof Error?F.reason.message:"Unable to load workspaces."),G.status==="fulfilled"?(i(G.value),p(null)):p(G.reason instanceof Error?G.reason.message:"Unable to load supervisor config.")}};return O(),()=>{V=!0,M&&clearTimeout(M)}},[]);async function se(V){const M={...V,isFavorite:!V.isFavorite};a(ae=>ae.map(O=>O.id===V.id?M:O));try{const ae=await Nd(V.id,{isFavorite:!V.isFavorite});a(O=>O.map(F=>F.id===ae.id?ae:F))}catch(ae){a(O=>O.map(F=>F.id===V.id?V:F)),N(ae instanceof Error?ae.message:"Unable to update workspace.")}}async function u(V){const M=w.trim();if(M){P(V);try{const ae=await wd(V,{label:M});a(O=>O.map(F=>F.id===ae.id?ae:F)),k(null),d("")}catch(ae){N(ae instanceof Error?ae.message:"Unable to rename workspace.")}finally{P(null)}}}function K(V){k(V.id),d(V.label)}function Re(){k(null),d("")}function ee(V){t(Ht(V))}async function Ae(){if(R){te(!0);try{await jd(R.id,{confirmWorkspaceId:R.id,confirmLabel:R.label}),a(V=>V.filter(M=>M.id!==R.id)),L(null)}catch(V){N(V instanceof Error?V.message:"Unable to delete workspace.")}finally{te(!1)}}}function Pe(V,M){(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),ee(M))}const Le=n.useMemo(()=>[...s].sort(tu),[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(ba,{}),e.jsx(Be,{to:Lr("/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(Be,{to:Lr("/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:[Q?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 ",oe]})]}):r?e.jsx("div",{className:"host-empty-state rounded-lg border px-6 py-12 text-center",children:"Loading workspace registry..."}):null,g&&e.jsx("div",{className:"host-error rounded-lg border px-4 py-4",children:g}),!r&&!g&&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&&Le.length>0&&e.jsx("div",{className:"space-y-2 overflow-x-hidden",children:Le.map(V=>e.jsxs("article",{role:"link",tabIndex:0,onClick:()=>ee(V.id),onKeyDown:M=>Pe(M,V.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 ${V.label}`,title:"Delete workspace",onClick:M=>{M.stopPropagation(),L(V)},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(nu,{})}),e.jsx("button",{type:"button","aria-label":V.isFavorite?`Unpin workspace ${V.label}`:`Pin workspace ${V.label}`,title:V.isFavorite?"Unpin workspace":"Pin workspace",onClick:M=>{M.stopPropagation(),se(V)},className:`inline-flex h-7 w-7 items-center justify-center rounded-full border transition ${V.isFavorite?"host-warning-pill":"host-icon-button"}`,children:e.jsx(ru,{active:V.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:V.label,children:V.label}),e.jsx("button",{type:"button",onClick:M=>{M.stopPropagation(),K(V)},"aria-label":`Rename workspace ${V.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":V.absPath,title:V.absPath,onClick:M=>{M.stopPropagation(),U(V.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:au(V.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: ",su(V.lastOpenedAt)]})})]})})]},V.id))})]}),e.jsx(ou,{config:l,error:c,vmStarting:Q,workspaceCount:s.length})]}),e.jsx(no,{open:x!==null,title:"Rename Workspace",label:"Workspace Label",value:w,busy:h!==null,onChange:d,onCancel:Re,onSubmit:()=>x?u(x):void 0}),e.jsx(dl,{open:$!==null,title:"Workspace Path",text:$??"",onClose:()=>U(null)}),e.jsx(ua,{open:R!==null,title:"Delete Workspace",description:R?`Delete ${R.label} from supervisor. This also removes its threads and local supervisor metadata.`:"",confirmLabel:"Delete Workspace",busy:z,onCancel:()=>{z||L(null)},onConfirm:()=>void Ae()})]})}function ou({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(ds,{label:"Workspace root",value:(t==null?void 0:t.workspaceRoot)??(a?"VM is starting…":"Loading...")}),e.jsx(ds,{label:"Environment",value:t?`${t.environment} · ${t.host}:${t.port}`:a?"Connecting automatically…":s??"Loading..."}),e.jsx(ds,{label:"Version",value:t?`${t.appName} ${t.appVersion}`:"Loading..."}),e.jsx(ds,{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 ds({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 lo="remote-codex-theme-mode",io="remote-codex-default-backend",co="remote-codex-auto-collapse-completed-turns";function lu({children:t}){const s=n.useMemo(()=>({fetchPlugins:Fi,importPlugin:qi,updatePlugin:Vi,deletePlugin:zi}),[]);return e.jsx(cl,{adapter:s,builtinPlugins:ul,children:t})}function iu(){if(typeof window>"u")return"system";const t=window.localStorage.getItem(lo);return t==="light"||t==="dark"||t==="system"?t:"system"}function du(){if(typeof window>"u")return tt;const t=window.localStorage.getItem(io);return pl(t)??tt}function cu(){return typeof window>"u"?!0:window.localStorage.getItem(co)!=="false"}function uu(t){return(t==null?void 0:t.trim())||"Remote Codex"}function mu(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 hu(){const t=Wt();return n.useEffect(()=>{document.title=uu(mu(t.pathname))},[t.pathname]),null}function fu(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function pu({themeMode:t,setThemeMode:s,effectiveTheme:a}){const[r,o]=n.useState(!1),[l,i]=n.useState(!1),[c,p]=n.useState(du),[g,N]=n.useState(cu),[x,k]=n.useState(null),w=Wt(),h=!(/^\/threads\/(?:import|new)$/.test(w.pathname)||/^\/devices\/[^/]+\/threads\/(?:import|new)$/.test(w.pathname))&&(/^\/threads\/[^/]+$/.test(w.pathname)||/^\/devices\/[^/]+\/threads\/[^/]+$/.test(w.pathname)),P=w.pathname==="/threads"||/^\/devices\/[^/]+\/threads$/.test(w.pathname),$=h||P,U=P||h,R=w.pathname==="/workspaces"||/^\/devices\/[^/]+\/workspaces$/.test(w.pathname);n.useEffect(()=>{o(!1)},[w.pathname,w.search]),n.useEffect(()=>{const Q=D=>{const oe=D.detail;if(oe.state==="connected"){k(null);return}k(Z=>({attempt:oe.attempt,startedAt:(Z==null?void 0:Z.startedAt)??Date.now()}))};return window.addEventListener(oa,Q),()=>window.removeEventListener(oa,Q)},[]);function L(Q){p(Q),window.localStorage.setItem(io,Q)}function z(Q){N(Q),window.localStorage.setItem(co,Q?"true":"false")}const te={navOpen:r,openNav:()=>o(!0),toggleNav:()=>o(Q=>!Q),closeNav:()=>o(!1),settingsOpen:l,openSettings:()=>{o(!1),i(!0)},closeSettings:()=>i(!1),themeMode:t,setThemeMode:s,effectiveTheme:a,defaultBackend:c,setDefaultBackend:L,autoCollapseCompletedTurns:g,setAutoCollapseCompletedTurns:z};return e.jsxs(ml.Provider,{value:te,children:[e.jsxs("div",{className:`bg-[var(--app-bg)] text-[var(--app-fg)] ${$?"fixed inset-0 overflow-hidden overscroll-none":"min-h-screen"}`,children:[x?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 ",x.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 ${U?"max-w-none":"max-w-[1600px]"} ${$?"absolute inset-0 pb-0 sm:pb-4":"pb-4"} ${U?h?"pt-0":P?"pt-[env(safe-area-inset-top)] sm:pt-0":"pt-[calc(env(safe-area-inset-top)+4rem)] sm:pt-4":R?"pt-[env(safe-area-inset-top)] sm:pt-4":"pt-4"} ${$?"overflow-hidden overscroll-none px-0":"px-4 sm:px-6"}`,children:e.jsx("section",{className:`min-w-0 ${$?h?"h-full min-h-0 overflow-hidden overscroll-none":"h-full overflow-hidden overscroll-none":""}`,children:e.jsx(Qo,{})})})]}),e.jsx(ga,{})]})}function xu({children:t}){const[s,a]=n.useState({status:"checking"});async function r(i){try{const c=await ql();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 ie&&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 Vl(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(qn,{onLogin:o})]}):t}function gu({children:t}){var r;const[s,a]=n.useState({status:"checking"});return n.useEffect(()=>{let o=!1;return Tt().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(fs,{to:"/",replace:!0}):((r=s.session.user)==null?void 0:r.role)==="admin"?e.jsx(fs,{to:"/relay-admin",replace:!0}):t}function vu({children:t}){return ut()?e.jsx(gu,{children:t}):e.jsx(xu,{children:t})}function uo(){return ut()?e.jsx(gc,{}):e.jsx(fs,{to:"/workspaces",replace:!0})}function bu({themeMode:t,setThemeMode:s,effectiveTheme:a}){return e.jsxs(vn,{children:[e.jsx(Ce,{path:"/",element:e.jsx(uo,{})}),e.jsxs(Ce,{element:e.jsx(pu,{themeMode:t,setThemeMode:s,effectiveTheme:a}),children:[e.jsx(Ce,{path:"/workspaces",element:e.jsx(xn,{})}),e.jsx(Ce,{path:"/workspaces/new",element:e.jsx(fn,{})}),e.jsx(Ce,{path:"/relay-account",element:e.jsx(Td,{})}),e.jsx(Ce,{path:"/relay-devices",element:e.jsx(rc,{})}),e.jsx(Ce,{path:"/threads",element:e.jsx(mn,{})}),e.jsx(Ce,{path:"/threads/import",element:e.jsx(cn,{})}),e.jsx(Ce,{path:"/threads/new",element:e.jsx(un,{})}),e.jsx(Ce,{path:"/threads/:id",element:e.jsx(dn,{})}),e.jsx(Ce,{path:"/devices/:relayDeviceId/workspaces",element:e.jsx(xn,{})}),e.jsx(Ce,{path:"/devices/:relayDeviceId/workspaces/new",element:e.jsx(fn,{})}),e.jsx(Ce,{path:"/devices/:relayDeviceId/threads",element:e.jsx(mn,{})}),e.jsx(Ce,{path:"/devices/:relayDeviceId/threads/import",element:e.jsx(cn,{})}),e.jsx(Ce,{path:"/devices/:relayDeviceId/threads/new",element:e.jsx(un,{})}),e.jsx(Ce,{path:"/devices/:relayDeviceId/threads/:id",element:e.jsx(dn,{})})]})]})}function yu(){const[t,s]=n.useState(()=>iu()),[a,r]=n.useState(()=>fu()),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(lo,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(Zo,{children:[e.jsx(hu,{}),e.jsx(lu,{children:e.jsxs(vn,{children:[e.jsx(Ce,{path:"/",element:e.jsx(uo,{})}),e.jsx(Ce,{path:"/relay-guide",element:e.jsx(xc,{})}),e.jsx(Ce,{path:"/relay-portal",element:e.jsx(vc,{})}),e.jsx(Ce,{path:"/relay-admin",element:e.jsx(Ed,{})}),e.jsx(Ce,{path:"/*",element:e.jsx(vu,{children:e.jsx(bu,{themeMode:t,setThemeMode:s,effectiveTheme:o})})})]})})]})})}el.createRoot(document.getElementById("root")).render(e.jsx(tl.StrictMode,{children:e.jsx(yu,{})}));
|