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