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.
Files changed (28) hide show
  1. package/README.md +9 -0
  2. package/apps/relay-server/dist/index.js +17 -1
  3. package/apps/supervisor-api/dist/index.js +2189 -1798
  4. package/apps/supervisor-web/dist/assets/index-BO9S3vTX.css +1 -0
  5. package/apps/supervisor-web/dist/assets/index-GqVDOqbI.js +22 -0
  6. package/apps/supervisor-web/dist/assets/{thread-ui-Dmrigdek.js → thread-ui-BWC_ljvN.js} +11 -11
  7. package/apps/supervisor-web/dist/index.html +3 -3
  8. package/bin/remote-codex.mjs +426 -35
  9. package/docs/windows.md +81 -0
  10. package/package.json +14 -3
  11. package/packages/claude/src/runtimeAdapter.test.ts +32 -4
  12. package/packages/claude/src/runtimeAdapter.ts +21 -22
  13. package/packages/codex/src/appServerManager.test.ts +47 -0
  14. package/packages/codex/src/appServerManager.ts +6 -2
  15. package/packages/codex/src/runtimeAdapter.test.ts +9 -2
  16. package/packages/opencode/src/historyItems.ts +7 -6
  17. package/packages/opencode/src/runtimeAdapter.ts +7 -11
  18. package/packages/process-runtime/src/index.test.ts +132 -0
  19. package/packages/process-runtime/src/index.ts +253 -0
  20. package/packages/shared/src/index.ts +12 -0
  21. package/scripts/service-manager.mjs +112 -4
  22. package/scripts/verify-relay-supervisor-smoke.mjs +262 -0
  23. package/scripts/windows/install-relay-supervisor-task.ps1 +44 -0
  24. package/scripts/windows/relay-smoke.ps1 +16 -0
  25. package/scripts/windows/uninstall-relay-supervisor-task.ps1 +27 -0
  26. package/scripts/windows/validate-real-codex.mjs +680 -0
  27. package/apps/supervisor-web/dist/assets/index-BT0SM9C-.js +0 -21
  28. package/apps/supervisor-web/dist/assets/index-BcCLYWAf.css +0 -1
@@ -1,21 +0,0 @@
1
- import{j as e,r as n,L as Ue,u as Ye,d as Ut,b as nn,e as sa,f as Fo,N as is,B as qo,h as on,i as Ne,O as Vo,k as zo,c as Go}from"./react-vendor-Dfg_6BLf.js";import{u as Dt,a as ln,t as Jo,f as yr,T as Ko,C as aa,b as Yo,c as Zo,d as Xo,e as Qo,g as el,L as tl,P as sl,h as al,A as rl}from"./thread-ui-Dmrigdek.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 nl=["codex","claude","opencode"],Je="codex",wr={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 ol(t){return typeof t=="string"&&nl.includes(t)}function ll(t){return ol(t)?t:null}var jr=15;function il(t){return t.replace(/\s+/g," ").trim()}function dl(t){const s=il(t);if(!s)return"";const a=Array.from(s);return a.length<=jr?s:`${a.slice(0,jr).join("")}...`}function cl(t,s){const a=new Set(t.map(r=>r.id));return[...s.filter(r=>!a.has(r.id)),...t]}function ul(t,s,a=null){var v;const r=new Set,o=s.reduceRight((d,p)=>(r.has(p.id)||(r.add(p.id),d.unshift(p)),d),[]),l=new Map(o.map(d=>[d.id,d])),i=o.filter(d=>d.items.some(p=>p.kind==="userMessage")),c=new Set,f=new Set,g=t.reduceRight((d,p)=>(f.has(p.id)||(f.add(p.id),d.unshift(p)),d),[]);for(const d of g){if(l.has(d.id)){c.add(d.id);continue}if(d.status!=="inProgress")continue;const p=(v=d.items.find(P=>P.kind==="userMessage"))==null?void 0:v.text.trim(),O=d.startedAt?Date.parse(d.startedAt):Number.NaN;if(!p||!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===p&&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 ml=["codex","claude","opencode"],dn="codex",cn={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"}},Nr=15;function hl(t){return t.replace(/\s+/g," ").trim()}function fl(t){const s=hl(t);if(!s)return"";const a=Array.from(s);return a.length<=Nr?s:`${a.slice(0,Nr).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 pl=[{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."}],un={hostConfigFiles:[],toolboxItems:[],hookCommandTemplates:[],providerConfigFormat:"none",mcpConfigFormat:"none",configArchives:!1,buildRestart:!1},xl={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 zs(t){const s=xl[t];return{packageName:s.packageName,installed:t==="codex",installedVersion:null,latestVersion:null,installCommand:s.installCommand,updateCommand:s.updateCommand,busy:!1,lastError:null}}function gl(t,s){return{provider:t,displayName:s,description:`${s} backend descriptor is not available.`,enabled:!1,isDefault:t===dn,status:{state:"stopped",transport:cn[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:un,installation:zs(t)}}function Os(t){const s=t.installation??zs(t.provider);return{...t,installation:{...zs(t.provider),...s}}}const vt=[...ml.map(t=>gl(t,cn[t].displayName))];function vl(t){var s;return((s=vt.find(a=>a.provider===t))==null?void 0:s.managementSchema)??un}function bl(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 yl(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 wl=/^\/devices\/([^/]+)(?:\/|$)/,jl=/^(?:\/devices\/[^/]+)?\/threads\/([^/?#]+)(?:[/?#]|$)/;function mn(t){const s=wl.exec(t);return s?decodeURIComponent(s[1]??""):null}function Ke(){return typeof window>"u"?null:mn(window.location.pathname)}function Nl(t){const s=jl.exec(t);return s?decodeURIComponent(s[1]??""):null}function kl(){return typeof window>"u"?null:Nl(window.location.pathname)}function $t(t,s){if(!s)return t;const a=t.startsWith("/")?t:`/${t}`;return`/devices/${encodeURIComponent(s)}${a}`}function kr(t){return $t(t,Ke())}function Gs(t,s){return $t(`/threads/${encodeURIComponent(t)}`,s)}function $e(t){return Gs(t,Ke())}function Sl(t,s){const a=t?`?workspaceId=${encodeURIComponent(t)}`:"";return $t(`/threads${a}`,s)}function Ot(t){return Sl(t,Ke())}function Cl(t,s){const a=t?`?workspaceId=${encodeURIComponent(t)}`:"";return $t(`/threads/new${a}`,s)}function ds(t){return Cl(t,Ke())}function Js(t){return $t("/workspaces",t)}function xs(){return Js(Ke())}class le extends Error{constructor(s,a){super(a.message),this.statusCode=s,this.payload=a}}const Ks="remote-codex-auth-token",Ys="remote-codex-relay-token",Zs="remote-codex-relay-admin-token",hn="remote-codex-relay-mode",Xs="remote-codex-relay-device-id",Qs="remote-codex-relay-thread-id",ea="remote-codex:hosted-vm-wake";function Sr(t){typeof window<"u"&&window.dispatchEvent(new CustomEvent(ea,{detail:t}))}function Tl(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 fn(){return typeof window>"u"?null:window.localStorage.getItem(Ks)}function El(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(Ks,t);return}window.localStorage.removeItem(Ks)}}function pn(){return typeof window>"u"?null:window.localStorage.getItem(Ys)}function Rl(){return typeof window>"u"?null:window.localStorage.getItem(Zs)}function ra(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(Ys,t);return}window.localStorage.removeItem(Ys)}}function xn(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(hn)==="true"}function qe(){typeof window>"u"||window.localStorage.setItem(hn,"true")}function at(){return bt()}function gn(){return typeof window>"u"?null:Ke()??window.localStorage.getItem(Xs)}function rs(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(Xs,t);return}window.localStorage.removeItem(Xs)}}function Il(){return typeof window>"u"?null:kl()??window.localStorage.getItem(Qs)}function ns(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(Qs,t);return}window.localStorage.removeItem(Qs)}}function na(t){if(!bt())return t;if(t.startsWith("/api/")){const s=gn();return s?`/relay/devices/${encodeURIComponent(s)}${t}`:`/relay${t}`}return t}function vn(t){return na(t)}function Al(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 Pl(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)??Al(t.status),message:r,...o?{details:o}:{}}}async function bn(t){var o,l;const s=Pl(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=wn({...s,headers:r},a.auth);let l=0;for(;;){const c=await fetch(na(String(t)),o);if(c.ok)return l>0&&Sr({state:"connected",attempt:l}),await c.json();const f=await bn(c);if(!(c.status===503&&((i=f.details)==null?void 0:i.reason)==="hosted_sandbox_starting")||l>=60)throw new le(c.status,f);l+=1,Sr({state:"starting",attempt:l}),await Tl(1500,o.signal)}}function Ol(t){const s=String(t);return s.includes("/exports/pdf")?s.includes("format=html")?"remote-codex-transcript.html":"remote-codex-transcript.pdf":"download"}function Ll(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 yn(t,s){const a=await fetch(na(String(t)),wn(s));if(!a.ok){const o=await bn(a);throw new le(a.status,o)}const r=Ll(a.headers.get("content-disposition"))??Ol(t);return{blob:await a.blob(),filename:r}}function wn(t={},s="default"){const a=new Headers(t.headers),r=bt();if(s!=="none"&&!a.has("Authorization"))if(s==="relay-admin"){const o=Rl();o&&a.set("Authorization",`Bearer ${o}`)}else{const o=pn(),l=fn();r&&o?a.set("Authorization",`Bearer ${o}`):!r&&l&&a.set("Authorization",`Bearer ${l}`)}return{...t,credentials:t.credentials??"same-origin",headers:a}}function Cr(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 Ul(){return I("/api/config/runtime")}function Dl(){return I("/api/auth/session",{cache:"no-store"})}async function $l(t){const s=await I("/api/auth/login",{method:"POST",body:JSON.stringify(t)});return El(s.token??null),s}function yt(){return I("/relay/auth/session",{cache:"no-store"})}async function Ml(t){qe();const s=await I("/relay/auth/login",{method:"POST",body:JSON.stringify(t)},{auth:"none"});return ra(s.token),s}function jn(){return qe(),I("/relay/auth/session",{cache:"no-store"},{auth:"relay-admin"})}async function Hl(t){qe();const s=await I("/relay/auth/login",{method:"POST",body:JSON.stringify({identifier:t.username,password:t.password})},{auth:"none"});return xn(s.token),s}async function _l(){return xn(null),jn()}async function Bl(t){qe();const s=await I("/relay/auth/register",{method:"POST",body:JSON.stringify(t)},{auth:"none"});return ra(s.token??null),s}async function Wl(){const t=await I("/relay/auth/logout",{method:"POST"});return ra(null),rs(null),ns(null),t}function Nn(){return I("/relay/portal")}function Fl(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 ql(t){return I("/relay/devices",{method:"POST",body:JSON.stringify(t)})}function Vl(t){return I(`/relay/devices/${encodeURIComponent(t)}`,{method:"DELETE"})}function zl(t){return I("/relay/account",{method:"PATCH",body:JSON.stringify(t)})}function Gl(t){return I("/relay/account/password",{method:"PATCH",body:JSON.stringify(t)})}function Jl(t){return I("/relay/shares",{method:"POST",body:JSON.stringify(t)})}function Kl(t,s){return I(`/relay/shares/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(s)})}function kn(t){return I(`/relay/shares/${encodeURIComponent(t)}`,{method:"DELETE"})}function Yl(t){return I("/relay/grants",{method:"POST",body:JSON.stringify(t)})}function Zl(t,s){return I(`/relay/grants/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(s)})}function Xl(t){return I(`/relay/grants/${encodeURIComponent(t)}`,{method:"DELETE"})}function Ql(t){const s=t?`?days=${encodeURIComponent(String(t))}`:"";return I(`/relay/admin${s}`,void 0,{auth:"relay-admin"})}function ei(){return I("/relay/admin/hosted-sandboxes/capability",void 0,{auth:"relay-admin"})}function ti(){return I("/relay/admin/hosted-sandboxes",void 0,{auth:"relay-admin"})}function si(){return I("/relay/admin/hosted-sandboxes/reconciliation",void 0,{auth:"relay-admin"})}function ai(){return I("/relay/admin/hosted-sandboxes/reconciliation/run",{method:"POST"},{auth:"relay-admin"})}function ri(t){return I(`/relay/admin/hosted-sandboxes/reconciliation/orphan-instances/${encodeURIComponent(t)}`,{method:"DELETE"},{auth:"relay-admin"})}function ni(t){return I(`/relay/admin/hosted-sandboxes/reconciliation/orphan-credentials/${encodeURIComponent(t)}`,{method:"DELETE"},{auth:"relay-admin"})}function oi(t){return I("/relay/admin/hosted-sandboxes",{method:"POST",body:JSON.stringify(t)},{auth:"relay-admin"})}function Tr(t,s){return I(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}/members`,{method:"PUT",body:JSON.stringify({assignedUserIds:s})},{auth:"relay-admin"})}function li(t,s){return I(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}/settings`,{method:"PATCH",body:JSON.stringify(s)},{auth:"relay-admin"})}function Er(t,s){return I(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}/${s}`,{method:"POST"},{auth:"relay-admin"})}function ii(t,s){return I(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}/snapshots`,{method:"POST",body:JSON.stringify({name:s})},{auth:"relay-admin"})}function di(t){return I(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}/backends/codex/files`,void 0,{auth:"relay-admin"})}function ci(t,s){return I(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}/backends/codex/files`,{method:"PUT",body:JSON.stringify(s)},{auth:"relay-admin"})}function ui(t){return I(`/relay/admin/hosted-sandboxes/${encodeURIComponent(t)}`,{method:"DELETE"},{auth:"relay-admin"})}function mi(t){return I("/relay/admin/settings/registration",{method:"PATCH",body:JSON.stringify(t)},{auth:"relay-admin"})}function hi(t,s){return I(`/relay/admin/users/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({enabled:s})},{auth:"relay-admin"})}function fi(t){return I(`/relay/admin/users/${encodeURIComponent(t)}`,{method:"DELETE"},{auth:"relay-admin"})}function pi(t,s){return I(`/relay/admin/users/${encodeURIComponent(t)}/reset-password`,{method:"POST",body:JSON.stringify({password:s})},{auth:"relay-admin"})}function xi(t){return I(`/relay/admin/registrations/${encodeURIComponent(t)}/approve`,{method:"POST"},{auth:"relay-admin"})}function gi(t){return I(`/relay/admin/registrations/${encodeURIComponent(t)}/reject`,{method:"POST"},{auth:"relay-admin"})}function Sn(){return I("/api/config/workspace-settings",{cache:"no-store"})}function vi(t){return I("/api/config/workspace-settings",{method:"PATCH",body:JSON.stringify(t)})}function cs(){return I("/api/agent-runtimes",{cache:"no-store"})}function Cn(t){return I(`/api/agent-runtimes/${encodeURIComponent(t)}/status`,{cache:"no-store"})}function bi(t){return I(`/api/agent-runtimes/${encodeURIComponent(t)}/subscription-usage`,{cache:"no-store"})}function yi(t){return I(`/api/agent-runtimes/${encodeURIComponent(t)}/restart`,{method:"POST"})}function Tn(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 En(t,s){return I(`/api/config/providers/${encodeURIComponent(t)}/files/${encodeURIComponent(s)}`,{cache:"no-store"})}function Rn(t,s,a){return I(`/api/config/providers/${encodeURIComponent(t)}/files/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function wi(t){return I(`/api/config/providers/${encodeURIComponent(t)}/archives`,{cache:"no-store"})}function ji(t,s={}){return I(`/api/config/providers/${encodeURIComponent(t)}/archives`,{method:"POST",body:JSON.stringify(s)})}function Ni(t,s,a){return I(`/api/config/providers/${encodeURIComponent(t)}/archives/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function ki(t,s){return I(`/api/config/providers/${encodeURIComponent(t)}/archives/${encodeURIComponent(s)}/apply`,{method:"POST"})}function Si(){return I("/api/service/build-restart",{method:"POST"})}function Ci(){return I("/healthz",{cache:"no-store"})}function oa(){return I("/api/workspaces")}function Ti(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 Ei(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 Ri(t,s){const a=new URLSearchParams({path:s.path});return vn(`/api/workspaces/${encodeURIComponent(t)}/files/raw?${a.toString()}`)}function Ii(t,s){const a=new URLSearchParams({path:s.path});return vn(`/api/threads/${encodeURIComponent(t)}/assets/image?${a.toString()}`)}function Ai(t,s){const a=new URLSearchParams({path:s.path});return yn(`/api/workspaces/${encodeURIComponent(t)}/files/download?${a.toString()}`,{cache:"no-store"})}function Pi(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 Oi(t,s){return I(`/api/workspaces/${encodeURIComponent(t)}/files`,{method:"PUT",body:JSON.stringify(s)})}function la(){return I("/api/threads")}function Rr(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 Li(t,s){return I(`/api/threads/${t}/items/${encodeURIComponent(s)}/detail`)}function Ui(){return I("/api/plugins",{cache:"no-store"})}function Di(t){return I("/api/plugins/import",{method:"POST",body:JSON.stringify(t)})}function $i(t,s){return I(`/api/plugins/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(s)})}function Mi(t){return I(`/api/plugins/${encodeURIComponent(t)}`,{method:"DELETE"})}function Hi(t){return I(`/api/threads/${t}/export-turns`,{cache:"no-store"})}function _i(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 Bi(t,s){return yn(_i(t,s),{cache:"no-store"})}function Wi(t){return I(`/api/threads/${t}/shell`)}function Fi(t){return I("/api/threads/start",{method:"POST",body:JSON.stringify(t)})}function qi(t){return I("/api/threads/import",{method:"POST",body:JSON.stringify(typeof t=="string"?{sessionId:t}:t)})}function Vi(t,s={}){return I(`/api/threads/${t}/shell`,{method:"POST",...Object.keys(s).length>0?{body:JSON.stringify(s)}:{}})}function zi(t){return I(`/api/shells/${t}/terminate`,{method:"POST"})}function Gi(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 Ji(t){return I(`/api/threads/${t}/disconnect`,{method:"POST"})}function Ki(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:Cr(l,i),placeholder:l.placeholder}));r.append("attachmentManifest",JSON.stringify(o));for(const[l,i]of a.entries())r.append("attachments",i.file,Cr(i,l));return I(`/api/threads/${t}/prompt`,{method:"POST",body:r})}function Ir(t,s={}){return I(`/api/threads/${t}/interrupt`,{method:"POST",body:JSON.stringify(s)})}function In(t,s){return I(`/api/threads/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function An(t){return I(`/api/threads/${t}`,{method:"DELETE"})}function Yi(t,s){return I(`/api/threads/${t}/pending-steers/${encodeURIComponent(s)}`,{method:"DELETE"})}function Zi(t,s){return I(`/api/threads/${t}/pending-steers/${encodeURIComponent(s)}/steer`,{method:"POST"})}function Xi(t,s){return I(`/api/threads/${t}/settings`,{method:"PATCH",body:JSON.stringify(s)})}function Qi(t){return I(`/api/threads/${t}/compact`,{method:"POST"})}function ed(t){return I(`/api/threads/${t}/goal`,{cache:"no-store"})}function td(t,s){return I(`/api/threads/${t}/goal`,{method:"PATCH",body:JSON.stringify(s)})}function sd(t){return I(`/api/threads/${t}/goal`,{method:"DELETE"})}function ad(t){return I(`/api/threads/${t}/fork-turns`,{cache:"no-store"})}function Ar(t,s){return I(`/api/threads/${t}/fork`,{method:"POST",body:JSON.stringify(s)})}function rd(t){return I(`/api/threads/${t}/skills`,{cache:"no-store"})}function nd(t){return I(`/api/threads/${t}/mcp-servers`,{cache:"no-store"})}function od(t){return I(`/api/threads/${t}/hooks`,{cache:"no-store"})}function ld(t,s){return I(`/api/threads/${t}/hooks`,{method:"POST",body:JSON.stringify(s)})}function id(t,s){return I(`/api/threads/${t}/hooks`,{method:"PUT",body:JSON.stringify(s)})}function dd(t,s){return I(`/api/threads/${t}/hooks/trust`,{method:"POST",body:JSON.stringify(s)})}function cd(t,s){return I(`/api/threads/${t}/hooks/untrust`,{method:"POST",body:JSON.stringify(s)})}function ud(t,s,a){return I(`/api/threads/${t}/requests/${encodeURIComponent(s)}/respond`,{method:"POST",body:JSON.stringify(a)})}function md(t){return I("/api/workspaces",{method:"POST",body:JSON.stringify(t)})}function hd(t,s){return I(`/api/workspaces/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function fd(t,s){return I(`/api/workspaces/${t}`,{method:"DELETE",body:JSON.stringify(s)})}function pd(t,s){return I(`/api/workspaces/${t}/favorite`,{method:"POST",body:JSON.stringify(s)})}function Pn(t){const s=window.location.protocol==="https:"?"wss:":"ws:",a=new WebSocket(On(s));return a.addEventListener("message",r=>{try{const o=JSON.parse(r.data);gd(o)&&t(o)}catch{}}),a}function xd(t={}){const s=window.location.protocol==="https:"?"wss:":"ws:",a=new WebSocket(On(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}vd(i)&&((l=t.onShellEvent)==null||l.call(t,i))}catch{}}),{socket:a,send(r){a.send(JSON.stringify(r))}}}function On(t){const s=new URL(`${t}//${window.location.host}/ws`);if(bt()){const l=gn();s.pathname=l?`/relay/devices/${encodeURIComponent(l)}/ws`:"/relay/ws"}const a=fn(),r=pn(),o=Il();return bt()&&r&&s.searchParams.set("relaySession",r),bt()&&o&&s.searchParams.set("threadId",o),a&&s.searchParams.set("token",a),s.toString()}function gd(t){return"threadId"in t&&t.type.startsWith("thread.")&&typeof t.payload=="object"&&t.payload!==null}function vd(t){return"shellId"in t&&t.type.startsWith("shell.")&&typeof t.payload=="object"&&t.payload!==null}function ia({embedded:t=!1}={}){const s=Dt(),a=ln(),[r,o]=n.useState(""),[l,i]=n.useState({busy:!1,message:null,error:null}),[c,f]=n.useState(!1),[g,N]=n.useState(null),[x,S]=n.useState({}),v=g?x[g]:null,[d,p]=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 y=r.trim();if(!(!y||l.busy)){i({busy:!0,message:null,error:null});try{await a.importPluginManifest({manifestJson:y,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)??dn,ke=a.plugins.filter(y=>y.enabled).length,A=a.loading?"Loading...":`${ke}/${a.plugins.length} enabled`,W=P.find(y=>y.provider===ye)??vt.find(y=>y.provider===ye)??vt[0],ne=W.managementSchema??vl(W.provider),H=ne.hostConfigFiles;n.useEffect(()=>{if(!K||t||!s||!ne.configArchives)return;const y=s;function E(_){_.key==="Escape"&&y.closeSettings()}return window.addEventListener("keydown",E),()=>{window.removeEventListener("keydown",E)}},[ne.configArchives,t,K,s]),n.useEffect(()=>{if(!K)return;let y=!1;return V(E=>({...E,loading:!0,error:null})),cs().then(E=>{if(y)return;const _=[...E.map(Os),...vt.filter(ae=>!E.some(pe=>pe.provider===ae.provider))];R(_),V(ae=>({...ae,loading:!1}))}).catch(E=>{y||(R(vt),V(_=>({..._,loading:!1,error:E instanceof le?E.message:"Unable to load backend settings."})))}),()=>{y=!0}},[K]),n.useEffect(()=>{if(!K)return;let y=!1;return te(E=>({...E,loading:!0,message:null,error:null})),Sn().then(E=>{y||(Q(E),te(_=>({..._,devHomeDraft:E.devHome,loading:!1})))}).catch(E=>{y||te(_=>({..._,loading:!1,error:E instanceof le?E.message:"Unable to load workspace settings."}))}),()=>{y=!0}},[K]),n.useEffect(()=>{if(!K||!W.capabilities.management.hostConfigFiles)return;let y=!1;async function E(){S(ae=>{const pe={...ae};for(const Ee of H)pe[Ee.name]={...Tt(Ee.name),...ae[Ee.name],loading:!0,saving:!1,error:null,saveMessage:null};return pe});const _=await Promise.allSettled(H.map(async ae=>({name:ae.name,result:await En(W.provider,ae.name)})));y||S(ae=>{var Ee,Xe;const pe={...ae};for(const rt of _){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)??((Xe=H[0])==null?void 0:Xe.name);ct&&(pe[ct]={...Tt(ct),...pe[ct],loading:!1,saving:!1,error:Mt,saveMessage:null})}return pe})}return E(),()=>{y=!0}},[W.capabilities.management.hostConfigFiles,W.provider,H,K]),n.useEffect(()=>{if(!K)return;let y=!1;async function E(){Y(_=>({..._,loading:!0,error:null,message:null}));try{const _=await wi(W.provider);if(y)return;U(_),Y(ae=>({...ae,loading:!1}))}catch(_){if(y)return;Y(ae=>({...ae,loading:!1,error:_ instanceof le?_.message:"Unable to load config archives."}))}}return E(),()=>{y=!0}},[W.provider,ne.configArchives,K]);async function z(){if(!(d.busy||L.saving)){p({busy:!0,message:null,error:null});try{const y=await yi(W.provider),E=Os(y);p({busy:!1,message:E.status.state==="ready"?`${E.displayName} backend restarted.`:`${E.displayName} backend state: ${E.status.state}`,error:null}),R(_=>_.map(ae=>ae.provider===E.provider?E:ae))}catch(y){p({busy:!1,message:null,error:y instanceof le?y.message:"Unable to restart the app server."})}}}async function k(y,E){if(d.busy||L.saving)return;const _=P.find(ae=>ae.provider===y);V(ae=>({...ae,saving:!0,operatingProvider:y,operatingAction:E,message:null,error:null}));try{const ae=await Tn(y,E),pe=Os(ae);R(Ee=>Ee.map(Xe=>Xe.provider===pe.provider?pe:Xe)),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?yl(ae):`Unable to ${E} ${(_==null?void 0:_.displayName)??y}.`}))}}async function Z(){if(!(d.busy||L.saving)){p({busy:!0,message:null,error:null});try{await Si(),p({busy:!1,message:"Build and restart launched. The page may disconnect briefly.",error:null})}catch(y){p({busy:!1,message:null,error:y instanceof le?y.message:"Unable to launch build and restart."})}}}async function se(){const y=D.devHomeDraft.trim();if(!(!y||D.saving)){te(E=>({...E,saving:!0,message:null,error:null}));try{const E=await vi({devHome:y});Q(E),te(_=>({..._,devHomeDraft:E.devHome,saving:!1,message:"Workspace defaults saved."}))}catch(E){te(_=>({..._,saving:!1,error:E instanceof le?E.message:"Unable to save workspace settings."}))}}}async function Se(y){const E=x[y];if(!(!E||E.saving)){S(_=>({..._,[y]:{...Tt(y),..._[y],saving:!0,error:null,saveMessage:null}}));try{const _=await Rn(W.provider,y,{content:E.draftContent});S(ae=>({...ae,[y]:{path:_.path,exists:_.exists,originalContent:_.content,draftContent:_.content,loading:!1,saving:!1,error:null,saveMessage:"Saved"}}))}catch(_){S(ae=>({...ae,[y]:{...Tt(y),...ae[y],saving:!1,error:_ instanceof le?_.message:"Unable to save the file.",saveMessage:null}}))}}}async function ge(){if(!J.creating){Y(y=>({...y,creating:!0,message:null,error:null}));try{const y=await ji(W.provider);U(E=>[y,...E]),Y(E=>({...E,creating:!1,message:"Backup created."}))}catch(y){Y(E=>({...E,creating:!1,error:y instanceof le?y.message:"Unable to create a config backup."}))}}}async function u(y){if(!J.applyingId){Y(E=>({...E,applyingId:y.id,message:null,error:null}));try{const E=await ki(W.provider,y.id);Y(_=>({..._,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(_=>({..._,applyingId:null,error:E instanceof le?E.message:"Unable to apply the config archive."}))}}}async function j(y){const E=J.renameDraft.trim();if(!(!E||J.renamingId!==y.id)){Y(_=>({..._,message:null,error:null}));try{const _=await Ni(W.provider,y.id,{label:E});U(ae=>ae.map(pe=>pe.id===y.id?_:pe)),Y(ae=>({...ae,renamingId:null,renameDraft:"",message:"Backup renamed."}))}catch(_){Y(ae=>({...ae,error:_ instanceof le?_.message:"Unable to rename the config backup."}))}}}if(!K)return null;const X=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-3 grid gap-2",children:[a.plugins.map(y=>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:y.name}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-[var(--theme-fg-muted)]",children:y.description}),e.jsx("span",{className:"mt-2 block text-[10px] uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:[...y.capabilities.artifactTypes.map(E=>E.type),...y.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:y.source==="imported"?"Imported manifest":"Built-in module"})]}),e.jsx("input",{type:"checkbox",checked:y.enabled,onChange:E=>void a.setPluginEnabled(y.id,E.currentTarget.checked),className:"mt-1 h-4 w-4 shrink-0 accent-[var(--theme-accent-solid)]"})]},y.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:y=>{o(y.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:pl.map(y=>{const E=m===y.value;return e.jsxs("button",{type:"button",onClick:()=>s==null?void 0:s.setThemeMode(y.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:y.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:y.description})]},y.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:y=>{var E;return(E=s.setAutoCollapseCompletedTurns)==null?void 0:E.call(s,y.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:()=>f(!0),className:"rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-panel)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",children:"Manage"})]}):X]}),e.jsxs("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Workspace defaults"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Git projects clone into dev home. New workspace directories can create one missing child under this path."})]})}),e.jsxs("div",{className:"mt-3 grid gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--theme-fg-muted)]",children:"Workspace root"}),e.jsx("p",{title:(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:y=>te(E=>({...E,devHomeDraft:y.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 Z(),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(y=>{const E=y.installation,_=!E.installed&&!!E.installCommand,ae=E.installed&&!!E.updateCommand,pe=L.saving&&L.operatingProvider===y.provider,Ee=_?"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:y.displayName}),e.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${y.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:y.enabled?"Ready":E.installed?y.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]}),_||ae?e.jsx("button",{type:"button","aria-label":`${_?"Install":"Update"} ${y.displayName}`,onClick:()=>void k(y.provider,_?"install":"update"),disabled:d.busy||L.saving||!_&&!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]},y.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:[H.map(y=>{const E=x[y.name]??{path:y.name,exists:!1,originalContent:"",draftContent:"",loading:!1},_=E.draftContent!==E.originalContent;return e.jsx("button",{type:"button",onClick:()=>N(y.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:y.label}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:y.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"}):_?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"})})]})},y.name)}),H.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(y=>{const E=J.renamingId===y.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 ${y.label}`,value:J.renameDraft,onChange:_=>Y(ae=>({...ae,renameDraft:_.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 ${y.label}`,onClick:()=>void j(y),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(_=>({..._,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:y.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 ",bl(y.createdAt)]}),H.map(_=>{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:[_.name,":"," ",(ae=y.files[_.name])!=null&&ae.exists?"saved":"missing"]},_.name)})]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:()=>Y(_=>({..._,renamingId:y.id,renameDraft:y.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(y),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===y.id?"Applying...":"Apply"})]})]})},y.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:()=>f(!1),className:"ui-overlay-scrim absolute inset-0 backdrop-blur-[2px]"}),e.jsxs("section",{className:"relative z-10 flex max-h-[min(82vh,42rem)] w-full max-w-2xl flex-col overflow-hidden rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] shadow-[var(--theme-shadow)]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-[var(--theme-border)] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Plugins"}),e.jsx("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children: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:()=>f(!1),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-surface-strong)] text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",children:e.jsx(Ps,{})})]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-4",children:X})]})]}):null]}):e.jsxs("div",{className:"fixed inset-0 z-[70] flex items-start justify-center p-4 pt-[max(env(safe-area-inset-top),1rem)] sm:items-center",children:[e.jsx("button",{type:"button","aria-label":"Close Settings",onClick:s==null?void 0:s.closeSettings,className:"ui-overlay-scrim absolute inset-0 backdrop-blur-sm"}),e.jsx("section",{role:"dialog","aria-modal":"true","aria-label":"Settings",className:"relative z-10 flex max-h-[calc(100vh-2rem)] w-full max-w-4xl flex-col overflow-hidden rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] shadow-[var(--theme-shadow)]",children:ve}),g&&v?e.jsx("div",{className:"pointer-events-none fixed inset-0 z-[71] flex items-center justify-center p-4",children:e.jsxs("div",{className:"pointer-events-auto relative z-10 flex max-h-[min(88vh,56rem)] w-full max-w-3xl flex-col overflow-hidden rounded-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:v.path})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[v.error?e.jsx("span",{className:"text-xs text-rose-300",children:v.error}):v.saveMessage?e.jsx("span",{className:"text-xs text-emerald-300",children:v.saveMessage}):null,e.jsx("button",{type:"button","aria-label":`Save ${g}`,onClick:()=>void Se(g),disabled:v.loading||v.saving||v.draftContent===v.originalContent,className:"rounded-full bg-[var(--theme-accent-solid)] px-4 py-2 text-sm font-medium text-[var(--theme-accent-solid-fg)] transition hover:bg-[var(--theme-accent-solid-hover)] disabled:cursor-not-allowed disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:v.saving?"Saving...":"Save"}),e.jsx("button",{type:"button","aria-label":"Close File Editor",onClick:()=>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:v.draftContent,onChange:y=>S(E=>({...E,[g]:{...Tt(g),...E[g],draftContent:y.target.value,error:null,saveMessage:null}})),spellCheck:!1,className:"min-h-[28rem] w-full rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 font-mono text-[13px] leading-6 text-[var(--theme-fg)] outline-none transition focus:border-[var(--theme-accent-border)]",placeholder:v.loading?"Loading...":`Edit ${g} here`})})]})}):null]})}function Ln({eyebrow:t="Supervisor Access",description:s="Use the admin credentials configured on this Remote Codex server.",onLogin:a}){const[r,o]=n.useState(""),[l,i]=n.useState(""),[c,f]=n.useState(null),[g,N]=n.useState(!1);async function x(S){S.preventDefault(),f(null),N(!0);try{await a({username:r,password:l})}catch(v){v instanceof le?f(v.payload.message):f("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 Us(t,s){return t instanceof le?t.payload.message:t instanceof Error?t.message:s}function Un({className:t=""}){var J;const[s,a]=n.useState(null),[r,o]=n.useState(""),[l,i]=n.useState(""),[c,f]=n.useState(""),[g,N]=n.useState(""),[x,S]=n.useState(!0),[v,d]=n.useState(!1),[p,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(Us(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 zl({username:r});a(K=>K!=null&&K.authenticated?{...K,user:m}:K),o(m.username),P("Account updated.")}catch(m){L(Us(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 Gl({currentPassword:l,newPassword:c}),i(""),f(""),N(""),P("Password changed.")}catch(m){L(Us(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(Pr,{tone:"danger",children:R}):null,U?e.jsx(Pr,{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:v||!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(Ds,{label:"Current password",value:l,onChange:i}),e.jsx(Ds,{label:"New password",value:c,onChange:f}),e.jsx(Ds,{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:p||!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 bd(){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(Un,{})]})})}function Ds({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 Pr({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 yd(){const[t,s]=n.useState(null),[a,r]=n.useState(!0),[o,l]=n.useState(null),[i,c]=n.useState(!1),[f,g]=n.useState(null),[N,x]=n.useState("overview"),[S,v]=n.useState(7),[d,p]=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(H=S,z={}){z.showLoading!==!1&&r(!0),l(null);try{qe();const k=await Ql(H);s(k),p(k.settings),v(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(H={}){H.showLoading!==!1&&Q(!0),te(null);const[z,k,Z]=await Promise.allSettled([ei(),ti(),si()]);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)),Z.status==="fulfilled"?V(Z.value):(V(null),te(se=>se??We(Z.reason))),H.showLoading!==!1&&Q(!1)}n.useEffect(()=>{N==="hosted"&&K()},[N]),n.useEffect(()=>{if(N!=="hosted")return;const H=P.some(k=>["requested","creating","starting","provisioning","stopping","deleting"].includes(k.status)),z=window.setInterval(()=>void K({showLoading:!1}),H?2e3:15e3);return()=>window.clearInterval(z)},[N,P]);async function fe(H,z){Y(H),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 H=(t==null?void 0:t.users)??[],z=(t==null?void 0:t.devices)??[];return{users:H.length,enabledUsers:H.filter(k=>k.enabled).length,devices:z.length,onlineDevices:z.filter(k=>k.connected).length,conversations:H.reduce((k,Z)=>k+Z.conversationCount,0),shares:(t==null?void 0:t.shares.filter(k=>!k.revokedAt).length)??0}},[t]);async function be(H,z){g(H),l(null);try{const k=await hi(H,z);s(Z=>Lr(Z,k))}catch(k){l(We(k))}finally{g(null)}}async function ye(H){g(`delete:${H}`),l(null);try{await fi(H),await m(S,{showLoading:!1})}catch(z){l(We(z))}finally{g(null)}}async function ke(H,z){g(`reset:${H}`),l(null);try{const k=await pi(H,z);s(Z=>Lr(Z,k))}catch(k){l(We(k))}finally{g(null)}}async function A(H){if(H.preventDefault(),!!d){g("settings"),l(null);try{const z=await mi(d);s(k=>k&&{...k,registrationEnabled:z.registrationEnabled,settings:z.settings}),p(z.settings)}catch(z){l(We(z))}finally{g(null)}}}async function W(H,z){g(`${z}:${H}`),l(null);try{z==="approve"?await xi(H):await gi(H),await m(S,{showLoading:!1})}catch(k){l(We(k))}finally{g(null)}}async function ne(H){await Hl(H),await m(S)}return i?e.jsx(Ln,{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(Ed,{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:H=>void m(Number(H.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(H=>e.jsx("button",{className:`rounded-md px-3 py-2 text-sm font-medium ${N===H?"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(H),type:"button",children:_d(H)},H))}),N==="overview"?e.jsx(Rd,{summary:t}):null,N==="users"?e.jsx(Id,{busyKey:f,onDeleteUser:ye,onResetPassword:ke,onUpdateUser:be,users:t.users}):null,N==="devices"?e.jsx(Ad,{devices:t.devices,users:t.users}):null,N==="hosted"?e.jsx(wd,{busyKey:J,capability:O,error:D,loading:re,onAction:fe,onRefresh:K,sandboxes:P,reconciliation:L,users:t.users}):null,N==="shares"?e.jsx(Pd,{shares:t.shares}):null,N==="settings"&&d?e.jsx(Od,{busy:f==="settings",draft:d,onChange:p,onReviewRegistration:W,onSave:A,pending:t.pendingRegistrations,reviewBusyKey:f}):null]}):null]})]})}function wd({busyKey:t,capability:s,error:a,loading:r,onAction:o,onRefresh:l,reconciliation:i,sandboxes:c,users:f}){var Q;const g=f.filter(D=>D.role==="user"&&D.enabled),[N,x]=n.useState([]),[S,v]=n.useState("Hosted Codex"),[d,p]=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",()=>oi({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(jd,{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=>v(D.target.value),required:!0,value:S})]}),e.jsxs("label",{className:"text-sm text-[var(--theme-fg-soft)]",children:["Resources",e.jsxs("select",{className:"relay-input mt-2 w-full",onChange:D=>p(D.target.value),value: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(Nd,{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 jd({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",ai),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}`,()=>ri(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}`,()=>ni(i.credentialRef)),type:"button",children:"Delete orphan credential"})]},i.credentialRef))]})}function Nd({busyKey:t,onAction:s,sandbox:a,users:r}){const[o,l]=n.useState(!1),[i,c]=n.useState(!1),[f,g]=n.useState(""),[N,x]=n.useState(!1),[S,v]=n.useState(()=>Date.now()),d=(t==null?void 0:t.endsWith(a.id))??!1,p=Sd(a.status),O=a.assignedUsers.map(R=>R.userId),U=f.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(()=>v(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:p,children:Cd(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 ·"," ",Td(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 ${Fd(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}`,()=>Er(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}`,()=>Er(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}`,()=>ii(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}`,()=>ui(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}`,()=>li(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:f}),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 Tr(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}`,()=>Tr(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(kd,{busy:d,onAction:s,sandbox:a})]})]})]}):null]})}function kd({busy:t,onAction:s,sandbox:a}){const[r,o]=n.useState(!1),[l,i]=n.useState(!1),[c,f]=n.useState(null),[g,N]=n.useState(""),[x,S]=n.useState("");async function v(){i(!0),f(null);try{const d=await di(a.id);N(d.configToml),S(d.authJson)}catch(d){f(We(d))}finally{i(!1)}}return e.jsxs("details",{className:"mt-3",onToggle:d=>{const p=d.currentTarget.open;o(p),p&&!g&&!l&&a.status==="online"&&v()},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 v(),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}`,()=>ci(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 Sd(t){return t==="online"?"success":t==="error"?"danger":["creating","starting","provisioning","stopping","deleting"].includes(t)?"warning":"neutral"}function Cd(t){return t.replace("_"," ").replace(/^./,s=>s.toUpperCase())}function Td(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 Ed({onLogout:t}){const[s,a]=n.useState(null),[r,o]=n.useState(!1);n.useEffect(()=>{let c=!1;return jn().then(f=>{c||a(f.authenticated?f:null)}).catch(()=>{c||a(null)}),()=>{c=!0}},[]);const l=(s==null?void 0:s.user)??null;if(!l)return null;async function i(){await _l(),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:qd(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 Rd({summary:t}){const s=[...t.users].sort(Wd("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(Ld,{device:r},r.id))}):e.jsx(gs,{children:"No supervisors are connected."})})]})}function Id({busyKey:t,onDeleteUser:s,onResetPassword:a,onUpdateUser:r,users:o}){const[l,i]=n.useState(""),[c,f]=n.useState({key:"lastSeenAt",direction:"desc"}),[g,N]=n.useState(null),[x,S]=n.useState(null),v=n.useMemo(()=>{const p=Or(l);return o.filter(O=>p?Or(`${O.username} ${O.email}`).includes(p):!0).sort((O,U)=>$d(O,U,c))},[l,c,o]);function d(p){f(O=>({key:p,direction:O.key===p&&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:p=>i(p.target.value),placeholder:"Search username or email",value:l})]}),e.jsxs("p",{className:"text-sm text-[var(--theme-fg-muted)]",children:[v.length.toLocaleString()," of"," ",o.length.toLocaleString()," users"]})]}),e.jsxs(da,{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:v.map(p=>e.jsxs("tr",{children:[e.jsxs(Ce,{strong:!0,children:[p.username,e.jsx("div",{className:"text-xs font-normal text-[var(--theme-fg-muted)]",children:p.email})]}),e.jsx(Ce,{children:e.jsx(Dn,{active:p.enabled,children:p.enabled?"Enabled":"Disabled"})}),e.jsx(Ce,{children:Fe(p.lastSeenAt)}),e.jsx(Ce,{children:p.conversationCount.toLocaleString()}),e.jsx(Ce,{children:p.deviceCount.toLocaleString()}),e.jsx(Ce,{children:p.role}),e.jsx(Ce,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{className:"relay-button-secondary",disabled:t===p.id||p.role==="admin",onClick:()=>r(p.id,!p.enabled),type:"button",children:p.enabled?"Disable":"Enable"}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",disabled:t===`reset:${p.id}`||p.role==="admin",onClick:()=>N(p),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:${p.id}`||p.role==="admin",onClick:()=>S(p),type:"button",children:[e.jsx(F.Trash2,{className:"h-4 w-4"}),"Delete"]})]})})]},p.id))})]}),v.length?null:e.jsx(gs,{children:"No users match the current search."})]}),g?e.jsx(Ud,{busy:t===`reset:${g.id}`,onClose:()=>N(null),onSubmit:async p=>{await a(g.id,p),N(null)},user:g}):null,x?e.jsx(Dd,{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 Ad({devices:t,users:s}){const[a,r]=n.useState("all"),[o,l]=n.useState("all"),[i,c]=n.useState("all"),[f,g]=n.useState("lastActivity"),[N,x]=n.useState("desc"),S=n.useMemo(()=>s.filter(d=>t.some(p=>p.ownerUserId===d.id)),[t,s]),v=n.useMemo(()=>t.filter(d=>a==="all"||d.ownerUserId===a).filter(d=>o==="all"||(o==="online"?d.connected:!d.connected)).filter(d=>i==="all"||Hd(hs(d),i)).sort((d,p)=>Md(d,p,f,N)),[i,t,N,a,f,o]);return e.jsxs(dt,{title:"Devices",detail:"Supervisor devices grouped by owner, connection state, activity, and loaded workspace metadata.",children:[e.jsxs("div",{className:"mb-4 grid gap-3 md:grid-cols-2 xl:grid-cols-5",children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Owner",e.jsxs("select",{className:"relay-input mt-2 w-full",onChange: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:f,children:[e.jsx("option",{value:"lastActivity",children:"Last activity"}),e.jsx("option",{value:"name",children:"Device name"}),e.jsx("option",{value:"ownerUsername",children:"Owner"}),e.jsx("option",{value:"connected",children:"Connection"}),e.jsx("option",{value:"createdAt",children:"Created"}),e.jsx("option",{value:"workspaceCount",children:"Workspaces"}),e.jsx("option",{value:"threadCount",children:"Threads"})]})]}),e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Direction",e.jsxs("select",{className:"relay-input mt-2 w-full",onChange:d=>x(d.target.value),value:N,children:[e.jsx("option",{value:"desc",children:"Descending"}),e.jsx("option",{value:"asc",children:"Ascending"})]})]})]}),e.jsxs(da,{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:v.map(d=>{var p,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(Dn,{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:((p=d.workspaces[0])==null?void 0:p.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)})})]}),v.length?null:e.jsx(gs,{children:"No devices match the selected filters."})]})}function Pd({shares:t}){return e.jsx(dt,{title:"Share relationships",detail:"Thread grants between relay users. Revoked grants remain visible for audit.",children:e.jsxs(da,{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," /"," ",Bd(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 Od({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 Ld({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 da({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 Dn({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 Ud({busy:t,onClose:s,onSubmit:a,user:r}){const[o,l]=n.useState(""),[i,c]=n.useState(null);async function f(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:f,children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["New password",e.jsx("input",{autoFocus:!0,className:"relay-input mt-2 w-full",onChange: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 Dd({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 Or(t){return t.trim().toLowerCase()}function $d(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 Md(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 Hd(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 Lr(t,s){return t&&{...t,users:t.users.map(a=>a.id===s.id?{...a,...s}:a)}}function _d(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 Bd(t){switch(t){case"write":return"workspace write";case"read":return"workspace read";case"none":default:return"no workspace"}}function Wd(t){return(s,a)=>Date.parse(a[t]??"")-Date.parse(s[t]??"")}function Fe(t){return t?new Date(t).toLocaleString():"never"}function Fd(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 qd(t){const s=(t==null?void 0:t.trim())??"";return s?Array.from(s).slice(0,2).join("").toUpperCase():"??"}function Vd(t){const s=(t==null?void 0:t.trim())??"";return s?Array.from(s).slice(0,2).join("").toUpperCase():"??"}function ca({className:t="",menuAlign:s="left"}){const a=Ye(),r=Ut(),[o,l]=n.useState(null),[i,c]=n.useState(!1),[f,g]=n.useState(!1);n.useEffect(()=>{if(!at())return;let d=!1;return yt().then(p=>{d||l(p.authenticated?p: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(()=>Vd(N==null?void 0:N.username),[N==null?void 0:N.username]),S=f&&typeof document<"u"?nn.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(Un,{})})]})}),document.body):null;if(!at()||!N)return null;async function v(){await Wl(),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 v(),role:"menuitem",type:"button",children:[e.jsx(F.LogOut,{className:"h-4 w-4"}),"Logout"]})]}):null,S]})}const zd=3e3;function tt(t,s){return t instanceof le?t.payload.message:t instanceof Error?t.message:s}function Gd(t,s){return t?{...s,sharedWithMe:Ur(t.sharedWithMe,s.sharedWithMe),sharedByMe:Ur(t.sharedByMe,s.sharedByMe),sharedDevicesWithMe:$s(t.sharedDevicesWithMe??[],s.sharedDevicesWithMe??[]),sharedThreadsWithMe:$s(t.sharedThreadsWithMe??[],s.sharedThreadsWithMe??[]),grantsByMe:$s(t.grantsByMe??[],s.grantsByMe??[])}:Jd(s)}function Jd(t){return{...t,sharedWithMe:t.sharedWithMe.map(ta),sharedByMe:t.sharedByMe.map(ta),sharedDevicesWithMe:(t.sharedDevicesWithMe??[]).map(ls),sharedThreadsWithMe:(t.sharedThreadsWithMe??[]).map(ls),grantsByMe:(t.grantsByMe??[]).map(ls)}}function Ur(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 ta(r);const l=fs(r),i=fs(o);return{...r,threadTitle:l??i,workspaceLabel:r.workspaceLabel??o.workspaceLabel}})}function ta(t){return{...t,threadTitle:fs(t)}}function $s(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 Kd(){const t=Ye(),[s,a]=sa(),[r,o]=n.useState(null),[l,i]=n.useState(""),[c,f]=n.useState(null),[g,N]=n.useState(null),[x,S]=n.useState(!0),[v,d]=n.useState(null),[p,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,X=(u==null?void 0:u.clearError)??!0;j&&S(!0),X&&O(null);try{qe();const ve=await Nn();K.current=!0,o(y=>Gd(y,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})},zd);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 X=new URLSearchParams(s);X.delete("shareDevice"),a(X,{replace:!0})},[r,s,a]);async function be(u){u.preventDefault(),d("create"),O(null);try{const j=await ql({name:l});f(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 Vl(u.id),(c==null?void 0:c.device.id)===u.id&&f(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(Js(u.id))}function A(u){rs(u.deviceId),ns(u.threadId),t(Gs(u.threadId,u.deviceId))}function W(u){if(rs(u.deviceId),ns(u.threadId),u.threadId){t(Gs(u.threadId,u.deviceId));return}t(Js(u.deviceId))}async function ne(u,j){d(`grant:create:${u.id}`),O(null);try{await Yl({...j,deviceId:u.id,scope:"device",workspaceScope:"all",workspaceIds:[]}),J(null),await ee({showLoading:!1})}catch(X){O(tt(X,"Unable to share device."))}finally{d(null)}}async function H(u,j){d(`grant:${u.id}`),O(null);try{await Zl(u.id,{...j,workspaceId:u.workspaceId,workspaceScope:u.workspaceScope,workspaceIds:u.workspaceIds}),D(null),await ee({showLoading:!1})}catch(X){O(tt(X,"Unable to update shared access."))}finally{d(null)}}async function z(u){if(window.confirm(`Remove sharing access for "${ma(u)}"?`)){d(`grant:${u.id}`),O(null);try{await Xl(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 Kl(u.id,{...j,workspaceId:u.workspaceId}),re(null),await ee({showLoading:!1})}catch(X){O(tt(X,"Unable to update shared thread."))}finally{d(null)}}async function Z(u){if(window.confirm(`Remove sharing access for "${ua(u)}"?`)){d(`share:${u.id}`),O(null);try{await kn(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){var X;const j=u.token;if(!j){O("This device token is not available. Create a new device token for devices created before token storage was enabled.");return}try{await((X=navigator.clipboard)==null?void 0:X.writeText($n(j))),N(u.id),window.setTimeout(()=>{N(ve=>ve===u.id?null:ve)},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(ca,{}),e.jsx(Ue,{className:"host-info-pill inline-flex h-8 shrink-0 items-center rounded-md border px-2.5 text-[11px] font-medium uppercase tracking-[0.14em] transition sm:px-3 sm:text-xs sm:tracking-[0.18em]",to:"/",children:"Relay home"}),e.jsx("div",{className:"min-w-0 flex-1 text-right",children:e.jsx("p",{className:"host-page-eyebrow truncate text-[11px] uppercase tracking-[0.24em]",children:"Relay portal"})})]})}),e.jsxs("section",{className:"border-b border-[var(--theme-border)] pb-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay portal"}),e.jsx("h1",{className:"mt-1 text-2xl font-semibold text-[var(--theme-fg)]",children:"Devices and shared sessions"})]}),p?e.jsx(sc,{tone:"danger",children:p}):null,c?e.jsx(tc,{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(ec,{busy:v===u.id,copiedSetup:g===u.id,device:u,onConnect:()=>ke(u),onCopySetup:()=>void se(u),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(Dr,{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(Mr,{mode:"incoming",share:u,onOpen:()=>A(u)},u.id)}),e.jsx($r,{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($r,{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:v===`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(Dr,{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(Mr,{busy:v===`share:${u.id}`,expanded:U===u.id,mode:"outgoing",share:u,onOpen:()=>A(u),onEdit:()=>re(u),onRevoke:()=>void Z(u),onToggleAccess:()=>{P(j=>j===u.id?null:u.id)}},u.id)})]})]})]}),Y?e.jsx(Yd,{busy:v==="create",deviceName:l,onChangeDeviceName:i,onClose:()=>m(!1),onSubmit:be}):null,V?e.jsx(Zd,{busy:v===`share:${V.id}`,share:V,onClose:()=>re(null),onSave:u=>void k(V,u)}):null,Q?e.jsx(Qd,{busy:v===`grant:${Q.id}`,grant:Q,onClose:()=>D(null),onSave:u=>void H(Q,u)}):null,te?e.jsx(Xd,{busy:v===`grant:create:${te.id}`,device:te,onClose:()=>J(null),onShare:u=>void ne(te,u)}):null]})}function Yd({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 Dr({count:t,emptyText:s,loading:a,loadingText:r,renderShare:o,shares:l,subtitle:i,title:c}){return e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:c}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:i})]}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5 text-xs text-[var(--theme-fg-muted)]",children:t})]}),a?e.jsx("p",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-4 text-sm text-[var(--theme-fg-muted)]",children:r}):l.length?e.jsx("div",{className:"grid gap-3",children:l.map(f=>o(f))}):e.jsx("div",{className:"rounded-lg border border-dashed border-[var(--theme-border)] bg-[var(--theme-surface)] p-5 text-sm text-[var(--theme-fg-muted)]",children:s})]})}function $r({count:t,emptyText:s,grants:a,loading:r,loadingText:o,renderGrant:l,subtitle:i,title:c}){return e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:c}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:i})]}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5 text-xs text-[var(--theme-fg-muted)]",children:t})]}),r?e.jsx("p",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-4 text-sm text-[var(--theme-fg-muted)]",children:o}):a.length?e.jsx("div",{className:"grid gap-3",children:a.map(f=>l(f))}):e.jsx("div",{className:"rounded-lg border border-dashed border-[var(--theme-border)] bg-[var(--theme-surface)] p-5 text-sm text-[var(--theme-fg-muted)]",children:s})]})}function Mr({busy:t=!1,expanded:s=!1,mode:a,onEdit:r,onRevoke:o,onToggleAccess:l,share:i,onOpen:c}){var v,d;const f=ua(i),g=f,N=((v=i.label)==null?void 0:v.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:f}),e.jsxs("div",{className:"mt-1 space-y-0.5 text-xs text-[var(--theme-fg-muted)]",children:[e.jsxs("p",{className:"truncate",children:["Workspace:"," ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children: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:_n(i.workspaceAccess)})]})]}),a==="incoming"?e.jsx("button",{className:"relay-button-primary inline-flex items-center gap-2",onClick:c,type:"button",children:"Open"}):e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{className:"relay-button-primary inline-flex items-center gap-2",onClick:c,type:"button",children:"Open"}),e.jsx("button",{className:"relay-button-secondary inline-flex items-center gap-2",disabled:t,onClick:r,type:"button",children:"Permissions"}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:l,type:"button",children:["Access",e.jsx(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(p=>e.jsxs("li",{className:"flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate font-medium text-[var(--theme-fg)]",children:Bn(p.kind)}),e.jsx("span",{className:"block truncate",children:p.username})]}),e.jsx("span",{children:wt(p.accessedAt)})]},p.id))}):e.jsx("p",{className:"text-xs text-[var(--theme-fg-muted)]",children:"This shared thread has not been accessed yet."})}):null]})}function Hr({busy:t=!1,expanded:s=!1,grant:a,mode:r,onEdit:o,onOpen:l,onRevoke:i,onToggleAccess:c}){var d,p;const f=ma(a),g=nc(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=((p=a.label)==null?void 0:p.trim())||null,v=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:f}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5 text-[11px] uppercase tracking-[0.12em] text-[var(--theme-fg-muted)]",children: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: ",v]}):null,e.jsxs("p",{className:"mt-2 flex flex-wrap gap-1.5 text-[11px] text-[var(--theme-fg-muted)]",children:[e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5",children:a.threadAccess==="read"?"View only":"Collaborator"}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5",children:_n(a.workspaceAccess)}),a.canCreateThreads?e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5",children:"Can create threads"}):null]})]}),r==="incoming"?e.jsx("button",{className:"relay-button-primary inline-flex items-center gap-2",onClick:l,type:"button",children:"Open"}):e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{className:"relay-button-primary inline-flex items-center gap-2",onClick:l,type:"button",children:"Open"}),e.jsx("button",{className:"relay-button-secondary inline-flex items-center gap-2",disabled:t,onClick:o,type:"button",children:"Permissions"}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:c,type:"button",children:["Access",e.jsx(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:Bn(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 Zd({busy:t,onClose:s,onSave:a,share:r}){const[o,l]=n.useState(r.label??""),[i,c]=n.useState(r.threadAccess),[f,g]=n.useState(r.workspaceAccess),[N,x]=n.useState(Mn(r.expiresAt)),S=!r.workspaceId;function v(d){d.preventDefault(),a({label:o.trim()||null,threadAccess:i,workspaceAccess:S?"none":f,expiresAt:Hn(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:v,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 ",ua(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":f,children:[e.jsx("option",{value:"none",children:"No workspace"}),e.jsx("option",{value:"read",children:"Workspace read"}),e.jsx("option",{value:"write",children:"Workspace write"})]})]}),S?e.jsx("p",{className:"rounded-md border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-2 text-xs text-[var(--theme-fg-muted)]",children:"This share was created without a workspace scope, so only thread access can be changed."}):null,e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Expiration",e.jsx("input",{"aria-label":"Expiration",className:"relay-input mt-2 w-full",onChange: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 Xd({busy:t,device:s,onClose:a,onShare:r}){const[o,l]=n.useState(""),[i,c]=n.useState(""),[f,g]=n.useState("read"),[N,x]=n.useState("read"),[S,v]=n.useState(!1);function d(p){p.preventDefault(),r({targetIdentifier:o.trim(),label:i.trim()||null,threadAccess:f,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:p=>l(p.target.value),placeholder:"username or email",value:o})]}),e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Label",e.jsx("input",{className:"relay-input mt-2 w-full",onChange:p=>c(p.target.value),placeholder:"Optional note shown in Shared devices by me",value:i})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Thread access",e.jsxs("select",{className:"relay-input mt-2 w-full",onChange:p=>g(p.target.value),value:f,children:[e.jsx("option",{value:"read",children:"View only"}),e.jsx("option",{value:"control",children:"Collaborator"})]})]}),e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Workspace access",e.jsxs("select",{className:"relay-input mt-2 w-full",onChange:p=>x(p.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:p=>v(p.target.checked),type:"checkbox"})]})]}),e.jsxs("div",{className:"mt-5 flex justify-end gap-2",children:[e.jsx("button",{className:"relay-button-secondary",disabled:t,onClick:a,type:"button",children:"Cancel"}),e.jsxs("button",{className:"relay-button-primary inline-flex items-center gap-2",disabled:t||!o.trim(),type:"submit",children:[e.jsx(F.Share2,{className:"h-4 w-4"}),"Share device"]})]})]})})}function Qd({busy:t,grant:s,onClose:a,onSave:r}){const[o,l]=n.useState(s.label??""),[i,c]=n.useState(s.threadAccess),[f,g]=n.useState(s.workspaceAccess),[N,x]=n.useState(s.canCreateThreads),[S,v]=n.useState(Mn(s.expiresAt)),d=s.scope!=="thread",p=s.scope==="thread"&&!s.workspaceId;function O(U){U.preventDefault(),r({label:o.trim()||null,threadAccess:i,workspaceAccess:p?"none":f,canCreateThreads:d?N:!1,expiresAt:Hn(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 ",ma(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:p,onChange:U=>g(U.target.value),value:p?"none":f,children:[e.jsx("option",{value:"none",children:"No workspace"}),e.jsx("option",{value:"read",children:"Workspace read"}),e.jsx("option",{value:"write",children:"Workspace write"})]})]})]}),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=>v(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 ec({device:t,busy:s,copiedSetup:a,onConnect:r,onCopySetup:o,onDelete:l,onShare:i,setupTokenAvailable:c}){const f=t.hostedStatus??null,g=t.connected||f==="stopped",N=f?rc(f):t.connected?"Online":"Offline";return e.jsxs("article",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:`h-2.5 w-2.5 rounded-full ${t.connected?"bg-[var(--status-success-fg)]":"bg-[var(--theme-fg-muted)]"}`}),e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:t.name}),f?e.jsxs("span",{className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-2 py-0.5 text-[10px] font-medium text-[var(--theme-fg-muted)]",children:["Hosted · ",N]}):null]}),e.jsx("p",{className:"mt-1 font-mono text-xs text-[var(--theme-fg-muted)]",children:t.tokenPreview}),e.jsx("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:f==="stopped"?"Stopped. Connect to wake this VM.":f&&f!=="online"?`${N}. 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("button",{className:"relay-button-secondary inline-flex h-10 items-center gap-2 whitespace-nowrap",onClick:o,title:c?"Copy relay supervisor setup command":"Device token is not available. Create a new device token for devices created before token storage was enabled.",disabled:!c||!!f,type:"button",children:[e.jsx(F.Copy,{className:"h-4 w-4"}),a?"Copied":"Copy setup"]}),e.jsxs("button",{className:"relay-button-primary inline-flex h-10 items-center gap-2 whitespace-nowrap",disabled:!g,onClick:r,type:"button",children:[e.jsx(F.Plug,{className:"h-4 w-4"}),f==="stopped"?"Start & connect":"Connect"]}),e.jsxs("button",{className:"relay-button-secondary inline-flex h-10 items-center gap-2 whitespace-nowrap",onClick:i,type:"button",children:[e.jsx(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||!!f,onClick:l,title:f?"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 tc({result:t}){const s=$n(t.token);return e.jsxs("section",{className:"rounded-lg border border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] p-4",children:[e.jsxs("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:["Token created for ",t.device.name]}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Store this token now. It will not be shown again."}),e.jsx(_r,{label:"Device token",value:t.token}),e.jsx(_r,{label:"Supervisor command",value:s})]})}function _r({label:t,value:s}){async function a(){var r;try{await((r=navigator.clipboard)==null?void 0:r.writeText(s))}catch{}}return e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.14em] text-[var(--theme-fg-muted)]",children:t}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-1 px-2 py-1 text-xs",onClick:()=>void a(),type:"button",children:[e.jsx(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:s})]})}function sc({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 $n(t){const s=ac();return[`REMOTE_CODEX_RELAY_SERVER_URL=${Br(s)} \\`,`REMOTE_CODEX_RELAY_AGENT_TOKEN=${Br(t)} \\`,"REMOTE_CODEX_RELAY_SUPERVISOR_PORT=45679 \\","remote-codex relay-supervisor"].join(`
20
- `)}function Br(t){return/^[A-Za-z0-9_./:@%+=,~-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function ac(){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 rc(t){return t.replace("_"," ").replace(/^./,s=>s.toUpperCase())}function Mn(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 Hn(t){const s=t.trim();if(!s)return null;const a=new Date(s);return Number.isNaN(a.getTime())?null:a.toISOString()}function ua(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 ma(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 nc(t){switch(t.scope){case"device":return"Device";case"workspace":return"Workspace";case"thread":default:return"Thread"}}function _n(t){switch(t){case"write":return"Workspace write";case"read":return"Workspace read";case"none":default:return"No workspace"}}function Bn(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 oc=["REMOTE_CODEX_RELAY_SERVER_URL=wss://remote-codex.example.com \\","REMOTE_CODEX_RELAY_AGENT_TOKEN=rcd_... \\","REMOTE_CODEX_RELAY_SUPERVISOR_PORT=45679 \\","remote-codex relay-supervisor"].join(`
21
- `);function lc(){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(Ms,{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(Ms,{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(Ms,{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:oc})})]}),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 Ms({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 ic(){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(Bs,{label:"Mode",value:"Relay"}),e.jsx(Bs,{label:"Client",value:"Web, Android, iOS"}),e.jsx(Bs,{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(_s,{title:"Local stays local",detail:"Workspace files and agent execution remain on the supervisor device."}),e.jsx(_s,{title:"Shared sessions",detail:"Share a thread as view-only or collaborator access, with workspace permissions."}),e.jsx(_s,{title:"Mobile first",detail:"Resume threads, monitor long turns, and open shared sessions from Android or iOS."})]})]})})}function 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 _s({detail:t,title:s}){return e.jsxs("article",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-4",children:[e.jsx(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 Bs({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 Wn(t,s){return t instanceof le?t.payload.message:t instanceof Error?t.message:s}function dc(){const t=Ye(),s=Ut(),[a,r]=n.useState(null),[o,l]=n.useState(!0),[i,c]=n.useState(null);async function f(){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(Wn(x,"Unable to load relay portal."))}finally{l(!1)}}n.useEffect(()=>{f()},[]);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(Ws,{children:"Checking relay session..."}):a!=null&&a.authenticated?e.jsx(Ws,{children:"Opening relay devices..."}):e.jsx(Ws,{children:e.jsx(cc,{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 cc({registrationEnabled:t,settings:s,oauthNotice:a,oauthError:r,initialError:o,onAuthenticated:l}){const[i,c]=n.useState("login"),[f,g]=n.useState(""),[N,x]=n.useState(""),[S,v]=n.useState(""),[d,p]=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 Ml({identifier:f,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 Bl({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(Wn(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:f}):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:v,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:p,required:!0,type:"password",value:d,...i==="register"?{description:"Use at least 8 characters.",minLength:8}:{}}),P?e.jsx(Wr,{tone:"danger",children:P}):null,L?e.jsx(Wr,{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 Ws({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(ca,{}),e.jsx("div",{className:"flex min-h-[calc(100vh-3rem)] items-center justify-center",children:t})]})}function It({label:t,value:s,onChange:a,type:r="text",autoComplete:o,description:l,minLength:i,required:c=!1}){return e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:[t,e.jsx("input",{autoComplete:o,className:"relay-input mt-2 w-full",minLength:i,onChange:f=>a(f.target.value),required:c,type:r,value:s}),l?e.jsx("span",{className:"mt-1.5 block text-xs text-[var(--theme-fg-muted)]",children:l}):null]})}function Wr({tone:t,children:s}){return e.jsx("div",{className:`rounded-lg border px-3 py-2 text-sm ${t==="danger"?"border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] text-[var(--status-danger-fg)]":"border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] text-[var(--theme-fg)]"}`,children:s})}function uc(t,s){return cl(t,s)}function it(t,s,a=null){return ul(t,s,a)}function mc(t,s){return!s||s.items.length===0?t:t.map(a=>{if(a.id!==s.turnId)return a;const r=s.items.filter(f=>f.kind==="agentMessage"&&f.createdAt);if(r.length===0)return a;const o=new Map(r.map(f=>[f.id,f])),l=new Set;let i=!1;const c=a.items.map(f=>{if(f.kind!=="agentMessage"||f.createdAt&&f.createdAt!==a.startedAt)return f;let g=o.get(f.id);return g||(g=r.find(N=>!l.has(N.id)&&N.text.trim().length>=8&&f.text.trim().includes(N.text.trim()))),!(g!=null&&g.createdAt)||g.createdAt===a.startedAt?f:(l.add(g.id),i=!0,{...f,createdAt:g.createdAt})});return i?{...a,items:c}:a})}function hc(t,s){return{...t,pendingRequests:[...t.pendingRequests.filter(a=>a.id!==s.id),s]}}function fc(t,s){const a=t.pendingRequests.filter(r=>r.id!==s);return a.length===t.pendingRequests.length?t:{...t,pendingRequests:a}}function Fr(t,s,a){const r=s.filter(c=>!a.has(c.id)),o=t.filter(c=>!a.has(c.id));if(o.length===0)return r;const l=new Map(r.map(c=>[c.id,c]));return[...o.map(c=>l.get(c.id)??c),...r.filter(c=>!o.some(f=>f.id===c.id))].sort((c,f)=>c.createdAt.localeCompare(f.createdAt))}function pc(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 Fn(t,s){var l,i;if(!t||t.kind!==s.kind)return s;const a=c=>{let f=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&&f.sequence!==g&&(f={...f,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&&f.transcriptOrder!==N&&(f={...f,transcriptOrder:N}),f};if(t.kind==="agentMessage"&&s.kind==="agentMessage")return a(t.text.length>s.text.length?{...s,text:t.text,sequence:s.sequence??t.sequence??null}:s);const r=((l=t.detailText)==null?void 0:l.trim())||t.text.trim(),o=((i=s.detailText)==null?void 0:i.trim())||s.text.trim();return a(r.length>o.length?t:s)}function xc(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 v=o.get(S.id);return v?v.kind!==S.kind||typeof S.sequence=="number"&&Number.isFinite(S.sequence)&&v.sequence!==S.sequence:!i(S)});return x.length===0?null:{...t,items:x}}const c=new Map(t.items.map(x=>[x.id,x])),f=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=f.get(x),v=c.get(x);if(!S){const d=o.get(x);return!d&&v&&i(v)||d&&d.kind===(v==null?void 0:v.kind)&&!(v&&typeof v.sequence=="number"&&Number.isFinite(v.sequence)&&d.sequence!==v.sequence)?null:v??null}return Fn(v,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 gc(t){return`${t.threadId}:${t.objective}:${t.createdAt}`}function vc(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 qn(t){const s=new Map;for(const a of t){const r=gc(a),o=s.get(r);s.set(r,o?vc(o,a):a)}return[...s.values()].sort((a,r)=>Date.parse(r.updatedAt)-Date.parse(a.updatedAt))}function ps(t,s){return qn([s,...t])}function Fs(t,s){if(!s)return null;const a=t.find(r=>r.model===s);return a?a.supportedReasoningEfforts.length>1:null}function bc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`client-${Date.now()}-${Math.random().toString(16).slice(2,10)}`}function ha(t,s){return(t==null?void 0:t.items.some(a=>a.kind==="userMessage"&&a.text.trim()===s.trim()))??!1}const yc=/\s*\[(?:PHOTO\s+[^\]]+|localImage)\]\s*/g;function fa(t){return/\[(?:PHOTO\s+[^\]]+|localImage)\]/.test(t)}function qr(t){return t.replace(yc," ").replace(/\s+/g," ").trim()}function Vn(t,s){const a=qr(s);return a?(t==null?void 0:t.items.some(r=>r.kind==="userMessage"&&qr(r.text)===a))??!1:!1}function zn(t){return(t==null?void 0:t.items.some(s=>s.kind==="userMessage"&&/\[(?:PHOTO\s+\.\/\.temp\/threads\/[^\]]+|localImage)\]/.test(s.text)))??!1}function wc(t,s){return t.find(a=>ha(a,s))??(fa(s)?t.find(a=>Vn(a,s))??null:null)}function jc(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:ha(a,s.prompt)||fa(s.prompt)&&(Vn(a,s.prompt)||zn(a)))??null}function Nc(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 kc({activeView:t,composerHostRef:s,threadId:a}){const[r,o]=n.useState(!1),[l,i]=n.useState(0),[c,f]=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"){f(0);return}const R=()=>{const Q=P.getBoundingClientRect();f(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 v=r&&t==="chat",d=v&&x?g:0,p=Math.max(l,144),O=Math.max(c,p+d),U=v?O+12:0;return{floatingMobileComposerBottomOffset:d,timelineBottomSpacer:U,useFloatingMobileComposer:v}}const He=()=>({status:"idle",data:null,error:null});function Sc({detailRef:t,id:s,navigate:a,setDetail:r,setError:o,setThreads:l}){const[i,c]=n.useState(He),[f,g]=n.useState(He),[N,x]=n.useState(He),[S,v]=n.useState(He),[d,p]=n.useState(He),[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(He);n.useEffect(()=>{c(He),g(He),x(He),v(He),p(He),U(!1),V(new Set),Q(!1),Y(He)},[s]);const m=n.useCallback(async()=>{if(s){Y(u=>({status:"loading",data:u.data,error:null}));try{const u=await Hi(s);Y({status:"ready",data:u,error:null})}catch(u){const j=u instanceof le?u.payload.message:"Unable to load export turns.";Y(X=>({status:"failed",data:X.data,error:j}))}}},[s]);async function K(u){if(s){o(null),te(!0);try{const{blob:j,filename:X}=await Bi(s,u),ve=URL.createObjectURL(j),y=document.createElement("a");y.href=ve,y.download=X,document.body.append(y),y.click(),y.remove(),window.setTimeout(()=>URL.revokeObjectURL(ve),3e4),Q(!1)}catch(j){const X=j instanceof le?j.payload.message:"Unable to export transcript.";o(X)}finally{te(!1)}}}async function fe(){if(s){p(u=>{var j;return{status:"loading",data:u.data??((j=t.current)==null?void 0:j.goal)??null,error:null}});try{const u=await ed(s);p({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){p(j=>({status:"failed",data:j.data,error:u instanceof le?u.payload.message:"Unable to load goal."}))}}}async function ee(u){if(s){p(j=>{var X;return{status:"loading",data:j.data??((X=t.current)==null?void 0:X.goal)??null,error:null}});try{const j=await td(s,u);p({status:"ready",data:j.goal,error:null}),r(X=>X&&(j.goal?{...X,goal:j.goal,goalHistory:ps(X.goalHistory??[],j.goal)}:{...X,goal:j.goal}))}catch(j){throw p(X=>({status:"failed",data:X.data,error:j instanceof le?j.payload.message:"Unable to update goal."})),j}}}async function be(){if(s){p(u=>{var j;return{status:"loading",data:u.data??((j=t.current)==null?void 0:j.goal)??null,error:null}});try{const u=await sd(s);p({status:"ready",data:null,error:null}),r(j=>j&&(u.goalHistory?{...j,goal:null,goalHistory:u.goalHistory}:{...j,goal:null}))}catch(u){throw p(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 rd(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 nd(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 od(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 H(u){if(s){x(j=>({status:"loading",data:j.data,error:null}));try{const j=await ld(s,u);x({status:"ready",data:j,error:null})}catch(j){throw x(X=>({status:"failed",data:X.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 id(s,u);x({status:"ready",data:j,error:null})}catch(j){throw x(X=>({status:"failed",data:X.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 dd(s,u);x({status:"ready",data:j,error:null})}catch(j){throw x(X=>({status:"failed",data:X.data,error:j instanceof le?j.payload.message:"Unable to trust hook."})),j}}}async function Z(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(X=>({status:"failed",data:X.data,error:j instanceof le?j.payload.message:"Unable to untrust hook."})),j}}}async function se(){if(s){v(u=>({status:"loading",data:u.data,error:null}));try{const u=await ad(s);v({status:"ready",data:u,error:null})}catch(u){v(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 Ar(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 Ar(s,{mode:"turn",turnId:u});l(X=>Pt(X,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:H,handleExportTranscript:K,handleForkLatest:Se,handleForkTurn:ge,handleGoalStatusAction:ye,handleOpenForkTurns:se,handleOpenGoal:fe,handleOpenHooks:ne,handleOpenMcp:W,handleOpenSkills:A,handleTerminateGoal:ke,handleTrustHook:k,handleUntrustHook:Z,handleUpdateGoal:ee,handleUpdateHook:z,hooksState:N,loadExportTurns:m,mcpState:f,setExpandedGoalIds:V,setExportDialogOpen:Q,setGoalMonitorOpen:U,setGoalState:p,skillsState:i}}const Cc=5e3;function Vr(t){return JSON.stringify(t)}function Tc(t,s){return Vr(t)===Vr(s)}function Ec(t,s){const a=new Map(t.map(l=>[l.id,l]));let r=t.length!==s.length;const o=s.map((l,i)=>{var f;const c=a.get(l.id);return c&&Tc(c,l)?(((f=t[i])==null?void 0:f.id)!==l.id&&(r=!0),c):(r=!0,l)});return r?o:t}function Gn(t){const{enabled:s,setThreads:a,intervalMs:r=Cc}=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 la();a(c=>Ec(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 Rc({setError:t,workspaceId:s,access:a="write"}){return n.useMemo(()=>!s||a==="none"?null:{listTree:r=>Ti(s,{path:r.path??""}),readFile:r=>Ei(s,{path:r.path,...r.offset!==void 0?{offset:r.offset}:{},...r.limit!==void 0?{limit:r.limit}:{}}),getRawFileUrl:r=>Ri(s,{path:r.path}),...a==="write"?{uploadFile:r=>Pi(s,{file:r.file}),writeFile:async r=>{await Oi(s,{path:r.path,content:r.content})}}:{},downloadNode:async r=>{t(null);try{const o=await Ai(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 zr(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 pa({initialWorkspaceId:t,initialTitle:s="",onCreated:a,onCancel:r,variant:o="panel"}){const l=Dt(),i=n.useId(),[c,f]=n.useState([]),[g,N]=n.useState([]),[x,S]=n.useState([]),[v,d]=n.useState((l==null?void 0:l.defaultBackend)??Je),[p,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===v),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([oa(),cs()]).then(async([Z,se])=>{var X,ve,y;if(k)return;const Se=zr(se,ee);d(Se),N(se);const ge=await os(Se);if(k)return;f(Z),S(ge);const u=t??null,j=Z.some(E=>E.id===u)?u:((X=Z[0])==null?void 0:X.id)??"";O(j),P(((ve=ge.find(E=>E.isDefault))==null?void 0:ve.model)??((y=ge[0])==null?void 0:y.model)??"")}).catch(Z=>{k||fe(Z instanceof Error?Z.message:"Unable to load creation form data.")}).finally(()=>{k||D(!1)}),()=>{k=!0}},[ee,t]),n.useEffect(()=>{if(!v)return;let k=!1;return S([]),P(""),fe(null),os(v).then(Z=>{var se,Se;k||(S(Z),P(((se=Z.find(ge=>ge.isDefault))==null?void 0:se.model)??((Se=Z[0])==null?void 0:Se.model)??""))}).catch(Z=>{k||(S([]),P(""),fe(Z instanceof Error?Z.message:"Unable to load backend models."))}),()=>{k=!0}},[v]);async function ne(k=v){var u,j;const Z=await cs();N(Z);const se=Z.find(X=>X.provider===k),Se=se&&st(se)?k:zr(Z,ee);d(Se);const ge=await os(Se);S(ge),P(((u=ge.find(X=>X.isDefault))==null?void 0:u.model)??((j=ge[0])==null?void 0:j.model)??"")}async function H(k){const Z=k.installation.installed?"update":"install";m(k.provider),fe(null);try{await Tn(k.provider,Z),await ne(k.provider)}catch(se){se instanceof le?fe(se.payload.message):fe(se instanceof Error?se.message:`Unable to ${Z} ${k.displayName}.`);try{await ne(v)}catch{}}finally{m(null)}}async function z(k){k.preventDefault(),J(!0),fe(null);try{const Z=await Fi(R.trim()?{workspaceId:p,provider:v,model:U,approvalMode:V,title:R.trim()}:{workspaceId:p,provider:v,model:U,approvalMode:V});a(Z)}catch(Z){Z instanceof le?fe(Z.payload.message):fe(Z instanceof Error?Z.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:v,onChange:k=>{const Z=k.target.value;d(Z)},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 Z=st(k),se=k.provider===v,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"} ${Z?"":"opacity-75"}`,children:[e.jsxs("div",{className:"flex flex-wrap items-start gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>{Z&&d(k.provider)},disabled:!Z||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,Z?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."}),!Z&&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:()=>H(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]}),!Z&&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:p,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.jsxs("option",{value:k.model,children:[k.displayName," · ",k.model]},k.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-xs font-medium",htmlFor:`${i}-thread-title`,children:"Title"}),e.jsx("input",{id:`${i}-thread-title`,value: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||!p||!U,className:W,children:te?"Creating...":"Create Thread"}),r?e.jsx("button",{type:"button",onClick:r,disabled:te,className:A,children:"Cancel"}):null]})]})}const Gr=3,Ic=3,Ac=1e3,Pc=2e3,qs=5500,Oc=3e3,Vs=0,gt=1,es=3,Lc=[],Uc=[],Dc=[],$c={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 Jr(t){return t==="read"?"View only":"Collaborator"}function Kr(t){switch(t){case"write":return"Workspace write";case"read":return"Workspace read";case"none":default:return"No workspace"}}function Mc(t){var s,a;return((a=(s=t.match(/^\[PHOTO\s+([^\]]+)\]$/))==null?void 0:s[1])==null?void 0:a.trim())??null}function Yr(t){return!(t!=null&&t.length)||typeof URL.createObjectURL!="function"?[]:t.flatMap(s=>{if(s.kind!=="photo")return[];const a=Mc(s.placeholder);return a?[{path:a,url:URL.createObjectURL(s.file)}]:[]})}function Hc(t){if(typeof URL.revokeObjectURL=="function")for(const s of t)URL.revokeObjectURL(s.url)}function _c(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 Bc(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-3.5 w-3.5 fill-current",children:e.jsx("path",{d:"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 Wc(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 Zr(){var vr;const{id:t=""}=Fo(),s=n.useRef(t);s.current=t;const a=Ut(),r=Ye(),o=Dt(),l=ln(),i=n.useRef(""),c=n.useRef(null),f=n.useRef(null),g=n.useRef(null),N=n.useRef(!1),x=n.useRef(null),S=n.useRef(null),v=n.useRef(typeof navigator>"u"?!0:navigator.onLine),d=n.useRef(!1),p=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),[H,z]=n.useState(null),[k,Z]=n.useState(0),[se,Se]=n.useState(null),[ge,u]=n.useState(""),[j,X]=n.useState(null),[ve,y]=n.useState(null),E=n.useRef(null),[_,ae]=n.useState(!0),[pe,Ee]=n.useState(0),[Xe,rt]=n.useState(0),[Mt,ct]=n.useState(0),[vs,ut]=n.useState(!1),[to,so]=n.useState(!1),[xa,bs]=n.useState(!0),[Ht,ys]=n.useState(!1),[nt,Qe]=n.useState(!1),[_e,ga]=n.useState("chat"),[ao,ro]=n.useState(null),va=l.getThreadPanels().some(h=>h.kind==="terminal");n.useEffect(()=>{E.current=ve},[ve]);const ba=n.useMemo(()=>({fetchState:Wi,createShell:Vi,terminateShell:zi,updateShell:Gi,connectSocket:xd}),[]),ya=n.useCallback(h=>$e(h),[]),_t=n.useCallback(h=>{r($e(h))},[r]),wa=n.useCallback(h=>ds(h),[]),ja=n.useCallback(({close:h,closeNavigation:b,currentWorkspaceId:w})=>e.jsx(pa,{variant:"dialog",initialWorkspaceId:w,onCancel:h,onCreated:T=>{h(),b(),r($e(T.id))}}),[r]),Na=n.useCallback(({threadId:h,path:b})=>Ii(h,{path:b}),[]),[ka,ws]=n.useState({prompt:"",attachments:[]}),[ce,Sa]=n.useState(null),[Ca,jt]=n.useState(!1),[no,Ta]=n.useState(!1),[oo,Ea]=n.useState(!1),[Ra,Ia]=n.useState(null),[ot,Bt]=n.useState("idle"),[et,Aa]=n.useState({status:v.current?"checking":"offline",browserOnline:v.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()=>{Hc(h)}},[we]);const[Ve,js]=n.useState(null),[Ns,Pa]=n.useState(!1),[lo,oe]=n.useState(null),ks=((vr=se==null?void 0:se.hostConfigFiles.find(h=>{var b;return(b=h.roles)==null?void 0:b.includes("mcp")}))==null?void 0:vr.name)??null,{exportBusy:Ss,exportDialogOpen:Ft,exportTurnsState:Oa,forkTurnOptionsState:io,goalState:La,handleCreateHook:co,handleExportTranscript:Ua,handleForkLatest:uo,handleForkTurn:mo,handleOpenForkTurns:ho,handleOpenGoal:fo,handleOpenHooks:po,handleOpenMcp:xo,handleOpenSkills:go,handleTrustHook:vo,handleUntrustHook:bo,handleUpdateGoal:yo,handleUpdateHook:wo,hooksState:jo,loadExportTurns:Da,mcpState:No,setExportDialogOpen:Cs,setGoalState:Ts,skillsState:ko}=Sc({detailRef:D,id:t,navigate:r,setDetail:K,setError:oe,setThreads:ee}),[Es,qt]=n.useState(!1),[$a,ze]=n.useState({status:"idle",shares:[],error:null}),[Vt,zt]=n.useState({status:"idle",access:null,error:null}),Ma=mn(a.pathname),lt=at()&&!!Ma,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",So=(m==null?void 0:m.workspace.id)??(m==null?void 0:m.thread.workspaceId)??null,Co=lt?(ie==null?void 0:ie.kind)==="owner"?"write":(ie==null?void 0:ie.kind)==="shared"&&ie.workspaceId&&ie.workspaceId===So?ie.workspaceAccess:"none":"write",ht=n.useCallback(async()=>{const h=D.current,b=Ke();if(!at()||!h||!b){ze({status:"ready",shares:[],error:null});return}ze(w=>({...w,status:"loading",error:null}));try{const T=(await Nn()).sharedByMe.filter(M=>M.deviceId===b&&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]),_a=n.useCallback(async h=>{const b=D.current,w=Ke();if(!at()||!b||!w){ze(M=>({...M,status:"failed",error:"Relay sharing is only available from a relay device route."}));return}const T=h.workspaceAccess==="none"?null:b.workspace.id??b.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 Jl({targetIdentifier:h.targetIdentifier,deviceId:w,threadId:b.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]),Ba=n.useCallback(async h=>{qt(!0),ze(b=>({...b,error:null}));try{await kn(h),await ht()}catch(b){const w=ts(b,"Unable to revoke share.");ze(T=>({...T,status:"failed",error:w})),oe(w)}finally{qt(!1)}},[ht]),Wa=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,b=Ke();if(!at()||!h||!b){zt({status:"idle",access:null,error:null});return}let w=!1;return zt(T=>({...T,status:"loading",error:null})),Fl({deviceId:b,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]),Gn({enabled:!!t,setThreads:ee});const Fa=n.useCallback(()=>{const h=i.current;i.current="",c.current=null,h&&n.startTransition(()=>{u(b=>b+h)})},[]),qa=n.useCallback(h=>{i.current+=h,c.current===null&&(c.current=window.requestAnimationFrame(()=>{Fa()}))},[Fa]),Va=n.useCallback((h,b)=>{y(w=>{const T=(w==null?void 0:w.turnId)===h?w.items:[],M=T.findIndex(de=>de.id===b.id),q=Fn(T[M],b),me=M>=0?T.map((de,xe)=>xe===M?q:de):[...T,q];return{turnId:h,items:me,updatedAt:new Date().toISOString()}})},[]),za=n.useCallback((h,b,w,T,M)=>{y(q=>{const me=(q==null?void 0:q.turnId)===h?q.items:[],de=me.find(Te=>Te.id===b),xe=(de==null?void 0:de.kind)==="agentMessage"?{...de,text:`${de.text}${w}`,sequence:T??de.sequence??null}:{id:b,createdAt:M??new Date().toISOString(),kind:"agentMessage",text:w,sequence:T},B=me.findIndex(Te=>Te.id===b),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 b=J.current,w=b&&Object.keys(b).length>0?{...h,thread:{...h.thread,...b}}:h,T={...w,turns:mc(w.turns,E.current)},M=D.current;X(T.livePlan??null);const q=it((M==null?void 0:M.turns)??[],T.turns,T.thread.activeTurnId);D.current={...T,turns:q},y(B=>xc(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:Fr(B.pendingRequests,T.pendingRequests,Y.current),...B.goalHistory?{goalHistory:B.goalHistory}:{}}:B?{...T,turns:it(B.turns,T.turns,T.thread.activeTurnId),pendingRequests:Fr(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||ha(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=wc(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&&fa(B.prompt)&&T.thread.activeTurnId&&T.thread.status==="running"){const ue=de.get(T.thread.activeTurnId);if(ue&&zn(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(""),X(null),y(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 b=!1;const w=async()=>{var M;try{const q=await bi(h);b||z(((M=q.usage)==null?void 0:M.authKind)==="subscription"&&q.usage.windows.length>0?q.usage:null)}catch{b||z(q=>q?{...q,stale:!0}:null)}};w();const T=window.setInterval(w,6e4);return()=>{b=!0,window.clearInterval(T)}},[m==null?void 0:m.thread.lastTurnCompletedAt,m==null?void 0:m.thread.provider,k]);const Ga=n.useCallback(async({seedThread:h}={})=>{var me;const b=V.current+1;V.current=b;const w=(h==null?void 0:h.provider)??((me=D.current)==null?void 0:me.thread.provider)??"codex",[T,M,q]=await Promise.allSettled([la(),Cn(w),os(w)]);V.current===b&&(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)))},[]),Ze=n.useCallback(async({showLoading:h=!0,clearError:b=!0,reportError:w=!0,limit:T=Gr}={})=>{if(P.current>0){L.current=!0;return}const M=U.current+1;U.current=M,h&&bs(!0),b&&oe(null);try{const q=await Rr(t,{limit:T});if(U.current!==M)return;Gt(q),re.current!==q.thread.provider&&Ga({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,Ga]),ft=n.useCallback(h=>{const b=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,Ze({showLoading:!1,clearError:!1,reportError:!1}))},0)}});return R.current=b.then(()=>{},()=>{}),b},[Gt,Ze]),Re=n.useCallback(()=>{var de;const h=((de=f.current)==null?void 0:de.readyState)??es,b=h===gt,w=v.current,T=Date.now(),M=x.current!==null&&T-Date.parse(x.current)<=qs,q=S.current!==null&&T-S.current<=qs;let me;w?b&&q?me="connected":h===Vs||g.current!==null||M||q||N.current?me="reconnecting":me="checking":me="offline",Aa(xe=>xe.status===me&&xe.browserOnline===w&&xe.healthOk===M&&xe.socketOpen===b&&xe.lastHealthyAt===x.current?xe:{status:me,browserOnline:w,healthOk:M,socketOpen:b,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([]),y(null),J.current=null,Q.current=null,Y.current=new Set,x.current=null,S.current=null,d.current=!1,v.current=typeof navigator>"u"?!0:navigator.onLine,Aa({status:v.current?"checking":"offline",browserOnline:v.current,healthOk:!1,socketOpen:!1,lastHealthyAt:null})},[t,Ma]),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:b}=document;return h.classList.add("thread-detail-scroll-locked"),b.classList.add("thread-detail-scroll-locked"),()=>{h.classList.remove("thread-detail-scroll-locked"),b.classList.remove("thread-detail-scroll-locked")}},[]),n.useEffect(()=>{Ze({showLoading:!0,limit:Gr})},[Ze]),n.useEffect(()=>{let h=!1,b=null;const w=()=>{Ze({showLoading:!1,clearError:!1,reportError:!1})},T=()=>{g.current!==null&&(window.clearTimeout(g.current),g.current=null)},M=()=>{h||!v.current||g.current!==null||(g.current=window.setTimeout(()=>{g.current=null,!h&&xe()},Ac),Re())},q=()=>{const C=f.current;if(f.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?za($,G,C.payload.delta,ue,C.payload.createdAt??C.timestamp):qa(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=Nc(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(""),y(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"&&pc(C.payload.request)&&(Y.current.delete(C.payload.request.id),K($=>$&&hc($,C.payload.request))),C.type==="thread.request.resolved"&&typeof C.payload.requestId=="string"){const $=C.payload.requestId;Y.current.add($),K(G=>G&&fc(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"&&Va($,G)}C.type==="thread.plan.updated"&&Array.isArray(C.payload.plan)&&X({turnId:String(C.payload.turnId??""),explanation:typeof C.payload.explanation=="string"?C.payload.explanation:null,plan:C.payload.plan})}},de=()=>{const C=f.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||!v.current){Re();return}const C=((G=f.current)==null?void 0:G.readyState)??es;if(C===Vs||C===gt){Re();return}const $=Pn(me);f.current=$,Re(),$.addEventListener("message",ue=>{if(f.current===$)try{const he=JSON.parse(ue.data);(he.type==="supervisor.connected"||he.type==="supervisor.pong")&&(S.current=Date.now(),Re())}catch{}}),$.addEventListener("open",()=>{f.current===$&&(d.current=!0,Z(ue=>ue+1),w(),de(),Re())}),$.addEventListener("close",()=>{f.current===$&&(f.current=null),d.current=!0,M(),Re()}),$.addEventListener("error",()=>{f.current===$&&(f.current=null),d.current=!0,M(),Re()})},B=async()=>{var C;if(!(h||!v.current||N.current)){N.current=!0,Re();try{await Ci();const $=d.current;x.current=new Date().toISOString(),$&&(d.current=!1,w()),(((C=f.current)==null?void 0:C.readyState)??es)!==gt&&xe()}catch{x.current=null,d.current=!0,M()}finally{N.current=!1,Re()}}},Ae=()=>{v.current=!0,d.current=!0,Re(),xe(),B()},Te=()=>{v.current=!1,x.current=null,S.current=null,d.current=!0,T(),q(),Re()},Ie=()=>{var G;if(h||!v.current){Re();return}const C=((G=f.current)==null?void 0:G.readyState)??es,$=S.current===null?null:Date.now()-S.current;C===gt&&$!==null&&$>qs?(d.current=!0,q(),M()):C===gt?de():C!==Vs&&xe(),B(),Re()};return window.addEventListener("online",Ae),window.addEventListener("offline",Te),xe(),B(),b=window.setInterval(Ie,Pc),()=>{h=!0,window.removeEventListener("online",Ae),window.removeEventListener("offline",Te),T(),b!==null&&window.clearInterval(b),Ge(),q()}},[za,Ge,t,Ze,qa,Re,Va]),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 b=window.setInterval(()=>{Ze({showLoading:!1,clearError:!1,reportError:!1})},Oc);return()=>{window.clearInterval(b)}},[m==null?void 0:m.thread.activeTurnId,m==null?void 0:m.thread.status,ge.length,ve,j,Ze,Wt.length,we]);const Ja=n.useCallback(async()=>{var h;if(!(!m||m.turns.length===0||Ht)){ys(!0),oe(null);try{const b=(h=m.turns[0])==null?void 0:h.id,w=await Rr(t,{limit:Ic,...b?{beforeTurnId:b}:{}});K(T=>T?{...T,turns:uc(T.turns,w.turns),totalTurnCount:Math.max(T.totalTurnCount??T.turns.length,w.totalTurnCount??w.turns.length)}:w)}catch(b){oe(b instanceof Error?b.message:"Unable to load earlier turns.")}finally{ys(!1)}}},[m,t,Ht]);async function To(h){var Ae,Te,Ie;if(_e==="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=p.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=p.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 b=D.current,w=b?{...b.thread,...J.current??{}}:null,T=(w==null?void 0:w.model)??null,M=(w==null?void 0:w.reasoningEffort)??null,q=bc(),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(Xt=>Xt?{...Pe,turns:it(Xt.turns,Pe.turns,Pe.thread.activeTurnId)}:Pe),ee(Xt=>Xt.map(br=>br.id===Pe.thread.id?Pe.thread:br))}const $=C?{...C.thread,...J.current??{}}:null,G=($==null?void 0:$.status)==="running"?$.activeTurnId:null,ue=_e==="chat"&&!!G;ue&&G?mt(je=>[...je,{id:de,clientRequestId:q,turnId:G,prompt:h.prompt,createdAt:xe,status:"steering"}]):(B=Yr(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:Fs(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 Ki(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=Yr(h.attachments),Ge(),u(""),X(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:Fs(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),X(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 Ka(h){if(te.current)return!1;te.current=!0;try{return await To(h)}finally{te.current=!1}}async function Eo(){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 b=await Ls(t,{...h.thread.model?{model:h.thread.model}:{}});return K(w=>w?{...b,turns:it(w.turns,b.turns,b.thread.activeTurnId)}:b),ee(w=>w.map(T=>T.id===b.thread.id?b.thread:T)),!0}catch(b){return oe(b instanceof Error?b.message:"Unable to connect this thread before setting its goal."),!1}finally{Qe(!1)}}async function Ro(h){var me;const b=((me=h.objective)==null?void 0:me.trim())??"",w=b?`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:b,attachmentPreviews:[],model:(q==null?void 0:q.model)??null,reasoningEffort:(q==null?void 0:q.reasoningEffort)??null,reasoningEffortAvailable:Fs(be,(q==null?void 0:q.model)??null),tokenUsage:null,priceEstimate:null}));try{await yo(h),await Ze({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 Io(){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 Ji(t);K(T=>T?{...w,turns:it(T.turns,w.turns,w.thread.activeTurnId)}:w),Sa(null),ee(T=>T.map(M=>M.id===w.thread.id?w.thread:M)),jt(!1);return}const b=await Ls(t,{...m.thread.model?{model:m.thread.model}:{}});K(w=>w?{...b,turns:it(w.turns,b.turns,b.thread.activeTurnId)}:b),ee(w=>w.map(T=>T.id===b.thread.id?b.thread:T)),h!=null&&h.attachShell&&_e==="shell"&&jt(!0)}catch(b){oe(b instanceof Error?b.message:"Unable to change connection state.")}finally{Qe(!1)}}}async function Jt(){var h;if(_e==="shell"){const b=((h=p.current)==null?void 0:h.sendControl("ctrl_c"))??!1;oe(b?null:"Connect the shell before sending Ctrl-C.");return}Qe(!0),oe(null);try{const b=m!=null&&m.thread.activeTurnId?await Ir(t,{turnId:m.thread.activeTurnId}):await Ir(t);K(w=>w&&{...w,thread:b}),ee(w=>w.map(T=>T.id===b.id?b:T)),Ge(),u("")}catch(b){oe(b instanceof Error?b.message:"Unable to interrupt turn.")}finally{Qe(!1)}}async function Is(h){if(!m)return;const b=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};Ta(!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 Xi(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=b?{...b,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=b,K(b),ee(q=>q.map(me=>me.id===b.thread.id?b.thread:me)),oe(M instanceof Error?M.message:"Unable to update thread settings.")}finally{Ta(!1)}}const Ya=n.useCallback(async(h,b)=>{if((ie==null?void 0:ie.kind)==="shared"&&ie.threadAccess==="read"){oe("This shared session is view only.");return}Ia(h),oe(null);try{await ft(async()=>{const w=await ud(t,h,b);return Y.current.add(h),w})}catch(w){oe(w instanceof Error?w.message:"Unable to answer this request.")}finally{Ia(null)}},[t,ie,ft]),Za=n.useCallback(h=>Li(t,h),[t]),Xa=n.useCallback(async(h,b)=>{oe(null);try{await ft(()=>Yi(h,b))}catch(w){throw oe(w instanceof Error?w.message:"Unable to cancel queued prompt."),w}},[ft]),Qa=n.useCallback(async(h,b)=>{oe(null);try{await ft(()=>Zi(h,b))}catch(w){throw oe(w instanceof Error?w.message:"Unable to steer queued prompt."),w}},[ft]);async function As(){if(m){Ea(!0),oe(null);try{const h=await Qi(t);K(b=>b&&{...b,thread:h}),ee(b=>b.map(w=>w.id===h.id?h:w))}catch(h){oe(h instanceof Error?h.message:"Unable to compact this thread context.")}finally{Ea(!1)}}}async function er(h,b){try{const w=await In(h,{title:b});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 tr(){if(Ve){Pa(!0),oe(null);try{await An(Ve.id),ee(b=>b.filter(w=>w.id!==Ve.id));const h=Ve.id===(m==null?void 0:m.thread.id);if(js(null),h){const b=fe.find(w=>w.id!==Ve.id&&w.workspaceId===(m==null?void 0:m.thread.workspaceId))??fe.find(w=>w.id!==Ve.id);r(b?$e(b.id):Ot())}}catch(h){oe(h instanceof Error?h.message:"Unable to delete thread.")}finally{Pa(!1)}}}function sr(){ga(h=>h==="chat"?(m!=null&&m.thread.isLoaded&&jt(!0),"shell"):"chat")}async function ar(){var b;const h=await((b=p.current)==null?void 0:b.copyLastCommandOutput());oe(h?null:"Unable to copy the last shell command output.")}function rr(h){var w,T;const b=h==="clear"?((w=p.current)==null?void 0:w.sendCommand("clear"))??!1:((T=p.current)==null?void 0:T.sendControl(h))??!1;oe(b?null:"Connect the shell before sending control input.")}n.useEffect(()=>{if(!(!Ca||_e!=="shell"||!p.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),p.current.toggleConnection()}},[_e,m==null?void 0:m.thread.isLoaded,Ca,ce==null?void 0:ce.loading,ce==null?void 0:ce.status]),n.useEffect(()=>{if(_e!=="shell")return;const h=window.requestAnimationFrame(()=>{var b;(b=p.current)==null||b.refreshLayout({syncBackendSize:!1})});return()=>{window.cancelAnimationFrame(h)}},[_e]);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:Ao,timelineBottomSpacer:nr,useFloatingMobileComposer:Po}=kc({activeView:_e,composerHostRef:O,threadId:(m==null?void 0:m.thread.id)??t}),Oo=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 Io(),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(Bc,{})})})]}),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:Jo(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:yr(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,Lo=null,or=we&&m?jc(m.turns,we):null,lr=n.useMemo(()=>we&&!or?{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,[or,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)]",ir=Wc(St,et),Yt=[ir,St?null:"Tap to connect this thread",et.lastHealthyAt?`Last healthy ${yr(et.lastHealthyAt)}`:null].filter(Boolean).join(" · "),dr=St?e.jsx("div",{role:"status","aria-live":"polite","aria-label":ir,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"})}),cr=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"})}),ur=La.data??(m==null?void 0:m.goal)??null,mr=(m==null?void 0:m.goalHistory)??[],Uo=ur?ps(mr,ur):qn(mr),Zt=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:`${Jr(ie.threadAccess)} / ${Kr(ie.workspaceAccess)}`,children:[e.jsx("span",{children:Jr(ie.threadAccess)}),e.jsx("span",{className:"host-muted",children:"/"}),e.jsx("span",{className:"truncate",children:Kr(ie.workspaceAccess)})]}):null,[ie]),Do=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]),$o=n.useMemo(()=>e.jsxs("div",{className:"relative flex items-center justify-end gap-1.5",children:[Zt,dr]}),[dr,Zt]),Mo=n.useMemo(()=>e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[Zt,cr]}),[cr,Zt]),Ho=n.useMemo(()=>({livePlan:j,liveItems:ve,respondingRequestId:Ra,onRespondToRequest:Ya,scrollRequestKey:pe,previousTurnScrollRequestKey:Xe,nextTurnScrollRequestKey:Mt,bottomSpacer:nr,className:"thread-timeline-surface min-h-0 flex-1",onTailVisibilityChange:ae,onPreviousTurnAvailabilityChange:ut,onNextTurnAvailabilityChange:so,loadingEarlier:Ht,onLoadEarlier:Ja,onOpenThread:_t,answeredRequestNotes:(m==null?void 0:m.answeredRequestNotes)??Lc,activityNotes:(m==null?void 0:m.activityNotes)??Uc,pendingSteers:(m==null?void 0:m.pendingSteers)??Dc,optimisticSteers:Wt,optimisticTurn:lr}),[m==null?void 0:m.answeredRequestNotes,m==null?void 0:m.activityNotes,m==null?void 0:m.pendingSteers,Ja,Ya,ve,j,Ht,_t,Wt,Ra,pe,Xe,Mt,nr,lr]),hr=m?{busy:_e==="chat"?nt:!1,settingsBusy:no,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:H,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:_,threadConnected:m.thread.isLoaded,shellAvailable:va,disabled:!!kt,...kt?{disabledPlaceholder:kt}:{},shellControlState:ce,draftPrompt:ka.prompt,draftAttachments:ka.attachments,onDraftChange:ws,canInterrupt:!!(m.thread.activeTurnId&&Le),...Le?{onInterrupt:Jt}:{},...Le?{onCompact:As,onOpenForkTurns:ho,onForkLatest:uo,onForkTurn:mo,onOpenSkills:go,onOpenMcp:xo,onOpenHooks:po,onCreateHook:co,onUpdateHook:wo,onTrustHook:vo,onUntrustHook:bo}:{},goalState:La,goalHistory:Uo,...Le?{onOpenGoal:fo,onPrepareGoalSubmit:Eo,onUpdateGoal:Ro}:{},...ks?{...Nt?{onReadProviderConfig:()=>En(m.thread.provider,ks),onWriteProviderConfig:h=>Rn(m.thread.provider,ks,{content:h})}:{}}:{},onToggleFollow:()=>Ee(h=>h+1),canJumpToPreviousTurn:vs,onJumpToPreviousTurn:()=>rt(h=>h+1),canJumpToNextTurn:to,onJumpToNextTurn:()=>ct(h=>h+1),...Le?{onUpdateSettings:Is}:{},onToggleView:sr,onShellCopy:ar,...Le?{onShellControl:rr}:{},compactBusy:oo,skillsState:ko,mcpState:No,hooksState:jo,forkTurnOptionsState:io}:null,fr=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:va,shellControlState:ce,canInterrupt:!!(m.thread.isLoaded&&(ce!=null&&ce.isCommandRunning)&&Le),...Le?{onInterrupt:Jt}:{},onToggleView:sr,onShellCopy:ar,...Le?{onShellControl:rr}:{}}:null,pr=n.useCallback(h=>m?Na({threadId:m.thread.id,path:h}):"",[m==null?void 0:m.thread.id,Na]),xr=Rc({setError:oe,workspaceId:(m==null?void 0:m.workspace.id)??null,access:Co}),gr=n.useCallback(h=>{const b=D.current;if(!b)return;const w=_c(h.path,b.workspace.absPath);if(w===null){oe(`Cannot open ${h.path}; it is outside this workspace.`);return}ga("chat"),ro(T=>({path:w,...h.line!==void 0?{line:h.line}:{},requestId:((T==null?void 0:T.requestId)??0)+1}))},[]),_o=n.useMemo(()=>({openThread:_t,getThreadHref:ya,getNewThreadHref:wa,renderNewThreadDialogContent:ja,...Nt?{renameThread:er}:{},...Nt?{deleteThread:js}:{},cancelPendingSteer:Xa,...Le?{steerPendingPrompt:Qa}:{},sendPrompt:Ka,...Le?{interrupt:Jt}:{},...Le?{compact:As}:{},...Le?{updateSettings:Is}:{},loadHistoryItemDetail:Za,getImageAssetUrl:pr,openWorkspaceFile:gr,workspace:xr,shell:ba}),[pr,wa,ya,ja,As,Xa,Qa,Jt,Za,gr,Ka,er,Is,ba,_t,Le,Nt,xr]),Bo=m!=null&&m.thread.workspaceId?Ot(m.thread.workspaceId):xs(),Wo=n.useMemo(()=>e.jsxs(e.Fragment,{children:[e.jsx(Ko,{open:Ft,busy:Ss||Es,turnsState:Oa,shareAvailable:Ha,...lt&&(ie==null?void 0:ie.kind)==="shared"?{shareUnavailableMessage:"Only the owner can share this session."}:{},shareState:$a,onCancel:()=>{!Ss&&!Es&&Cs(!1)},onLoadTurns:Da,onExport:Ua,...Ha?{onCreateShare:_a,onOpenDeviceSharing:Wa,onRevokeShare:Ba}:{}}),e.jsx(aa,{open:Ve!==null,title:"Delete Thread",description:Ve?`Delete ${fl(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 tr()})]}),[Ve,Ns,Ss,Ft,Oa,_a,tr,Ua,Wa,Ba,Da,lt,Es,$a]);return e.jsx(Yo,{threads:fe,detail:m,status:ke,loading:xa,error:xa?null:lo,plugins:l,adapter:_o,metaContent:Oo,settingsContent:Lo,globalSettingsContent:e.jsx(ia,{embedded:!0}),mobileHeaderAction:$o,workspaceReturnHref:Bo,onCloseAppNavigation:(o==null?void 0:o.closeNav)??(()=>{}),threadActionsButton:Do,surfaceActions:Mo,workspaceFeatures:$c,workspaceFocusPathRequest:ao,activeView:_e,liveOutput:ge,timelineProps:Ho,timelineComponent:Xo,useFloatingMobileComposer:Po,floatingMobileComposerBottomOffset:Ao,composerHostRef:O,shellPanelRef:p,shellPanelComponent:Zo,shellEffectiveTheme:(o==null?void 0:o.effectiveTheme)??"dark",shellThemeMode:(o==null?void 0:o.themeMode)??"system",...o!=null&&o.setThemeMode?{onShellThemeModeChange:o.setThemeMode}:{},onShellStateChange:Sa,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:Wo,...hr?{composerProps:hr}:{},...fr?{shellComposerProps:fr}:{}})}function Xr(){const t=Ye(),[s,a]=n.useState(""),[r,o]=n.useState(Je),[l,i]=n.useState([]),[c,f]=n.useState(!0),[g,N]=n.useState(!1),[x,S]=n.useState(null);n.useEffect(()=>{let p=!1;return f(!0),cs().then(O=>{var P,R;if(p)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(()=>{p||i([])}).finally(()=>{p||f(!1)}),()=>{p=!0}},[]);const v=n.useMemo(()=>l.length>0?l:[{provider:Je,displayName:wr[Je].displayName,enabled:!0}],[l]);async function d(p){p.preventDefault();const O=s.trim();if(!O){S("Session ID is required.");return}N(!0),S(null);try{const U=await qi({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:p=>o(p.target.value),disabled:g||c,className:"host-form-control mt-2 w-full rounded-lg border px-4 py-3 outline-none transition",children:v.map(p=>e.jsxs("option",{value:p.provider,children:[p.displayName||wr[p.provider].displayName,p.enabled?"":" (not ready)"]},p.provider))})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"session-id",className:"host-form-label text-sm font-medium",children:"Session ID"}),e.jsx("input",{id:"session-id",value:s,onChange:p=>a(p.target.value),placeholder:"019d6fb7-7033-7a30-a2c7-74d0919e87d4",className:"host-form-control mt-2 w-full rounded-lg border px-4 py-3 outline-none transition"})]}),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 Jn({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 Qr(){const t=Ye(),[s]=sa(),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(Jn,{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(pa,{initialWorkspaceId:a,initialTitle:r,onCancel:o,onCreated:l=>t($e(l.id))})})}function Fc(t){return ds(t)}function qc({getThreadHref:t,onOpenThread:s,getNewThreadHref:a,renderThreadLink:r,onCloseAppNavigation:o,...l}){const i=Ye(),c=Dt(),f=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(Qo,{...l,workspaceReturnHref:l.workspaceReturnHref??xs(),globalSettingsContent:l.globalSettingsContent??e.jsx(ia,{embedded:!0}),...g?{effectiveTheme:g}:{},...N?{themeMode:N}:{},...x?{onThemeModeChange:x}:{},getThreadHref:t??(S=>$e(S)),onOpenThread:s??(S=>i($e(S))),getNewThreadHref:a??Fc,renderNewThreadDialogContent:l.renderNewThreadDialogContent??(({close:S,closeNavigation:v,currentWorkspaceId:d})=>e.jsx(pa,{variant:"dialog",initialWorkspaceId:d,onCancel:S,onCreated:p=>{S(),v(),i($e(p.id))}})),renderThreadLink:r??(({thread:S,children:v,className:d,onClick:p})=>e.jsx(Ue,{to:$e(S.id),className:d,onClick:p,children:v})),...f?{onCloseAppNavigation:f}:{}})}function Kn({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 f(g){g.preventDefault(),c()}return nn.createPortal(e.jsxs("div",{className:"fixed inset-0 z-[95] flex items-center justify-center p-4 sm:p-6",children:[e.jsx("button",{type:"button","aria-label":"Close rename dialog",onClick:i,disabled:o,className:"ui-overlay-scrim absolute inset-0 backdrop-blur-sm disabled:cursor-not-allowed"}),e.jsxs("form",{role:"dialog","aria-modal":"true","aria-label":s,onSubmit:f,className:"host-dialog relative z-[1] w-full max-w-md rounded-lg border p-5 shadow-[var(--theme-shadow)] sm:p-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"host-page-title text-sm font-medium",children:s}),e.jsx("p",{className:"host-muted mt-1 text-sm",children:"Changes are saved only after confirmation."})]}),e.jsx("button",{type:"button","aria-label":"Close dialog",onClick:i,disabled:o,className:"host-icon-button inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full border transition disabled:cursor-not-allowed disabled:opacity-60",children:e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-current",children:e.jsx("path",{d:"M3.22 2.47 8 7.25l4.78-4.78 1.06 1.06L9.06 8.31l4.78 4.78-1.06 1.06L8 9.37l-4.78 4.78-1.06-1.06 4.78-4.78-4.78-4.78 1.06-1.06Z"})})})]}),e.jsxs("div",{className:"mt-5",children:[e.jsx("label",{htmlFor:"rename-dialog-input",className:"host-form-label text-sm font-medium",children:a}),e.jsx("input",{id:"rename-dialog-input","aria-label":a,autoFocus:!0,value:r,onChange: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 en(){const[t]=sa(),s=Ye(),a=Dt(),r=t.get("workspaceId"),[o,l]=n.useState([]),[i,c]=n.useState([]),[f,g]=n.useState(null),[N,x]=n.useState(!0),[S,v]=n.useState(null),[d,p]=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),v(null);try{const[A,W,ne]=await Promise.all([Cn(D).then(H=>H.status),la(),oa()]);g(A),l(W),c(ne)}catch(A){v(A instanceof Error?A.message:"Unable to load threads.")}finally{x(!1)}},[D]);n.useEffect(()=>{if(r===null)return;te();const A=Pn(W=>{l(ne=>ne.map(H=>H.id===W.threadId?{...H,status:W.type==="thread.updated"&&typeof W.payload.status=="string"?W.payload.status:H.status,lastError:(W.type==="thread.turn.failed"||W.type==="thread.turn.completed")&&typeof W.payload.error=="string"?W.payload.error:H.lastError,title:W.type==="thread.updated"&&typeof W.payload.title=="string"?W.payload.title:H.title}:H))});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(Gn({enabled:r!==null,setThreads:l}),r===null)return e.jsx(is,{to:xs(),replace:!0});function ee(){switch(f==null?void 0:f.state){case"ready":return"bg-teal-300 shadow-[0_0_0_3px_rgba(94,234,212,0.14)]";case"starting":return"bg-[var(--status-warning-fg)] shadow-[0_0_0_3px_var(--status-warning-bg)]";case"degraded":case"failed":return"bg-rose-400 shadow-[0_0_0_3px_rgba(251,113,133,0.14)]";default:return"bg-slate-500 shadow-[0_0_0_3px_rgba(100,116,139,0.14)]"}}async function be(A,W){try{const ne=await In(A,{title:W});l(H=>H.map(z=>z.id===ne.id?{...z,title:ne.title,updatedAt:ne.updatedAt}:z))}catch(ne){throw v(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),p(null),U("")}finally{R(null)}}}async function ke(){if(L){Q(!0);try{await An(L.id),l(A=>A.filter(W=>W.id!==L.id)),V(null)}catch(A){v(A instanceof Error?A.message:"Unable to delete thread.")}finally{Q(!1)}}}return e.jsx(qc,{threads:o,workspaceLabels:J,status:f,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:(f==null?void 0:f.lastError)??((f==null?void 0:f.state)==="ready"?"Ready":(f==null?void 0:f.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(el,{threads:m,currentWorkspaceId:r,workspaceLabels:J,onOpenThread:A=>s($e(A)),onBeginRenameThread:A=>{p(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(Kn,{open:d!==null,title:"Rename Thread",label:"Thread Title",value:O,busy:P!==null,onChange:U,onCancel:()=>{p(null),U("")},onSubmit:()=>void ye()}),e.jsx(aa,{open:L!==null,title:"Delete Thread",description:L?`Delete ${dl(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 tn(t){const s=t.trim(),a=s.replace(/[\\/]+$/,"");if(!a)return"";if(Yn(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 Yn(t){const s=t.trim();return/^https?:\/\/.+/i.test(s)||/^ssh:\/\/.+/i.test(s)||/^git@[^:]+:.+/.test(s)}function Vc({initialPath:t="",initialLabel:s="",submitLabel:a="Save Workspace",error:r,busy:o=!1,surface:l=!0,onSubmit:i}){const c=tn(t),[f,g]=n.useState(t),[N,x]=n.useState(s||c),[S,v]=n.useState(null),d=n.useRef(c);n.useEffect(()=>{const U=tn(f);x(P=>!P.trim()||P===d.current?U:P),d.current=U},[f]);async function p(U){U.preventDefault();const P=f.trim();if(!P){v("Workspace path or Git URL is required.");return}v(null);const R=N.trim(),L=Yn(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:p,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:f,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 sn(){const t=Ye(),[s,a]=n.useState(null),[r,o]=n.useState(!1),[l,i]=n.useState(null);n.useEffect(()=>{Sn().then(f=>i(f.devHome)).catch(()=>i(null))},[]);async function c(f){o(!0),a(null);try{const g="absPath"in f&&l&&/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(f.absPath)?{...f,absPath:`${l.replace(/\/$/,"")}/${f.absPath}`}:f,N=await md(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(Jn,{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(Vc,{busy:r,error:s,submitLabel:"Create Workspace",surface:!1,onSubmit:c})})}function an(t){return Date.parse(t.lastOpenedAt??t.createdAt)}function zc(t,s){return t.isFavorite!==s.isFavorite?t.isFavorite?-1:1:an(s)-an(t)}function Gc(t){return t?new Date(t).toLocaleString():"Never opened"}function Jc(t,s=28){return t.length<=s?t:`...${t.slice(-(s-3))}`}function Kc({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 Yc(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-3.5 w-3.5 fill-current",children:e.jsx("path",{d:"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 rn(){const t=Ye(),[s,a]=n.useState([]),[r,o]=n.useState(!0),[l,i]=n.useState(null),[c,f]=n.useState(null),[g,N]=n.useState(null),[x,S]=n.useState(null),[v,d]=n.useState(""),[p,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"},H=async()=>{const[z,k]=await Promise.allSettled([oa(),Ul()]);if(!A){if(z.status==="rejected"&&ne(z)||k.status==="rejected"&&ne(k)){D(!0),o(!0),N(null),f(null),J(Z=>Z+1),W=setTimeout(()=>void H(),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),f(null)):f(k.reason instanceof Error?k.reason.message:"Unable to load supervisor config.")}};return H(),()=>{A=!0,W&&clearTimeout(W)}},[]);async function Y(A){const W={...A,isFavorite:!A.isFavorite};a(ne=>ne.map(H=>H.id===A.id?W:H));try{const ne=await pd(A.id,{isFavorite:!A.isFavorite});a(H=>H.map(z=>z.id===ne.id?ne:z))}catch(ne){a(H=>H.map(z=>z.id===A.id?A:z)),N(ne instanceof Error?ne.message:"Unable to update workspace.")}}async function m(A){const W=v.trim();if(W){O(A);try{const ne=await hd(A,{label:W});a(H=>H.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 fd(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(zc),[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(ca,{}),e.jsx(Ue,{to:kr("/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:kr("/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(Yc,{})}),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(Kc,{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:Jc(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: ",Gc(A.lastOpenedAt)]})})]})})]},A.id))})]}),e.jsx(Zc,{config:l,error:c,vmStarting:Q,workspaceCount:s.length})]}),e.jsx(Kn,{open:x!==null,title:"Rename Workspace",label:"Workspace Label",value:v,busy:p!==null,onChange:d,onCancel:fe,onSubmit:()=>x?m(x):void 0}),e.jsx(tl,{open:U!==null,title:"Workspace Path",text:U??"",onClose:()=>P(null)}),e.jsx(aa,{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 Zc({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 Zn="remote-codex-theme-mode",Xn="remote-codex-default-backend",Qn="remote-codex-auto-collapse-completed-turns";function Xc({children:t}){const s=n.useMemo(()=>({fetchPlugins:Ui,importPlugin:Di,updatePlugin:$i,deletePlugin:Mi}),[]);return e.jsx(sl,{adapter:s,builtinPlugins:al,children:t})}function Qc(){if(typeof window>"u")return"system";const t=window.localStorage.getItem(Zn);return t==="light"||t==="dark"||t==="system"?t:"system"}function eu(){if(typeof window>"u")return Je;const t=window.localStorage.getItem(Xn);return ll(t)??Je}function tu(){return typeof window>"u"?!0:window.localStorage.getItem(Qn)!=="false"}function su(t){return(t==null?void 0:t.trim())||"Remote Codex"}function au(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 ru(){const t=Ut();return n.useEffect(()=>{document.title=su(au(t.pathname))},[t.pathname]),null}function nu(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function ou({themeMode:t,setThemeMode:s,effectiveTheme:a}){const[r,o]=n.useState(!1),[l,i]=n.useState(!1),[c,f]=n.useState(eu),[g,N]=n.useState(tu),[x,S]=n.useState(null),v=Ut(),p=!(/^\/threads\/(?:import|new)$/.test(v.pathname)||/^\/devices\/[^/]+\/threads\/(?:import|new)$/.test(v.pathname))&&(/^\/threads\/[^/]+$/.test(v.pathname)||/^\/devices\/[^/]+\/threads\/[^/]+$/.test(v.pathname)),O=v.pathname==="/threads"||/^\/devices\/[^/]+\/threads$/.test(v.pathname),U=p||O,P=O||p,R=v.pathname==="/workspaces"||/^\/devices\/[^/]+\/workspaces$/.test(v.pathname);n.useEffect(()=>{o(!1)},[v.pathname,v.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(ea,Q),()=>window.removeEventListener(ea,Q)},[]);function L(Q){f(Q),window.localStorage.setItem(Xn,Q)}function V(Q){N(Q),window.localStorage.setItem(Qn,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(rl.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?p?"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?p?"h-full min-h-0 overflow-hidden overscroll-none":"h-full overflow-hidden overscroll-none":""}`,children:e.jsx(Vo,{})})})]}),e.jsx(ia,{})]})}function lu({children:t}){const[s,a]=n.useState({status:"checking"});async function r(i){try{const c=await Dl();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 $l(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(Ln,{onLogin:o})]}):t}function iu({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 du({children:t}){return at()?e.jsx(iu,{children:t}):e.jsx(lu,{children:t})}function eo(){return at()?e.jsx(ic,{}):e.jsx(is,{to:"/workspaces",replace:!0})}function cu({themeMode:t,setThemeMode:s,effectiveTheme:a}){return e.jsxs(on,{children:[e.jsx(Ne,{path:"/",element:e.jsx(eo,{})}),e.jsxs(Ne,{element:e.jsx(ou,{themeMode:t,setThemeMode:s,effectiveTheme:a}),children:[e.jsx(Ne,{path:"/workspaces",element:e.jsx(rn,{})}),e.jsx(Ne,{path:"/workspaces/new",element:e.jsx(sn,{})}),e.jsx(Ne,{path:"/relay-account",element:e.jsx(bd,{})}),e.jsx(Ne,{path:"/relay-devices",element:e.jsx(Kd,{})}),e.jsx(Ne,{path:"/threads",element:e.jsx(en,{})}),e.jsx(Ne,{path:"/threads/import",element:e.jsx(Xr,{})}),e.jsx(Ne,{path:"/threads/new",element:e.jsx(Qr,{})}),e.jsx(Ne,{path:"/threads/:id",element:e.jsx(Zr,{})}),e.jsx(Ne,{path:"/devices/:relayDeviceId/workspaces",element:e.jsx(rn,{})}),e.jsx(Ne,{path:"/devices/:relayDeviceId/workspaces/new",element:e.jsx(sn,{})}),e.jsx(Ne,{path:"/devices/:relayDeviceId/threads",element:e.jsx(en,{})}),e.jsx(Ne,{path:"/devices/:relayDeviceId/threads/import",element:e.jsx(Xr,{})}),e.jsx(Ne,{path:"/devices/:relayDeviceId/threads/new",element:e.jsx(Qr,{})}),e.jsx(Ne,{path:"/devices/:relayDeviceId/threads/:id",element:e.jsx(Zr,{})})]})]})}function uu(){const[t,s]=n.useState(()=>Qc()),[a,r]=n.useState(()=>nu()),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(Zn,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(qo,{children:[e.jsx(ru,{}),e.jsx(Xc,{children:e.jsxs(on,{children:[e.jsx(Ne,{path:"/",element:e.jsx(eo,{})}),e.jsx(Ne,{path:"/relay-guide",element:e.jsx(lc,{})}),e.jsx(Ne,{path:"/relay-portal",element:e.jsx(dc,{})}),e.jsx(Ne,{path:"/relay-admin",element:e.jsx(yd,{})}),e.jsx(Ne,{path:"/*",element:e.jsx(du,{children:e.jsx(cu,{themeMode:t,setThemeMode:s,effectiveTheme:o})})})]})})]})})}zo.createRoot(document.getElementById("root")).render(e.jsx(Go.StrictMode,{children:e.jsx(uu,{})}));