remote-codex 0.11.24 → 0.11.26

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.
@@ -0,0 +1,5 @@
1
+ import{j as e,r as n,u as ua,d as He,L as ze,e as fo,f as Mr,b as xo,N as ma,B as go,h as Hr,i as je,O as bo,k as vo,c as yo}from"./react-vendor-CgLzZcV4.js";import{u as ot,a as _r,t as wo,f as Sa,T as jo,C as Ba,b as No,c as ko,d as So,e as Co,g as To,L as Eo,P as Io,A as Ao}from"./thread-ui-CaDgVQIY.js";import{l as ie}from"./ui-vendor-CeKGesq3.js";import"./graph-vendor-DVPtkh3h.js";import"./terminal-vendor-B365Go3Z.js";import"./markdown-vendor-BQJfKm05.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const o of l)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function s(l){const o={};return l.integrity&&(o.integrity=l.integrity),l.referrerPolicy&&(o.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?o.credentials="include":l.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(l){if(l.ep)return;l.ep=!0;const o=s(l);fetch(l.href,o)}})();var Ro=["codex","claude","opencode"],qe="codex",rr={codex:{displayName:"Codex",description:"Local Codex app-server runtime.",defaultTransport:"stdio",homeEnvVar:"CODEX_HOME",commandEnvVar:"CODEX_COMMAND",defaultHomeDir:".codex",defaultCommand:"codex"},claude:{displayName:"Claude Code",description:"Local Claude Code Agent SDK runtime.",defaultTransport:"sdk",homeEnvVar:"CLAUDE_HOME",commandEnvVar:"CLAUDE_COMMAND",defaultHomeDir:".claude",defaultCommand:"claude"},opencode:{displayName:"OpenCode",description:"Local OpenCode runtime.",defaultTransport:"sdk",homeEnvVar:"OPENCODE_HOME",commandEnvVar:"OPENCODE_COMMAND",defaultHomeDir:".opencode",defaultCommand:"opencode"}};function Po(t){return typeof t=="string"&&Ro.includes(t)}function Oo(t){return Po(t)?t:null}var nr=15;function Lo(t){return t.replace(/\s+/g," ").trim()}function Uo(t){const a=Lo(t);if(!a)return"";const s=Array.from(a);return s.length<=nr?a:`${s.slice(0,nr).join("")}...`}const Do=["codex","claude","opencode"],Br="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"}},or=15;function $o(t){return t.replace(/\s+/g," ").trim()}function Mo(t){const a=$o(t);if(!a)return"";const s=Array.from(a);return s.length<=or?a:`${s.slice(0,or).join("")}...`}function Ho(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-current",children:e.jsx("path",{d:"M2 3.25h12v1.5H2Zm0 4h12v1.5H2Zm0 4h12v1.5H2Z"})})}function Qt(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-current",children:e.jsx("path",{d:"M3.22 2.47 8 7.25l4.78-4.78 1.06 1.06L9.06 8.31l4.78 4.78-1.06 1.06L8 9.37l-4.78 4.78-1.06-1.06 4.78-4.78-4.78-4.78 1.06-1.06Z"})})}function Ca(t=!1){return`flex w-full items-center rounded-[0.95rem] px-3 py-2 text-left text-sm transition ${t?"cursor-not-allowed bg-[var(--theme-muted)] text-[var(--theme-fg-muted)]":"text-[var(--theme-fg)] hover:bg-[var(--theme-hover)]"}`}const _o=[{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."}],Fr={hostConfigFiles:[],toolboxItems:[],hookCommandTemplates:[],providerConfigFormat:"none",mcpConfigFormat:"none",configArchives:!1,buildRestart:!1},Bo={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 La(t){const a=Bo[t];return{packageName:a.packageName,installed:t==="codex",installedVersion:null,latestVersion:null,installCommand:a.installCommand,updateCommand:a.updateCommand,busy:!1,lastError:null}}function Wo(t,a){return{provider:t,displayName:a,description:`${a} backend descriptor is not available.`,enabled:!1,isDefault:t===Br,status:{state:"stopped",transport:Wr[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:Fr,installation:La(t)}}function Ta(t){const a=t.installation??La(t.provider);return{...t,installation:{...La(t.provider),...a}}}const pt=[...Do.map(t=>Wo(t,Wr[t].displayName))];function Fo(t){var a;return((a=pt.find(s=>s.provider===t))==null?void 0:a.managementSchema)??Fr}function qo(t){const a=new Date(t);return Number.isNaN(a.getTime())?t:a.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function zo(t){const a=t.payload.details,s=typeof(a==null?void 0:a.stderr)=="string"&&a.stderr.trim()?a.stderr.trim():typeof(a==null?void 0:a.stdout)=="string"&&a.stdout.trim()?a.stdout.trim():null;return s?`${t.message}
2
+ ${s}`:t.message}function jt(t){return{path:t,exists:!1,originalContent:"",draftContent:"",loading:!1,saving:!1,error:null,saveMessage:null}}const Vo=/^\/devices\/([^/]+)(?:\/|$)/,Go=/^(?:\/devices\/[^/]+)?\/threads\/([^/?#]+)(?:[/?#]|$)/;function qr(t){const a=Vo.exec(t);return a?decodeURIComponent(a[1]??""):null}function Ve(){return typeof window>"u"?null:qr(window.location.pathname)}function Jo(t){const a=Go.exec(t);return a?decodeURIComponent(a[1]??""):null}function Ko(){return typeof window>"u"?null:Jo(window.location.pathname)}function Pt(t,a){if(!a)return t;const s=t.startsWith("/")?t:`/${t}`;return`/devices/${encodeURIComponent(a)}${s}`}function Ua(t){return Pt(t,Ve())}function Wa(t,a){return Pt(`/threads/${encodeURIComponent(t)}`,a)}function Ue(t){return Wa(t,Ve())}function Yo(t,a){const s=t?`?workspaceId=${encodeURIComponent(t)}`:"";return Pt(`/threads${s}`,a)}function Et(t){return Yo(t,Ve())}function Zo(t,a){const s=t?`?workspaceId=${encodeURIComponent(t)}`:"";return Pt(`/threads/new${s}`,a)}function aa(t){return Zo(t,Ve())}function Fa(t){return Pt("/workspaces",t)}function Ot(){return Fa(Ve())}class te extends Error{constructor(a,s){super(s.message),this.statusCode=a,this.payload=s}}const Da="remote-codex-auth-token",$a="remote-codex-relay-token",Ma="remote-codex-relay-admin-token",zr="remote-codex-relay-mode",Ha="remote-codex-relay-device-id",_a="remote-codex-relay-thread-id";function Vr(){return typeof window>"u"?null:window.localStorage.getItem(Da)}function Xo(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(Da,t);return}window.localStorage.removeItem(Da)}}function Gr(){return typeof window>"u"?null:window.localStorage.getItem($a)}function Qo(){return typeof window>"u"?null:window.localStorage.getItem(Ma)}function qa(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem($a,t);return}window.localStorage.removeItem($a)}}function Jr(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(Ma,t);return}window.localStorage.removeItem(Ma)}}function xt(){var t;return typeof window>"u"?!1:((t=window.__REMOTE_CODEX_BOOTSTRAP__)==null?void 0:t.mode)==="relay"||window.location.pathname.startsWith("/relay-portal")||window.location.pathname.startsWith("/relay-admin")||window.location.search.includes("relay=1")||window.localStorage.getItem(zr)==="true"}function Xe(){typeof window>"u"||window.localStorage.setItem(zr,"true")}function rt(){return xt()}function Kr(){return typeof window>"u"?null:Ve()??window.localStorage.getItem(Ha)}function It(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(Ha,t);return}window.localStorage.removeItem(Ha)}}function el(){return typeof window>"u"?null:Ko()??window.localStorage.getItem(_a)}function At(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(_a,t);return}window.localStorage.removeItem(_a)}}function za(t){if(!xt())return t;if(t.startsWith("/api/")){const a=Kr();return a?`/relay/devices/${encodeURIComponent(a)}${t}`:`/relay${t}`}return t}function Yr(t){return za(t)}function tl(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 al(t,a){const s=a==null?void 0:a.trim(),r=s?`${t} ${s}`:`${t}`;return t===429?`Too many requests (${r}).`:t===503?`Upstream service unavailable (${r}).`:`Request failed (${r}).`}function ut(t,a,s){const r=typeof(a==null?void 0:a.message)=="string"&&a.message.trim()?a.message.trim():s,l=a!=null&&a.details&&typeof a.details=="object"?a.details:void 0;return{code:(a==null?void 0:a.code)??tl(t.status),message:r,...l?{details:l}:{}}}async function Zr(t){var l,o;const a=al(t.status,t.statusText),s=((o=(l=t.headers)==null?void 0:l.get)==null?void 0:o.call(l,"content-type"))??"",r=async()=>ut(t,await t.json(),a);if(s.includes("application/json"))try{return await r()}catch{return ut(t,null,a)}try{if(typeof t.text!="function")try{return await r()}catch{return ut(t,null,a)}const i=(await t.text()).trim();if(i.startsWith("{"))try{return ut(t,JSON.parse(i),a)}catch{}return ut(t,i?{message:`${a}
3
+ ${i}`}:null,a)}catch{try{return await r()}catch{return ut(t,null,a)}}}async function R(t,a,s={}){const r=new Headers(a==null?void 0:a.headers);(a==null?void 0:a.body)!==void 0&&!(a.body instanceof FormData)&&!r.has("Content-Type")&&r.set("Content-Type","application/json");const l=await fetch(za(String(t)),Qr({...a,headers:r},s.auth));if(!l.ok){const o=await Zr(l);throw new te(l.status,o)}return await l.json()}function sl(t){const a=String(t);return a.includes("/exports/pdf")?a.includes("format=html")?"remote-codex-transcript.html":"remote-codex-transcript.pdf":"download"}function rl(t){var l;if(!t)return null;const a=t.match(/filename\*=UTF-8''([^;]+)/i);if(a!=null&&a[1])try{return decodeURIComponent(a[1].trim())}catch{return a[1].trim()}const s=t.match(/filename="([^"]+)"/i);if(s!=null&&s[1])return s[1].trim();const r=t.match(/filename=([^;]+)/i);return((l=r==null?void 0:r[1])==null?void 0:l.trim())??null}async function Xr(t,a){const s=await fetch(za(String(t)),Qr(a));if(!s.ok){const l=await Zr(s);throw new te(s.status,l)}const r=rl(s.headers.get("content-disposition"))??sl(t);return{blob:await s.blob(),filename:r}}function Qr(t={},a="default"){const s=new Headers(t.headers),r=xt();if(a!=="none"&&!s.has("Authorization"))if(a==="relay-admin"){const l=Qo();l&&s.set("Authorization",`Bearer ${l}`)}else{const l=Gr(),o=Vr();r&&l?s.set("Authorization",`Bearer ${l}`):!r&&o&&s.set("Authorization",`Bearer ${o}`)}return{...t,credentials:t.credentials??(r?"omit":"same-origin"),headers:s}}function lr(t,a){const s=t.originalName.trim();if(s)return s;const r=t.file.name.trim();return r||(t.kind==="photo"?`photo-${a+1}.jpg`:`file-${a+1}`)}function nl(){return R("/api/config/runtime")}function ol(){return R("/api/auth/session",{cache:"no-store"})}async function ll(t){const a=await R("/api/auth/login",{method:"POST",body:JSON.stringify(t)});return Xo(a.token??null),a}function Rt(){return R("/relay/auth/session",{cache:"no-store"})}async function il(t){Xe();const a=await R("/relay/auth/login",{method:"POST",body:JSON.stringify(t)},{auth:"none"});return qa(a.token),a}function en(){return Xe(),R("/relay/auth/session",{cache:"no-store"},{auth:"relay-admin"})}async function dl(t){Xe();const a=await R("/relay/auth/login",{method:"POST",body:JSON.stringify({identifier:t.username,password:t.password})},{auth:"none"});return Jr(a.token),a}async function cl(){return Jr(null),en()}async function ul(t){Xe();const a=await R("/relay/auth/register",{method:"POST",body:JSON.stringify(t)},{auth:"none"});return qa(a.token??null),a}async function tn(){const t=await R("/relay/auth/logout",{method:"POST"});return qa(null),It(null),At(null),t}function Va(){return R("/relay/portal")}function ml(t){const a=new URLSearchParams({deviceId:t.deviceId});return t.threadId&&a.set("threadId",t.threadId),t.workspaceId&&a.set("workspaceId",t.workspaceId),R(`/relay/access?${a.toString()}`)}function an(t){return R("/relay/devices",{method:"POST",body:JSON.stringify(t)})}function sn(t){return R(`/relay/devices/${encodeURIComponent(t)}`,{method:"DELETE"})}function hl(t){return R("/relay/account",{method:"PATCH",body:JSON.stringify(t)})}function pl(t){return R("/relay/account/password",{method:"PATCH",body:JSON.stringify(t)})}function fl(t){return R("/relay/shares",{method:"POST",body:JSON.stringify(t)})}function rn(t,a){return R(`/relay/shares/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(a)})}function Ga(t){return R(`/relay/shares/${encodeURIComponent(t)}`,{method:"DELETE"})}function xl(t){const a=t?`?days=${encodeURIComponent(String(t))}`:"";return R(`/relay/admin${a}`,void 0,{auth:"relay-admin"})}function gl(t){return R("/relay/admin/settings/registration",{method:"PATCH",body:JSON.stringify(t)},{auth:"relay-admin"})}function bl(t,a){return R(`/relay/admin/users/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({enabled:a})},{auth:"relay-admin"})}function vl(t){return R(`/relay/admin/users/${encodeURIComponent(t)}`,{method:"DELETE"},{auth:"relay-admin"})}function yl(t,a){return R(`/relay/admin/users/${encodeURIComponent(t)}/reset-password`,{method:"POST",body:JSON.stringify({password:a})},{auth:"relay-admin"})}function wl(t){return R(`/relay/admin/registrations/${encodeURIComponent(t)}/approve`,{method:"POST"},{auth:"relay-admin"})}function jl(t){return R(`/relay/admin/registrations/${encodeURIComponent(t)}/reject`,{method:"POST"},{auth:"relay-admin"})}function Nl(){return R("/api/config/workspace-settings",{cache:"no-store"})}function kl(t){return R("/api/config/workspace-settings",{method:"PATCH",body:JSON.stringify(t)})}function sa(){return R("/api/agent-runtimes",{cache:"no-store"})}function nn(t){return R(`/api/agent-runtimes/${encodeURIComponent(t)}/status`,{cache:"no-store"})}function Sl(t){return R(`/api/agent-runtimes/${encodeURIComponent(t)}/restart`,{method:"POST"})}function on(t,a){return R(`/api/agent-runtimes/${encodeURIComponent(t)}/install`,{method:"POST",body:JSON.stringify({action:a})})}function ea(t){return R(`/api/agent-runtimes/${encodeURIComponent(t)}/models`,{cache:"no-store"})}function ln(t,a){return R(`/api/config/providers/${encodeURIComponent(t)}/files/${encodeURIComponent(a)}`,{cache:"no-store"})}function dn(t,a,s){return R(`/api/config/providers/${encodeURIComponent(t)}/files/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify(s)})}function Cl(t){return R(`/api/config/providers/${encodeURIComponent(t)}/archives`,{cache:"no-store"})}function Tl(t,a={}){return R(`/api/config/providers/${encodeURIComponent(t)}/archives`,{method:"POST",body:JSON.stringify(a)})}function El(t,a,s){return R(`/api/config/providers/${encodeURIComponent(t)}/archives/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify(s)})}function Il(t,a){return R(`/api/config/providers/${encodeURIComponent(t)}/archives/${encodeURIComponent(a)}/apply`,{method:"POST"})}function Al(){return R("/api/service/build-restart",{method:"POST"})}function Rl(){return R("/healthz",{cache:"no-store"})}function Ja(){return R("/api/workspaces")}function Pl(t,a={}){const s=new URLSearchParams;a.path&&s.set("path",a.path);const r=s.size>0?`?${s.toString()}`:"";return R(`/api/workspaces/${encodeURIComponent(t)}/files/tree${r}`,{cache:"no-store"})}function Ol(t,a){const s=new URLSearchParams({path:a.path});return a.offset!==void 0&&s.set("offset",String(a.offset)),a.limit!==void 0&&s.set("limit",String(a.limit)),R(`/api/workspaces/${encodeURIComponent(t)}/files/preview?${s.toString()}`,{cache:"no-store"})}function Ll(t,a){const s=new URLSearchParams({path:a.path});return Yr(`/api/workspaces/${encodeURIComponent(t)}/files/raw?${s.toString()}`)}function Ul(t,a){const s=new URLSearchParams({path:a.path});return Yr(`/api/threads/${encodeURIComponent(t)}/assets/image?${s.toString()}`)}function Dl(t,a){const s=new URLSearchParams({path:a.path});return Xr(`/api/workspaces/${encodeURIComponent(t)}/files/download?${s.toString()}`,{cache:"no-store"})}function $l(t,a){const s=new FormData;return s.append("file",a.file,a.file.name),R(`/api/workspaces/${encodeURIComponent(t)}/files/upload`,{method:"POST",body:s})}function Ml(t,a){return R(`/api/workspaces/${encodeURIComponent(t)}/files`,{method:"PUT",body:JSON.stringify(a)})}function Ka(){return R("/api/threads")}function ir(t,a={}){const s=new URLSearchParams;return a.limit!==void 0&&s.set("limit",String(a.limit)),a.beforeTurnId&&s.set("beforeTurnId",a.beforeTurnId),R(`/api/threads/${t}${s.size>0?`?${s.toString()}`:""}`)}function Hl(t,a){return R(`/api/threads/${t}/items/${encodeURIComponent(a)}/detail`)}function _l(){return R("/api/plugins",{cache:"no-store"})}function Bl(t){return R("/api/plugins/import",{method:"POST",body:JSON.stringify(t)})}function Wl(t,a){return R(`/api/plugins/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(a)})}function Fl(t){return R(`/api/plugins/${encodeURIComponent(t)}`,{method:"DELETE"})}function ql(t){return R(`/api/threads/${t}/export-turns`,{cache:"no-store"})}function zl(t,a){var r,l,o;const s=new URLSearchParams;return a.format!==void 0&&s.set("format",a.format),s.set("mode",a.mode),a.limit!==void 0&&s.set("limit",String(a.limit)),a.turnIds!==void 0&&s.set("turnIds",a.turnIds.join(",")),a.profile!==void 0&&s.set("profile",a.profile),((r=a.options)==null?void 0:r.includeTokenAndPrice)!==void 0&&s.set("includeTokenAndPrice",String(a.options.includeTokenAndPrice)),((l=a.options)==null?void 0:l.includeCommandOutput)!==void 0&&s.set("includeCommandOutput",String(a.options.includeCommandOutput)),((o=a.options)==null?void 0:o.includeAbsolutePaths)!==void 0&&s.set("includeAbsolutePaths",String(a.options.includeAbsolutePaths)),`/api/threads/${encodeURIComponent(t)}/exports/pdf?${s.toString()}`}function Vl(t,a){return Xr(zl(t,a),{cache:"no-store"})}function Gl(t){return R(`/api/threads/${t}/shell`)}function Jl(t){return R("/api/threads/start",{method:"POST",body:JSON.stringify(t)})}function Kl(t){return R("/api/threads/import",{method:"POST",body:JSON.stringify(typeof t=="string"?{sessionId:t}:t)})}function Yl(t,a={}){return R(`/api/threads/${t}/shell`,{method:"POST",...Object.keys(a).length>0?{body:JSON.stringify(a)}:{}})}function Zl(t){return R(`/api/shells/${t}/terminate`,{method:"POST"})}function Xl(t,a){return R(`/api/shells/${t}`,{method:"PATCH",body:JSON.stringify(a)})}function dr(t,a={}){return R(`/api/threads/${t}/resume`,{method:"POST",...Object.keys(a).length>0?{body:JSON.stringify(a)}:{}})}function Ql(t){return R(`/api/threads/${t}/disconnect`,{method:"POST"})}function ei(t,a){const s=a.attachments??[];if(s.length===0)return R(`/api/threads/${t}/prompt`,{method:"POST",body:JSON.stringify(a)});const r=new FormData;r.append("prompt",a.prompt),a.clientRequestId!==void 0&&r.append("clientRequestId",a.clientRequestId),a.model!==void 0&&r.append("model",a.model),a.reasoningEffort!==void 0&&a.reasoningEffort!==null&&r.append("reasoningEffort",a.reasoningEffort),a.collaborationMode!==void 0&&r.append("collaborationMode",a.collaborationMode);const l=s.map((o,i)=>({clientId:o.clientId,kind:o.kind,originalName:lr(o,i),placeholder:o.placeholder}));r.append("attachmentManifest",JSON.stringify(l));for(const[o,i]of s.entries())r.append("attachments",i.file,lr(i,o));return R(`/api/threads/${t}/prompt`,{method:"POST",body:r})}function cr(t,a={}){return R(`/api/threads/${t}/interrupt`,{method:"POST",body:JSON.stringify(a)})}function cn(t,a){return R(`/api/threads/${t}`,{method:"PATCH",body:JSON.stringify(a)})}function un(t){return R(`/api/threads/${t}`,{method:"DELETE"})}function ti(t,a){return R(`/api/threads/${t}/pending-steers/${encodeURIComponent(a)}`,{method:"DELETE"})}function ai(t,a){return R(`/api/threads/${t}/settings`,{method:"PATCH",body:JSON.stringify(a)})}function si(t){return R(`/api/threads/${t}/compact`,{method:"POST"})}function ri(t){return R(`/api/threads/${t}/goal`,{cache:"no-store"})}function ni(t,a){return R(`/api/threads/${t}/goal`,{method:"PATCH",body:JSON.stringify(a)})}function oi(t){return R(`/api/threads/${t}/goal`,{method:"DELETE"})}function li(t){return R(`/api/threads/${t}/fork-turns`,{cache:"no-store"})}function ur(t,a){return R(`/api/threads/${t}/fork`,{method:"POST",body:JSON.stringify(a)})}function ii(t){return R(`/api/threads/${t}/skills`,{cache:"no-store"})}function di(t){return R(`/api/threads/${t}/mcp-servers`,{cache:"no-store"})}function ci(t){return R(`/api/threads/${t}/hooks`,{cache:"no-store"})}function ui(t,a){return R(`/api/threads/${t}/hooks`,{method:"POST",body:JSON.stringify(a)})}function mi(t,a){return R(`/api/threads/${t}/hooks`,{method:"PUT",body:JSON.stringify(a)})}function hi(t,a){return R(`/api/threads/${t}/hooks/trust`,{method:"POST",body:JSON.stringify(a)})}function pi(t,a){return R(`/api/threads/${t}/hooks/untrust`,{method:"POST",body:JSON.stringify(a)})}function fi(t,a,s){return R(`/api/threads/${t}/requests/${encodeURIComponent(a)}/respond`,{method:"POST",body:JSON.stringify(s)})}function xi(t){return R("/api/workspaces",{method:"POST",body:JSON.stringify(t)})}function gi(t,a){return R(`/api/workspaces/${t}`,{method:"PATCH",body:JSON.stringify(a)})}function bi(t,a){return R(`/api/workspaces/${t}`,{method:"DELETE",body:JSON.stringify(a)})}function vi(t,a){return R(`/api/workspaces/${t}/favorite`,{method:"POST",body:JSON.stringify(a)})}function mn(t){const a=window.location.protocol==="https:"?"wss:":"ws:",s=new WebSocket(hn(a));return s.addEventListener("message",r=>{try{const l=JSON.parse(r.data);wi(l)&&t(l)}catch{}}),s}function yi(t={}){const a=window.location.protocol==="https:"?"wss:":"ws:",s=new WebSocket(hn(a));return s.addEventListener("message",r=>{var l,o;try{const i=JSON.parse(r.data);if(i.type==="supervisor.connected"){(l=t.onConnected)==null||l.call(t,i);return}ji(i)&&((o=t.onShellEvent)==null||o.call(t,i))}catch{}}),{socket:s,send(r){s.send(JSON.stringify(r))}}}function hn(t){const a=new URL(`${t}//${window.location.host}/ws`);if(xt()){const o=Kr();a.pathname=o?`/relay/devices/${encodeURIComponent(o)}/ws`:"/relay/ws"}const s=Vr(),r=Gr(),l=el();return xt()&&r&&a.searchParams.set("relaySession",r),xt()&&l&&a.searchParams.set("threadId",l),s&&a.searchParams.set("token",s),a.toString()}function wi(t){return"threadId"in t&&t.type.startsWith("thread.")&&typeof t.payload=="object"&&t.payload!==null}function ji(t){return"shellId"in t&&t.type.startsWith("shell.")&&typeof t.payload=="object"&&t.payload!==null}function Ya({embedded:t=!1}={}){const a=ot(),s=_r(),[r,l]=n.useState(""),[o,i]=n.useState({busy:!1,message:null,error:null}),[d,f]=n.useState(!1),[g,C]=n.useState(null),[h,S]=n.useState({}),k=g?h[g]:null,[p,v]=n.useState({busy:!1,message:null,error:null}),[q,_]=n.useState([]),[D,L]=n.useState(pt),[E,z]=n.useState({loading:!1,saving:!1,error:null,operatingProvider:null,operatingAction:null,message:null}),[Q,c]=n.useState(null),[P,K]=n.useState({devHomeDraft:"",loading:!1,saving:!1,message:null,error:null}),[m,H]=n.useState({loading:!1,creating:!1,applyingId:null,renamingId:null,renameDraft:"",message:null,error:null}),I=(a==null?void 0:a.themeMode)??"system",X=t||!!(a!=null&&a.settingsOpen);async function he(){const x=r.trim();if(!(!x||o.busy)){i({busy:!0,message:null,error:null});try{await s.importPluginManifest({manifestJson:x,enabled:!0}),l(""),i({busy:!1,message:"Plugin manifest imported.",error:null})}catch(w){i({busy:!1,message:null,error:w instanceof Error?w.message:"Unable to import plugin manifest."})}}}const pe=(a==null?void 0:a.effectiveTheme)??"dark",B=(a==null?void 0:a.autoCollapseCompletedTurns)??!0,J=(a==null?void 0:a.defaultBackend)??Br,ue=s.plugins.filter(x=>x.enabled).length,Y=s.loading?"Loading...":`${ue}/${s.plugins.length} enabled`,G=D.find(x=>x.provider===J)??pt.find(x=>x.provider===J)??pt[0],me=G.managementSchema??Fo(G.provider),de=me.hostConfigFiles;n.useEffect(()=>{if(!X||t||!a||!me.configArchives)return;const x=a;function w(M){M.key==="Escape"&&x.closeSettings()}return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[me.configArchives,t,X,a]),n.useEffect(()=>{if(!X)return;let x=!1;return z(w=>({...w,loading:!0,error:null})),sa().then(w=>{if(x)return;const M=[...w.map(Ta),...pt.filter(V=>!w.some(fe=>fe.provider===V.provider))];L(M),z(V=>({...V,loading:!1}))}).catch(w=>{x||(L(pt),z(M=>({...M,loading:!1,error:w instanceof te?w.message:"Unable to load backend settings."})))}),()=>{x=!0}},[X]),n.useEffect(()=>{if(!X)return;let x=!1;return K(w=>({...w,loading:!0,message:null,error:null})),Nl().then(w=>{x||(c(w),K(M=>({...M,devHomeDraft:w.devHome,loading:!1})))}).catch(w=>{x||K(M=>({...M,loading:!1,error:w instanceof te?w.message:"Unable to load workspace settings."}))}),()=>{x=!0}},[X]),n.useEffect(()=>{if(!X||!G.capabilities.management.hostConfigFiles)return;let x=!1;async function w(){S(V=>{const fe={...V};for(const Re of de)fe[Re.name]={...jt(Re.name),...V[Re.name],loading:!0,saving:!1,error:null,saveMessage:null};return fe});const M=await Promise.allSettled(de.map(async V=>({name:V.name,result:await ln(G.provider,V.name)})));x||S(V=>{var Re,Qe;const fe={...V};for(const Je of M){if(Je.status==="fulfilled"){const{name:lt,result:tt}=Je.value;fe[lt]={path:tt.path,exists:tt.exists,originalContent:tt.content,draftContent:tt.content,loading:!1,saving:!1,error:null,saveMessage:null};continue}const Lt=Je.reason instanceof te?Je.reason.message:"Unable to load the file.",et=((Re=de[M.indexOf(Je)])==null?void 0:Re.name)??((Qe=de[0])==null?void 0:Qe.name);et&&(fe[et]={...jt(et),...fe[et],loading:!1,saving:!1,error:Lt,saveMessage:null})}return fe})}return w(),()=>{x=!0}},[G.capabilities.management.hostConfigFiles,G.provider,de,X]),n.useEffect(()=>{if(!X)return;let x=!1;async function w(){H(M=>({...M,loading:!0,error:null,message:null}));try{const M=await Cl(G.provider);if(x)return;_(M),H(V=>({...V,loading:!1}))}catch(M){if(x)return;H(V=>({...V,loading:!1,error:M instanceof te?M.message:"Unable to load config archives."}))}}return w(),()=>{x=!0}},[G.provider,me.configArchives,X]);async function Ce(){if(!(p.busy||E.saving)){v({busy:!0,message:null,error:null});try{const x=await Sl(G.provider),w=Ta(x);v({busy:!1,message:w.status.state==="ready"?`${w.displayName} backend restarted.`:`${w.displayName} backend state: ${w.status.state}`,error:null}),L(M=>M.map(V=>V.provider===w.provider?w:V))}catch(x){v({busy:!1,message:null,error:x instanceof te?x.message:"Unable to restart the app server."})}}}async function U(x,w){if(p.busy||E.saving)return;const M=D.find(V=>V.provider===x);z(V=>({...V,saving:!0,operatingProvider:x,operatingAction:w,message:null,error:null}));try{const V=await on(x,w),fe=Ta(V);L(Re=>Re.map(Qe=>Qe.provider===fe.provider?fe:Qe)),z(Re=>({...Re,saving:!1,operatingProvider:null,operatingAction:null,message:fe.installation.lastError?`${fe.displayName} ${w==="install"?"installed":"updated"}, but requires attention:
4
+ ${fe.installation.lastError}`:`${fe.displayName} ${w==="install"?"installed":"updated"}.`,error:null}))}catch(V){z(fe=>({...fe,saving:!1,operatingProvider:null,operatingAction:null,message:null,error:V instanceof te?zo(V):`Unable to ${w} ${(M==null?void 0:M.displayName)??x}.`}))}}async function ee(){if(!(p.busy||E.saving)){v({busy:!0,message:null,error:null});try{await Al(),v({busy:!1,message:"Build and restart launched. The page may disconnect briefly.",error:null})}catch(x){v({busy:!1,message:null,error:x instanceof te?x.message:"Unable to launch build and restart."})}}}async function ve(){const x=P.devHomeDraft.trim();if(!(!x||P.saving)){K(w=>({...w,saving:!0,message:null,error:null}));try{const w=await kl({devHome:x});c(w),K(M=>({...M,devHomeDraft:w.devHome,saving:!1,message:"Workspace defaults saved."}))}catch(w){K(M=>({...M,saving:!1,error:w instanceof te?w.message:"Unable to save workspace settings."}))}}}async function ke(x){const w=h[x];if(!(!w||w.saving)){S(M=>({...M,[x]:{...jt(x),...M[x],saving:!0,error:null,saveMessage:null}}));try{const M=await dn(G.provider,x,{content:w.draftContent});S(V=>({...V,[x]:{path:M.path,exists:M.exists,originalContent:M.content,draftContent:M.content,loading:!1,saving:!1,error:null,saveMessage:"Saved"}}))}catch(M){S(V=>({...V,[x]:{...jt(x),...V[x],saving:!1,error:M instanceof te?M.message:"Unable to save the file.",saveMessage:null}}))}}}async function we(){if(!m.creating){H(x=>({...x,creating:!0,message:null,error:null}));try{const x=await Tl(G.provider);_(w=>[x,...w]),H(w=>({...w,creating:!1,message:"Backup created."}))}catch(x){H(w=>({...w,creating:!1,error:x instanceof te?x.message:"Unable to create a config backup."}))}}}async function A(x){if(!m.applyingId){H(w=>({...w,applyingId:x.id,message:null,error:null}));try{const w=await Il(G.provider,x.id);H(M=>({...M,applyingId:null,message:w.status.state==="ready"?`Applied "${w.archive.label}" and restarted ${G.displayName}.`:`Applied "${w.archive.label}". ${G.displayName} state: ${w.status.state}.`}))}catch(w){H(M=>({...M,applyingId:null,error:w instanceof te?w.message:"Unable to apply the config archive."}))}}}async function T(x){const w=m.renameDraft.trim();if(!(!w||m.renamingId!==x.id)){H(M=>({...M,message:null,error:null}));try{const M=await El(G.provider,x.id,{label:w});_(V=>V.map(fe=>fe.id===x.id?M:fe)),H(V=>({...V,renamingId:null,renameDraft:"",message:"Backup renamed."}))}catch(M){H(V=>({...V,error:M instanceof te?M.message:"Unable to rename the config backup."}))}}}if(!X)return null;const ae=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-3 grid gap-2",children:[s.plugins.map(x=>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:x.name}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-[var(--theme-fg-muted)]",children:x.description}),e.jsx("span",{className:"mt-2 block text-[10px] uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:[...x.capabilities.artifactTypes.map(w=>w.type),...x.capabilities.threadPanels.map(w=>w.kind??w.id)].join(", ")||"utility"}),e.jsx("span",{className:"mt-1 block text-[10px] uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:x.source==="imported"?"Imported manifest":"Built-in module"})]}),e.jsx("input",{type:"checkbox",checked:x.enabled,onChange:w=>void s.setPluginEnabled(x.id,w.currentTarget.checked),className:"mt-1 h-4 w-4 shrink-0 accent-[var(--theme-accent-solid)]"})]},x.id)),s.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:x=>{l(x.currentTarget.value),(o.message||o.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 he(),disabled:!r.trim()||o.busy,className:"rounded-full border border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] px-3 py-1.5 text-xs font-medium text-[var(--theme-accent-strong)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:border-[var(--theme-border)] disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:o.busy?"Importing...":"Import"})]}),o.error&&e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:o.error}),o.message&&e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:o.message})]}),s.error&&e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:s.error})]}),Oe=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:a==null?void 0:a.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(Qt,{})})]})}),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:"," ",pe,"."]})]})}),e.jsx("div",{className:"mt-3 grid gap-2 sm:grid-cols-3",children:_o.map(x=>{const w=I===x.value;return e.jsxs("button",{type:"button",onClick:()=>a==null?void 0:a.setThemeMode(x.value),className:`block rounded-[1rem] border px-3 py-2.5 text-left transition ${w?"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:x.label}),w?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:x.description})]},x.value)})})]}),a!=null&&a.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:B,onChange:x=>{var w;return(w=a.setAutoCollapseCompletedTurns)==null?void 0:w.call(a,x.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 s.refresh(),disabled:s.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:s.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:Y}),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"})]}):ae]}),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:(Q==null?void 0:Q.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:P.loading&&!Q?"Loading...":(Q==null?void 0:Q.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:P.devHomeDraft,onChange:x=>K(w=>({...w,devHomeDraft:x.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 ve(),disabled:P.loading||P.saving||!P.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:P.saving?"Saving...":"Save"})]})]})]}),P.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:P.error}):P.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:P.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 Ce(),disabled:p.busy||E.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:p.busy?"Restarting...":"Restart"}),e.jsx("button",{type:"button",onClick:()=>void ee(),disabled:p.busy||E.saving,className:"rounded-full border border-amber-400/35 bg-amber-400/10 px-3 py-1.5 text-xs font-medium text-amber-500 transition hover:bg-amber-400/16 disabled:cursor-not-allowed disabled:border-[var(--theme-border)] disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:p.busy?"Working...":"Build and restart"})]})]}),e.jsx("div",{className:"mt-3 grid gap-2",children:D.map(x=>{const w=x.installation,M=!w.installed&&!!w.installCommand,V=w.installed&&!!w.updateCommand,fe=E.saving&&E.operatingProvider===x.provider,Re=M?"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:x.displayName}),e.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${x.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:x.enabled?"Ready":w.installed?x.status.state:"Not installed"})]}),e.jsxs("p",{className:"mt-1 truncate text-xs text-[var(--theme-fg-muted)]",children:["Version:"," ",w.installedVersion??(w.installed?"Installed":"Unavailable"),w.latestVersion?` · Latest: ${w.latestVersion}`:""]}),w.lastError?e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-rose-300",children:w.lastError}):null]}),M||V?e.jsx("button",{type:"button","aria-label":`${M?"Install":"Update"} ${x.displayName}`,onClick:()=>void U(x.provider,M?"install":"update"),disabled:p.busy||E.saving||!M&&!V,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:fe?E.operatingAction==="install"?"Installing...":"Updating...":Re}):null]},x.provider)})}),p.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:p.error}):p.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:p.message}):E.message?e.jsx("p",{className:`mt-2 whitespace-pre-line text-xs ${E.message.includes("requires attention")?"text-amber-300":"text-emerald-300"}`,children:E.message}):E.error?e.jsx("p",{className:"mt-2 whitespace-pre-line text-xs text-rose-300",children:E.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:[G.displayName," exposes these editable files through its backend schema."]})]})}),e.jsxs("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[de.map(x=>{const w=h[x.name]??{path:x.name,exists:!1,originalContent:"",draftContent:"",loading:!1},M=w.draftContent!==w.originalContent;return e.jsx("button",{type:"button",onClick:()=>C(x.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:x.label}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:x.description})]}),e.jsx("div",{className:"shrink-0",children:w.loading?e.jsx("span",{className:"text-[11px] uppercase tracking-[0.2em] text-[var(--theme-fg-muted)]",children:"Loading"}):M?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"}):w.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"})})]})},x.name)}),de.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]})]}),me.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 we(),disabled:m.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:m.creating?"Creating...":"Create backup"})]}),m.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:m.error}):m.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:m.message}):null,e.jsx("div",{className:"mt-3 space-y-2",children:m.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..."}):q.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."}):q.map(x=>{const w=m.renamingId===x.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:[w?e.jsxs("div",{className:"flex max-w-xl gap-2",children:[e.jsx("input",{"aria-label":`Rename ${x.label}`,value:m.renameDraft,onChange:M=>H(V=>({...V,renameDraft:M.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 ${x.label}`,onClick:()=>void T(x),className:"rounded-full bg-[var(--theme-accent-solid)] px-3 py-1.5 text-xs font-medium text-[var(--theme-accent-solid-fg)] transition hover:bg-[var(--theme-accent-solid-hover)]",children:"Save"}),e.jsx("button",{type:"button",onClick:()=>H(M=>({...M,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:x.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 ",qo(x.createdAt)]}),de.map(M=>{var V;return e.jsxs("span",{className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-2 py-0.5 font-mono",children:[M.name,":"," ",(V=x.files[M.name])!=null&&V.exists?"saved":"missing"]},M.name)})]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:()=>H(M=>({...M,renamingId:x.id,renameDraft:x.label,message:null,error:null})),disabled:w,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 A(x),disabled:m.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:m.applyingId===x.id?"Applying...":"Apply"})]})]})},x.id)})})]}):null]})})]});return t?e.jsxs("div",{className:"flex min-h-0 flex-col overflow-hidden",children:[Oe,d?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:"absolute inset-0 bg-black/35 backdrop-blur-[2px]"}),e.jsxs("section",{className:"relative z-10 flex max-h-[min(82vh,42rem)] w-full max-w-2xl flex-col overflow-hidden rounded-[1.35rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] shadow-2xl shadow-black/25",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-[var(--theme-border)] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Plugins"}),e.jsx("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:Y})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>void s.refresh(),disabled:s.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:s.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(Qt,{})})]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-4",children:ae})]})]}):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:a==null?void 0:a.closeSettings,className:"ui-overlay-scrim absolute inset-0 backdrop-blur-sm"}),e.jsx("section",{role:"dialog","aria-modal":"true","aria-label":"Settings",className:"relative z-10 flex max-h-[calc(100vh-2rem)] w-full max-w-4xl flex-col overflow-hidden rounded-[1.8rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] shadow-2xl shadow-black/20",children:Oe}),g&&k?e.jsx("div",{className:"pointer-events-none fixed inset-0 z-[71] flex items-center justify-center p-4",children:e.jsxs("div",{className:"pointer-events-auto relative z-10 flex max-h-[min(88vh,56rem)] w-full max-w-3xl flex-col overflow-hidden rounded-[1.6rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] shadow-2xl shadow-black/25",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-[var(--theme-border)] px-4 py-3 sm:px-5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:g}),e.jsx("p",{className:"mt-1 break-all font-mono text-xs text-[var(--theme-fg-muted)]",children:k.path})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[k.error?e.jsx("span",{className:"text-xs text-rose-300",children:k.error}):k.saveMessage?e.jsx("span",{className:"text-xs text-emerald-300",children:k.saveMessage}):null,e.jsx("button",{type:"button","aria-label":`Save ${g}`,onClick:()=>void ke(g),disabled:k.loading||k.saving||k.draftContent===k.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:k.saving?"Saving...":"Save"}),e.jsx("button",{type:"button","aria-label":"Close File Editor",onClick:()=>C(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(Qt,{})})]})]}),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:k.draftContent,onChange:x=>S(w=>({...w,[g]:{...jt(g),...w[g],draftContent:x.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:k.loading?"Loading...":`Edit ${g} here`})})]})}):null]})}function pn({className:t=""}){const a=ot();return a?e.jsx("button",{type:"button","aria-label":a.navOpen?"Close Navigation":"Open Navigation","aria-expanded":a.navOpen,"aria-controls":"app-shell-navigation-menu",onClick:a.toggleNav,className:`inline-flex h-10 w-10 shrink-0 items-center justify-center text-[var(--theme-fg)] transition hover:text-[var(--theme-fg-soft)] ${t}`.trim(),children:a.navOpen?e.jsx(Qt,{}):e.jsx(Ho,{})}):null}function fn({className:t=""}){const a=ot(),s=ua(),r=He(),l=n.useRef(null),o=s.pathname==="/workspaces"||/^\/devices\/[^/]+\/workspaces$/.test(s.pathname),i=s.pathname==="/threads/import"||/^\/devices\/[^/]+\/threads\/import$/.test(s.pathname);return n.useEffect(()=>{if(!(a!=null&&a.navOpen))return;const d=a;function f(g){const C=g.target;if(!C)return;const h=l.current;h!=null&&h.contains(C)||C instanceof Element&&C.closest('[aria-controls="app-shell-navigation-menu"]')||d.closeNav()}return document.addEventListener("pointerdown",f),()=>{document.removeEventListener("pointerdown",f)}},[a]),a!=null&&a.navOpen?e.jsxs("div",{ref:l,id:"app-shell-navigation-menu",onPointerDown:d=>{d.stopPropagation()},onMouseDown:d=>{d.stopPropagation()},onTouchStart:d=>{d.stopPropagation()},className:`rounded-[1.8rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4 shadow-2xl shadow-black/15 backdrop-blur ${t}`.trim(),children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-base font-semibold tracking-wide text-[var(--theme-accent-strong)]",children:"Remote Codex"}),e.jsx("p",{className:"mt-1 text-xs uppercase tracking-[0.24em] text-[var(--theme-fg-muted)]",children:"Navigation"})]}),e.jsxs("nav",{className:"mt-4 flex flex-col gap-1.5 text-sm",children:[e.jsx("button",{type:"button",disabled:o,onClick:()=>{o||(a.closeNav(),r(Ot()))},className:Ca(o),children:"Workspaces"}),e.jsx("button",{type:"button",disabled:i,onClick:()=>{i||(a.closeNav(),r(Ua("/threads/import")))},className:Ca(i),children:"Import Session"}),e.jsx("button",{type:"button",onClick:()=>{a.openSettings()},className:Ca(),children:"Settings"})]})]}):null}function Ni(t){const a=(t==null?void 0:t.trim())??"";return a?Array.from(a).slice(0,2).join("").toUpperCase():"??"}function xn(){const t=He(),a=ua(),[s,r]=n.useState(null),[l,o]=n.useState(!1);n.useEffect(()=>{if(!rt())return;let g=!1;return Rt().then(C=>{g||r(C.authenticated?C:null)}).catch(()=>{g||r(null)}),()=>{g=!0}},[a.pathname]),n.useEffect(()=>{o(!1)},[a.pathname]);const i=(s==null?void 0:s.user)??null,d=n.useMemo(()=>Ni(i==null?void 0:i.username),[i==null?void 0:i.username]);if(!rt()||!i)return null;async function f(){await tn(),r(null),t("/relay-portal")}return e.jsxs("div",{className:"fixed right-3 top-[calc(env(safe-area-inset-top)+0.55rem)] z-50",children:[e.jsx("button",{"aria-expanded":l,"aria-haspopup":"menu","aria-label":`Relay account menu for ${i.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(g=>!g),type:"button",children:d}),l?e.jsxs("div",{className:"absolute right-0 mt-2 w-64 overflow-hidden rounded-xl border border-[var(--theme-border)] bg-[var(--theme-panel)] p-1 shadow-xl",role:"menu",children:[e.jsxs("div",{className:"border-b border-[var(--theme-border)] px-3 py-2",children:[e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:i.username}),e.jsx("p",{className:"truncate text-xs text-[var(--theme-fg-muted)]",children:i.email})]}),e.jsxs(ze,{className:"flex items-center gap-2 rounded-lg px-3 py-2 text-sm text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",role:"menuitem",to:"/relay-account",children:[e.jsx(ie.Settings,{className:"h-4 w-4"}),"Account settings"]}),e.jsxs(ze,{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(ie.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 f(),role:"menuitem",type:"button",children:[e.jsx(ie.LogOut,{className:"h-4 w-4"}),"Logout"]})]}):null]})}function gn({eyebrow:t="Supervisor Access",description:a="Use the admin credentials configured on this Remote Codex server.",onLogin:s}){const[r,l]=n.useState(""),[o,i]=n.useState(""),[d,f]=n.useState(null),[g,C]=n.useState(!1);async function h(S){S.preventDefault(),f(null),C(!0);try{await s({username:r,password:o})}catch(k){k instanceof te?f(k.payload.message):f("Unable to sign in.")}finally{C(!1)}}return e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-[var(--app-bg)] px-4 py-8 text-[var(--app-fg)]",children:e.jsxs("section",{className:"w-full max-w-sm rounded-[1.35rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-2xl shadow-[color-mix(in_oklch,var(--app-fg)_14%,transparent)] sm:p-6",children:[e.jsxs("div",{className:"mb-5",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-muted)]",children: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-muted)]",children:a})]}),e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-[var(--theme-fg-soft)]",children:"Username"}),e.jsx("input",{autoComplete:"username",autoFocus:!0,className:"mt-2 h-11 w-full rounded-xl border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 text-sm text-[var(--theme-fg)] outline-none transition focus:border-[var(--theme-accent-solid)] focus:ring-2 focus:ring-[var(--theme-accent-border)]",disabled:g,name:"username",onChange:S=>l(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-xl border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 text-sm text-[var(--theme-fg)] outline-none transition focus:border-[var(--theme-accent-solid)] focus:ring-2 focus:ring-[var(--theme-accent-border)]",disabled:g,name:"password",onChange:S=>i(S.target.value),type:"password",value:o})]}),d&&e.jsx("p",{className:"rounded-xl border border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] px-3 py-2 text-sm text-[var(--status-danger-fg)]",children:d}),e.jsx("button",{className:"h-11 w-full rounded-xl bg-[var(--theme-accent-solid)] px-4 text-sm font-semibold text-[var(--theme-accent-solid-fg)] transition hover:bg-[var(--theme-accent-solid-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--theme-accent-border)] disabled:cursor-not-allowed disabled:opacity-60",disabled:g||!r.trim()||!o,type:"submit",children:g?"Signing in...":"Sign in"})]})]})})}function Ea(t,a){return t instanceof te?t.payload.message:t instanceof Error?t.message:a}function ki(){var K;const[t,a]=n.useState(null),[s,r]=n.useState(""),[l,o]=n.useState(""),[i,d]=n.useState(""),[f,g]=n.useState(""),[C,h]=n.useState(!0),[S,k]=n.useState(!1),[p,v]=n.useState(!1),[q,_]=n.useState(null),[D,L]=n.useState(null),[E,z]=n.useState(!1);async function Q(){var m;h(!0),L(null);try{Xe();const H=await Rt();a(H),r(((m=H.user)==null?void 0:m.username)??"")}catch(H){L(Ea(H,"Unable to load account."))}finally{h(!1)}}n.useEffect(()=>{Q()},[]);async function c(m){m.preventDefault(),k(!0),L(null),_(null);try{const H=await hl({username:s});a(I=>I!=null&&I.authenticated?{...I,user:H}:I),r(H.username),_("Account updated.")}catch(H){L(Ea(H,"Unable to update account."))}finally{k(!1)}}async function P(m){m.preventDefault(),v(!0),L(null),_(null);try{if(i!==f){L("New passwords do not match.");return}await pl({currentPassword:l,newPassword:i}),o(""),d(""),g(""),_("Password changed.")}catch(H){L(Ea(H,"Unable to change password."))}finally{v(!1)}}return e.jsx("main",{className:"min-h-screen bg-[var(--app-bg)] px-4 py-6 text-[var(--app-fg)] sm:px-6",children:e.jsxs("div",{className:"mx-auto w-full max-w-4xl space-y-5 pr-12 sm:pr-0",children:[e.jsxs("header",{className:"border-b border-[var(--theme-border)] pb-5",children:[e.jsx(ze,{className:"text-sm text-[var(--theme-accent-strong)]",to:"/workspaces",children:"Back to workspaces"}),e.jsx("p",{className:"mt-4 text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Account"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:"Account settings"})]}),C?e.jsx("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4 text-sm text-[var(--theme-fg-muted)]",children:"Loading account..."}):t!=null&&t.authenticated?e.jsxs(e.Fragment,{children:[D?e.jsx(mr,{tone:"danger",children:D}):null,q?e.jsx(mr,{tone:"success",children:q}):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:c,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:((K=t.user)==null?void 0:K.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:m=>r(m.target.value),value:s})]}),e.jsxs("button",{className:"relay-button-primary inline-flex h-10 items-center justify-center gap-2",disabled:S||!s.trim(),type:"submit",children:[e.jsx(ie.Save,{className:"h-4 w-4"}),"Save"]})]}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:()=>z(!0),type:"button",children:[E?e.jsx(ie.CheckCircle2,{className:"h-4 w-4"}):e.jsx(ie.MailCheck,{className:"h-4 w-4"}),E?"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:P,children:[e.jsx(Ia,{label:"Current password",value:l,onChange:o}),e.jsx(Ia,{label:"New password",value:i,onChange:d}),e.jsx(Ia,{label:"Confirm password",value:f,onChange:g}),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||i.length<8||!f,type:"submit",children:[e.jsx(ie.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 Ia({label:t,value:a,onChange:s}){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=>s(r.target.value),type:"password",value:a})]})}function mr({tone:t,children:a}){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:a})}function mt(t){return t instanceof te?t.payload.message:t instanceof Error?t.message:"Unable to update relay admin state."}function Si(){const[t,a]=n.useState(null),[s,r]=n.useState(!0),[l,o]=n.useState(null),[i,d]=n.useState(!1),[f,g]=n.useState(null),[C,h]=n.useState("overview"),[S,k]=n.useState(7),[p,v]=n.useState(null);async function q(P=S,K={}){K.showLoading!==!1&&r(!0),o(null);try{Xe();const m=await xl(P);a(m),v(m.settings),k(m.conversationWindowDays),d(!1)}catch(m){m instanceof te&&(m.statusCode===401||m.statusCode===403)?(a(null),d(!0),o(null)):o(mt(m))}finally{r(!1)}}n.useEffect(()=>{q()},[]);const _=n.useMemo(()=>{const P=(t==null?void 0:t.users)??[],K=(t==null?void 0:t.devices)??[];return{users:P.length,enabledUsers:P.filter(m=>m.enabled).length,devices:K.length,onlineDevices:K.filter(m=>m.connected).length,conversations:P.reduce((m,H)=>m+H.conversationCount,0),shares:(t==null?void 0:t.shares.filter(m=>!m.revokedAt).length)??0}},[t]);async function D(P,K){g(P),o(null);try{const m=await bl(P,K);a(H=>fr(H,m))}catch(m){o(mt(m))}finally{g(null)}}async function L(P){g(`delete:${P}`),o(null);try{await vl(P),await q(S,{showLoading:!1})}catch(K){o(mt(K))}finally{g(null)}}async function E(P,K){g(`reset:${P}`),o(null);try{const m=await yl(P,K);a(H=>fr(H,m))}catch(m){o(mt(m))}finally{g(null)}}async function z(P){if(P.preventDefault(),!!p){g("settings"),o(null);try{const K=await gl(p);a(m=>m&&{...m,registrationEnabled:K.registrationEnabled,settings:K.settings}),v(K.settings)}catch(K){o(mt(K))}finally{g(null)}}}async function Q(P,K){g(`${K}:${P}`),o(null);try{K==="approve"?await wl(P):await jl(P),await q(S,{showLoading:!1})}catch(m){o(mt(m))}finally{g(null)}}async function c(P){await dl(P),await q(S)}return i?e.jsx(gn,{description:"Use the relay admin credentials for this server. This does not replace your normal relay account.",eyebrow:"Relay Admin",onLogin:c}):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(Ci,{onLogout:()=>{a(null),d(!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:P=>void q(Number(P.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(ze,{className:"relay-button-secondary",to:"/relay-portal",children:"Portal"}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:()=>void q(S),type:"button",children:[e.jsx(ie.RefreshCw,{className:"h-4 w-4"}),"Refresh"]})]})]}),l?e.jsx("section",{className:"rounded-lg border border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] p-4 text-sm text-[var(--status-danger-fg)]",children:l}):null,s?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(Jt,{icon:e.jsx(ie.Users,{className:"h-5 w-5"}),label:"Users",value:_.users,detail:`${_.enabledUsers} enabled`}),e.jsx(Jt,{icon:e.jsx(ie.Database,{className:"h-5 w-5"}),label:"Devices",value:_.devices,detail:`${_.onlineDevices} online`}),e.jsx(Jt,{icon:e.jsx(ie.Clock3,{className:"h-5 w-5"}),label:`Conversations, ${t.conversationWindowDays}d`,value:_.conversations,detail:"Relay prompt/start events"}),e.jsx(Jt,{icon:e.jsx(ie.Share2,{className:"h-5 w-5"}),label:"Active shares",value:_.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","shares","settings"].map(P=>e.jsx("button",{className:`rounded-md px-3 py-2 text-sm font-medium ${C===P?"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:()=>h(P),type:"button",children:Mi(P)},P))}),C==="overview"?e.jsx(Ti,{summary:t}):null,C==="users"?e.jsx(Ei,{busyKey:f,onDeleteUser:L,onResetPassword:E,onUpdateUser:D,users:t.users}):null,C==="devices"?e.jsx(Ii,{devices:t.devices,users:t.users}):null,C==="shares"?e.jsx(Ai,{shares:t.shares}):null,C==="settings"&&p?e.jsx(Ri,{busy:f==="settings",draft:p,onChange:v,onReviewRegistration:Q,onSave:z,pending:t.pendingRegistrations,reviewBusyKey:f}):null]}):null]})]})}function Jt({icon:t,label:a,value:s,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:a}),e.jsx("p",{className:"mt-1 text-2xl font-semibold text-[var(--theme-fg)]",children:s.toLocaleString()}),e.jsx("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:r})]})]})})}function Ci({onLogout:t}){const[a,s]=n.useState(null),[r,l]=n.useState(!1);n.useEffect(()=>{let d=!1;return en().then(f=>{d||s(f.authenticated?f:null)}).catch(()=>{d||s(null)}),()=>{d=!0}},[]);const o=(a==null?void 0:a.user)??null;if(!o)return null;async function i(){await cl(),s(null),l(!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 ${o.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:()=>l(d=>!d),type:"button",children:Bi(o.username)}),r?e.jsxs("div",{className:"absolute right-0 mt-2 w-64 overflow-hidden rounded-xl border border-[var(--theme-border)] bg-[var(--theme-panel)] p-1 shadow-xl",role:"menu",children:[e.jsxs("div",{className:"border-b border-[var(--theme-border)] px-3 py-2",children:[e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:o.username}),e.jsx("p",{className:"truncate text-xs text-[var(--theme-fg-muted)]",children:o.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(ie.LogOut,{className:"h-4 w-4"}),"Logout admin"]})]}):null]})}function Ti({summary:t}){const a=[...t.users].sort(_i("lastSeenAt")).slice(0,6),s=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(nt,{title:"Recent users",detail:"Last authenticated relay activity.",children:e.jsx("div",{className:"divide-y divide-[var(--theme-border)]",children:a.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:Ge(r.lastSeenAt)}),e.jsxs("p",{children:[r.conversationCount," conversations"]})]})]},r.id))})}),e.jsx(nt,{title:"Online devices",detail:"Devices with an active supervisor tunnel.",children:s.length?e.jsx("div",{className:"space-y-3",children:s.map(r=>e.jsx(Pi,{device:r},r.id))}):e.jsx(ha,{children:"No supervisors are connected."})})]})}function Ei({busyKey:t,onDeleteUser:a,onResetPassword:s,onUpdateUser:r,users:l}){const[o,i]=n.useState(""),[d,f]=n.useState({key:"lastSeenAt",direction:"desc"}),[g,C]=n.useState(null),[h,S]=n.useState(null),k=n.useMemo(()=>{const v=pr(o);return l.filter(q=>v?pr(`${q.username} ${q.email}`).includes(v):!0).sort((q,_)=>Ui(q,_,d))},[o,d,l]);function p(v){f(q=>({key:v,direction:q.key===v&&q.direction==="desc"?"asc":"desc"}))}return e.jsxs(e.Fragment,{children:[e.jsxs(nt,{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(ie.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:v=>i(v.target.value),placeholder:"Search username or email",value:o})]}),e.jsxs("p",{className:"text-sm text-[var(--theme-fg-muted)]",children:[k.length.toLocaleString()," of ",l.length.toLocaleString()," users"]})]}),e.jsxs(Za,{minWidth:"68rem",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx(Nt,{active:d.key==="username",direction:d.direction,onClick:()=>p("username"),children:"User"}),e.jsx(Nt,{active:d.key==="enabled",direction:d.direction,onClick:()=>p("enabled"),children:"Status"}),e.jsx(Nt,{active:d.key==="lastSeenAt",direction:d.direction,onClick:()=>p("lastSeenAt"),children:"Last used"}),e.jsx(Nt,{active:d.key==="conversationCount",direction:d.direction,onClick:()=>p("conversationCount"),children:"Conversations"}),e.jsx(Nt,{active:d.key==="deviceCount",direction:d.direction,onClick:()=>p("deviceCount"),children:"Devices"}),e.jsx(Ae,{children:"Role"}),e.jsx(Ae,{children:"Actions"})]})}),e.jsx("tbody",{children:k.map(v=>e.jsxs("tr",{children:[e.jsxs(Ne,{strong:!0,children:[v.username,e.jsx("div",{className:"text-xs font-normal text-[var(--theme-fg-muted)]",children:v.email})]}),e.jsx(Ne,{children:e.jsx(bn,{active:v.enabled,children:v.enabled?"Enabled":"Disabled"})}),e.jsx(Ne,{children:Ge(v.lastSeenAt)}),e.jsx(Ne,{children:v.conversationCount.toLocaleString()}),e.jsx(Ne,{children:v.deviceCount.toLocaleString()}),e.jsx(Ne,{children:v.role}),e.jsx(Ne,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{className:"relay-button-secondary",disabled:t===v.id||v.role==="admin",onClick:()=>r(v.id,!v.enabled),type:"button",children:v.enabled?"Disable":"Enable"}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",disabled:t===`reset:${v.id}`||v.role==="admin",onClick:()=>C(v),type:"button",children:[e.jsx(ie.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:${v.id}`||v.role==="admin",onClick:()=>S(v),type:"button",children:[e.jsx(ie.Trash2,{className:"h-4 w-4"}),"Delete"]})]})})]},v.id))})]}),k.length?null:e.jsx(ha,{children:"No users match the current search."})]}),g?e.jsx(Oi,{busy:t===`reset:${g.id}`,onClose:()=>C(null),onSubmit:async v=>{await s(g.id,v),C(null)},user:g}):null,h?e.jsx(Li,{busy:t===`delete:${h.id}`,confirmLabel:"Delete user",description:`Delete ${h.username}, their devices, shares, and access history. This cannot be undone.`,onClose:()=>S(null),onConfirm:async()=>{await a(h.id),S(null)},title:"Delete relay user"}):null]})}function Ii({devices:t,users:a}){const[s,r]=n.useState("all"),[l,o]=n.useState("all"),[i,d]=n.useState("all"),[f,g]=n.useState("lastActivity"),[C,h]=n.useState("desc"),S=n.useMemo(()=>a.filter(p=>t.some(v=>v.ownerUserId===p.id)),[t,a]),k=n.useMemo(()=>t.filter(p=>s==="all"||p.ownerUserId===s).filter(p=>l==="all"||(l==="online"?p.connected:!p.connected)).filter(p=>i==="all"||$i(na(p),i)).sort((p,v)=>Di(p,v,f,C)),[i,t,C,s,f,l]);return e.jsxs(nt,{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:p=>r(p.target.value),value:s,children:[e.jsx("option",{value:"all",children:"All users"}),S.map(p=>e.jsx("option",{value:p.id,children:p.username},p.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:p=>o(p.target.value),value:l,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:p=>d(p.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:p=>g(p.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:p=>h(p.target.value),value:C,children:[e.jsx("option",{value:"desc",children:"Descending"}),e.jsx("option",{value:"asc",children:"Ascending"})]})]})]}),e.jsxs(Za,{minWidth:"74rem",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx(Ae,{children:"Device"}),e.jsx(Ae,{children:"Owner"}),e.jsx(Ae,{children:"Status"}),e.jsx(Ae,{children:"Last activity"}),e.jsx(Ae,{children:"Inventory"}),e.jsx(Ae,{children:"Network"})]})}),e.jsx("tbody",{children:k.map(p=>{var v,q;return e.jsxs("tr",{children:[e.jsxs(Ne,{strong:!0,children:[p.name,e.jsx("div",{className:"text-xs font-normal text-[var(--theme-fg-muted)]",children:p.tokenPreview})]}),e.jsxs(Ne,{children:[e.jsx("span",{className:"font-medium text-[var(--theme-fg-soft)]",children:p.ownerUsername}),e.jsx("div",{className:"text-xs text-[var(--theme-fg-muted)]",children:p.ownerEmail})]}),e.jsx(Ne,{children:e.jsx(bn,{active:p.connected,children:p.connected?"Online":"Offline"})}),e.jsxs(Ne,{children:[Ge(na(p)),e.jsxs("div",{className:"text-xs text-[var(--theme-fg-muted)]",children:["created ",Ge(p.createdAt)]})]}),e.jsxs(Ne,{children:[e.jsxs("span",{children:[p.workspaces.length.toLocaleString()," workspaces"]}),e.jsx("span",{className:"mx-2 text-[var(--theme-fg-muted)]",children:"·"}),e.jsxs("span",{children:[p.threads.length.toLocaleString()," threads"]}),e.jsx("div",{className:"mt-1 truncate text-xs text-[var(--theme-fg-muted)]",children:((v=p.workspaces[0])==null?void 0:v.label)??"No workspace metadata"}),e.jsx("div",{className:"truncate text-xs text-[var(--theme-fg-muted)]",children:((q=p.threads[0])==null?void 0:q.title)??"No thread metadata"})]}),e.jsxs(Ne,{children:[p.ipAddress??"IP unavailable",e.jsxs("div",{className:"text-xs text-[var(--theme-fg-muted)]",children:["heartbeat ",Ge(p.lastHeartbeatAt)]})]})]},p.id)})})]}),k.length?null:e.jsx(ha,{children:"No devices match the selected filters."})]})}function Ai({shares:t}){return e.jsx(nt,{title:"Share relationships",detail:"Thread grants between relay users. Revoked grants remain visible for audit.",children:e.jsxs(Za,{minWidth:"62rem",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx(Ae,{children:"Owner"}),e.jsx(Ae,{children:"Target"}),e.jsx(Ae,{children:"Thread"}),e.jsx(Ae,{children:"Device"}),e.jsx(Ae,{children:"Permissions"}),e.jsx(Ae,{children:"Last access"}),e.jsx(Ae,{children:"Status"})]})}),e.jsx("tbody",{children:t.map(a=>e.jsxs("tr",{children:[e.jsx(Ne,{strong:!0,children:a.ownerUsername}),e.jsx(Ne,{children:a.targetUsername}),e.jsxs(Ne,{children:[e.jsx("span",{className:"font-medium text-[var(--theme-fg)]",children:a.threadTitle??a.label??"Thread unavailable"}),e.jsx("div",{className:"text-xs text-[var(--theme-fg-muted)]",children:a.workspaceLabel??"Workspace unavailable"})]}),e.jsx(Ne,{children:a.deviceName}),e.jsxs(Ne,{children:[a.threadAccess," / ",Hi(a.workspaceAccess)]}),e.jsx(Ne,{children:Ge(a.lastAccessedAt)}),e.jsx(Ne,{children:a.revokedAt?"Revoked":a.expiresAt&&a.expiresAt<=new Date().toISOString()?"Expired":"Active"})]},a.id))})]})})}function Ri({busy:t,draft:a,onChange:s,onReviewRegistration:r,onSave:l,pending:o,reviewBusyKey:i}){return e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[e.jsx(nt,{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:l,children:[e.jsx(hr,{checked:a.enabled,label:"Open registration",onChange:d=>s({...a,enabled:d})}),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:d=>s({...a,registrationPassword:d.target.value}),placeholder:"Leave empty for no invite password",value:a.registrationPassword??""})]}),e.jsx(hr,{checked:a.approvalRequired,label:"Require admin approval",onChange:d=>s({...a,approvalRequired:d})}),e.jsxs("button",{className:"relay-button-primary inline-flex items-center gap-2",disabled:t,type:"submit",children:[e.jsx(ie.Settings,{className:"h-4 w-4"}),"Save settings"]})]})}),e.jsx(nt,{title:"Pending registrations",detail:"Approve creates the user. Reject keeps an audit trail.",children:o.length?e.jsx("div",{className:"divide-y divide-[var(--theme-border)]",children:o.map(d=>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:d.username}),e.jsxs("p",{className:"truncate text-xs text-[var(--theme-fg-muted)]",children:[d.email," · ",Ge(d.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:${d.id}`,onClick:()=>r(d.id,"approve"),type:"button",children:[e.jsx(ie.Check,{className:"h-4 w-4"}),"Approve"]}),e.jsx("button",{className:"relay-button-secondary",disabled:i===`reject:${d.id}`,onClick:()=>r(d.id,"reject"),type:"button",children:"Reject"})]})]},d.id))}):e.jsx(ha,{children:"No pending applications."})})]})}function Pi({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:Ge(t.connectedAt)})]}),e.jsxs("p",{children:["Heartbeat: ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children:Ge(t.lastHeartbeatAt)})]})]})}function nt({aside:t,children:a,detail:s,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:s})]}),t]}),a]})}function Za({children:t,minWidth:a}){return e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:"w-full border-collapse text-left text-sm",style:{minWidth:a},children:t})})}function Ae({children:t}){return e.jsx("th",{className:"border-b border-[var(--theme-border)] py-2 pr-3 text-xs font-semibold uppercase tracking-[0.14em] text-[var(--theme-fg-muted)]",children:t})}function Nt({active:t,children:a,direction:s,onClick:r}){const l=t?s==="asc"?ie.ArrowUp:ie.ArrowDown:ie.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:[a,e.jsx(l,{className:"h-3.5 w-3.5"})]})})}function Ne({children:t,strong:a=!1}){return e.jsx("td",{className:`border-b border-[var(--theme-border)] py-3 pr-3 ${a?"font-medium text-[var(--theme-fg)]":"text-[var(--theme-fg-muted)]"}`,children:t})}function hr({checked:t,label:a,onChange:s}){return e.jsxs("label",{className:"flex items-center gap-3 text-sm text-[var(--theme-fg-soft)]",children:[e.jsx("input",{checked:t,className:"h-4 w-4 accent-[var(--theme-accent)]",onChange:r=>s(r.target.checked),type:"checkbox"}),a]})}function bn({active:t,children:a}){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:a})}function ha({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 Oi({busy:t,onClose:a,onSubmit:s,user:r}){const[l,o]=n.useState(""),[i,d]=n.useState(null);async function f(g){if(g.preventDefault(),d(null),l.length<8){d("Password must be at least 8 characters.");return}await s(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(--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=>o(g.target.value),type:"password",value:l})]}),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:a,type:"button",children:"Cancel"}),e.jsxs("button",{className:"relay-button-primary inline-flex items-center gap-2",disabled:t,type:"submit",children:[e.jsx(ie.KeyRound,{className:"h-4 w-4"}),"Save password"]})]})]})]})})}function Li({busy:t,confirmLabel:a,description:s,onClose:r,onConfirm:l,title: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(--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:o}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--theme-fg-muted)]",children:s}),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:l,type:"button",children:[e.jsx(ie.Trash2,{className:"h-4 w-4"}),a]})]})]})})}function pr(t){return t.trim().toLowerCase()}function Ui(t,a,s){const r=s.direction==="asc"?1:-1;let l=0;return s.key==="username"?l=t.username.localeCompare(a.username):s.key==="enabled"?l=Number(t.enabled)-Number(a.enabled):s.key==="lastSeenAt"?l=ra(t.lastSeenAt,a.lastSeenAt):s.key==="conversationCount"?l=t.conversationCount-a.conversationCount:s.key==="deviceCount"?l=t.deviceCount-a.deviceCount:l=ra(t.createdAt,a.createdAt),l*r||t.username.localeCompare(a.username)}function Di(t,a,s,r){const l=r==="asc"?1:-1;let o=0;return s==="name"?o=t.name.localeCompare(a.name):s==="ownerUsername"?o=t.ownerUsername.localeCompare(a.ownerUsername):s==="connected"?o=Number(t.connected)-Number(a.connected):s==="lastActivity"?o=ra(na(t),na(a)):s==="createdAt"?o=ra(t.createdAt,a.createdAt):s==="workspaceCount"?o=t.workspaces.length-a.workspaces.length:o=t.threads.length-a.threads.length,o*l||t.name.localeCompare(a.name)}function ra(t,a){const s=Date.parse(t??""),r=Date.parse(a??""),l=Number.isFinite(s)?s:-1/0,o=Number.isFinite(r)?r:-1/0;return l-o}function na(t){return t.lastHeartbeatAt??t.connectedAt??t.createdAt}function $i(t,a){const s=Date.parse(t??"");if(!Number.isFinite(s))return!1;const r=a==="24h"?24:a==="7d"?168:720;return s>=Date.now()-r*60*60*1e3}function fr(t,a){return t&&{...t,users:t.users.map(s=>s.id===a.id?{...s,...a}:s)}}function Mi(t){switch(t){case"overview":return"Overview";case"users":return"Users";case"devices":return"Devices";case"shares":return"Shares";case"settings":return"Settings"}}function Hi(t){switch(t){case"write":return"workspace write";case"read":return"workspace read";case"none":default:return"no workspace"}}function _i(t){return(a,s)=>Date.parse(s[t]??"")-Date.parse(a[t]??"")}function Ge(t){return t?new Date(t).toLocaleString():"never"}function Bi(t){const a=(t==null?void 0:t.trim())??"";return a?Array.from(a).slice(0,2).join("").toUpperCase():"??"}const Wi=3e3;function kt(t,a){return t instanceof te?t.payload.message:t instanceof Error?t.message:a}function Fi(){const t=He(),[a,s]=n.useState(null),[r,l]=n.useState(""),[o,i]=n.useState(null),[d,f]=n.useState(null),[g,C]=n.useState(!0),[h,S]=n.useState(null),[k,p]=n.useState(null),[v,q]=n.useState(null),[_,D]=n.useState(null),L=n.useRef(!1),E=n.useCallback(async I=>{const X=(I==null?void 0:I.showLoading)??!0,he=(I==null?void 0:I.clearError)??!0;X&&C(!0),he&&p(null);try{Xe();const pe=await Va();L.current=!0,s(pe)}catch(pe){(X||!L.current)&&p(kt(pe,"Unable to load devices."))}finally{X&&C(!1)}},[]);n.useEffect(()=>{E();const I=window.setInterval(()=>{E({showLoading:!1,clearError:!1})},Wi);return()=>{window.clearInterval(I)}},[E]);async function z(I){I.preventDefault(),S("create"),p(null);try{const X=await an({name:r});i(X),l(""),await E({showLoading:!1})}catch(X){p(kt(X,"Unable to create device."))}finally{S(null)}}async function Q(I){if(window.confirm(`Delete relay device "${I.name}"?`)){S(I.id),p(null);try{await sn(I.id),(o==null?void 0:o.device.id)===I.id&&i(null),await E({showLoading:!1})}catch(X){p(kt(X,"Unable to delete device."))}finally{S(null)}}}function c(I){It(I.id),At(null),t(Fa(I.id))}function P(I){It(I.deviceId),At(I.threadId),t(Wa(I.threadId,I.deviceId))}async function K(I,X){S(`share:${I.id}`),p(null);try{await rn(I.id,{...X,workspaceId:I.workspaceId,expiresAt:I.expiresAt}),D(null),await E({showLoading:!1})}catch(he){p(kt(he,"Unable to update shared thread."))}finally{S(null)}}async function m(I){if(window.confirm(`Remove sharing access for "${Xa(I)}"?`)){S(`share:${I.id}`),p(null);try{await Ga(I.id),q(X=>X===I.id?null:X),await E({showLoading:!1})}catch(X){p(kt(X,"Unable to remove shared thread access."))}finally{S(null)}}}async function H(I){var he;const X=I.token;if(!X){p("This device token is not available. Create a new device token for devices created before token storage was enabled.");return}try{await((he=navigator.clipboard)==null?void 0:he.writeText(vn(X))),f(I.id),window.setTimeout(()=>{f(pe=>pe===I.id?null:pe)},1600)}catch{}}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.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-5 pr-12 sm:pr-0",children:[e.jsx("header",{className:"border-b border-[var(--theme-border)] pb-5",children:e.jsxs("div",{children:[e.jsx(ze,{className:"text-sm text-[var(--theme-accent-strong)]",to:"/workspaces",children:"Back to workspaces"}),e.jsx("p",{className:"mt-4 text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Devices"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:"Device management"})]})}),k?e.jsx(Gi,{tone:"danger",children:k}):null,o?e.jsx(Vi,{result:o}):null,e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[minmax(20rem,0.8fr)_minmax(0,1.2fr)]",children:[e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4 flex items-start gap-3",children:[e.jsx("span",{className:"inline-flex h-9 w-9 items-center justify-center rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] text-[var(--theme-fg)]",children:e.jsx(ie.Plus,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Add device"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Create a token for one private supervisor."})]})]}),e.jsxs("form",{className:"space-y-3",onSubmit:z,children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Device name",e.jsx("input",{className:"relay-input mt-2 w-full",onChange:I=>l(I.target.value),placeholder:"MacBook Pro",value:r})]}),e.jsxs("button",{className:"relay-button-primary inline-flex h-10 w-full items-center justify-center gap-2",disabled:h==="create"||!r.trim(),type:"submit",children:[e.jsx(ie.MonitorSmartphone,{className:"h-4 w-4"}),"Create device token"]})]})]}),e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Devices"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Connect to an online device before opening workspaces."})]}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5 text-xs text-[var(--theme-fg-muted)]",children:(a==null?void 0:a.devices.length)??0})]}),g?e.jsx("p",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-4 text-sm text-[var(--theme-fg-muted)]",children:"Loading devices..."}):a!=null&&a.devices.length?e.jsx("div",{className:"space-y-3",children:a.devices.map(I=>e.jsx(zi,{busy:h===I.id,copiedSetup:d===I.id,device:I,onConnect:()=>c(I),onCopySetup:()=>void H(I),onDelete:()=>void Q(I),setupTokenAvailable:!!I.token},I.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.jsx(xr,{count:(a==null?void 0:a.sharedWithMe.length)??0,emptyText:"No sessions have been shared with this account yet.",loading:g,loadingText:"Loading shared sessions...",shares:(a==null?void 0:a.sharedWithMe)??[],title:"Shared with me",subtitle:"Sessions another relay user has shared with this account.",renderShare:I=>e.jsx(gr,{mode:"incoming",share:I,onOpen:()=>P(I)},I.id)}),e.jsx(xr,{count:(a==null?void 0:a.sharedByMe.length)??0,emptyText:"No sessions have been shared by this account yet.",loading:g,loadingText:"Loading shared sessions...",shares:(a==null?void 0:a.sharedByMe)??[],title:"Shared by me",subtitle:"Threads this relay account has shared with other users.",renderShare:I=>e.jsx(gr,{busy:h===`share:${I.id}`,expanded:v===I.id,mode:"outgoing",share:I,onOpen:()=>P(I),onEdit:()=>D(I),onRevoke:()=>void m(I),onToggleAccess:()=>{q(X=>X===I.id?null:I.id)}},I.id)})]}),_?e.jsx(qi,{busy:h===`share:${_.id}`,share:_,onClose:()=>D(null),onSave:I=>void K(_,I)}):null]})}function xr({count:t,emptyText:a,loading:s,loadingText:r,renderShare:l,shares:o,subtitle:i,title:d}){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:d}),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})]}),s?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}):o.length?e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:o.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:a})]})}function gr({busy:t=!1,expanded:a=!1,mode:s,onEdit:r,onRevoke:l,onToggleAccess:o,share:i,onOpen:d}){var S;const f=Xa(i),g=f,C=((S=i.workspaceLabel)==null?void 0:S.trim())||"Workspace unavailable",h=i.lastAccessedAt?`${i.lastAccessedByUsername??"unknown"} at ${oa(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",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:C})]}),e.jsxs("p",{className:"truncate",children:["Thread: ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children:g})]}),e.jsx("p",{className:"truncate",children:s==="incoming"?`From ${i.ownerUsername}`:`To ${i.targetUsername}`}),e.jsxs("p",{className:"truncate",children:["Device: ",i.deviceName]})]}),s==="outgoing"?e.jsxs("p",{className:"mt-1 text-xs text-[var(--theme-fg-soft)]",children:["Last access: ",h]}):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:Ki(i.workspaceAccess)})]})]}),s==="incoming"?e.jsx("button",{className:"relay-button-primary inline-flex items-center gap-2",onClick:d,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:d,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:o,type:"button",children:["Access",e.jsx(ie.ChevronDown,{className:`h-4 w-4 transition-transform ${a?"rotate-180":""}`})]}),e.jsx("button",{className:"relay-button-secondary inline-flex items-center gap-2 text-[var(--status-danger-fg)]",disabled:t,onClick:l,type:"button",children:"Revoke"})]})]}),s==="outgoing"&&a?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(k=>e.jsxs("li",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"font-medium text-[var(--theme-fg)]",children:k.username}),e.jsx("span",{children:oa(k.accessedAt)})]},k.id))}):e.jsx("p",{className:"text-xs text-[var(--theme-fg-muted)]",children:"This shared thread has not been accessed yet."})}):null]})}function qi({busy:t,onClose:a,onSave:s,share:r}){const[l,o]=n.useState(r.label??""),[i,d]=n.useState(r.threadAccess),[f,g]=n.useState(r.workspaceAccess),C=!r.workspaceId;function h(S){S.preventDefault(),s({label:l.trim()||null,threadAccess:i,workspaceAccess:C?"none":f})}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-lg rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-2xl",onSubmit:h,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 ",Xa(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:S=>o(S.target.value),placeholder:"Optional shared thread label",value:l})]}),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:S=>d(S.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:C,onChange:S=>g(S.target.value),value:C?"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"})]})]}),C?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("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 zi({device:t,busy:a,copiedSetup:s,onConnect:r,onCopySetup:l,onDelete:o,setupTokenAvailable:i}){return e.jsxs("article",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:`h-2.5 w-2.5 rounded-full ${t.connected?"bg-[var(--status-success-fg)]":"bg-[var(--theme-fg-muted)]"}`}),e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:t.name})]}),e.jsx("p",{className:"mt-1 font-mono text-xs text-[var(--theme-fg-muted)]",children:t.tokenPreview}),e.jsx("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:t.connected?`Online since ${oa(t.connectedAt)}`:`Offline. Last heartbeat: ${oa(t.lastHeartbeatAt)}`})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:l,title:i?"Copy relay supervisor setup command":"Device token is not available. Create a new device token for devices created before token storage was enabled.",disabled:!i,type:"button",children:[e.jsx(ie.Copy,{className:"h-4 w-4"}),s?"Copied":"Copy setup"]}),e.jsxs("button",{className:"relay-button-primary inline-flex items-center gap-2",disabled:!t.connected,onClick:r,type:"button",children:[e.jsx(ie.Plug,{className:"h-4 w-4"}),"Connect"]}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",disabled:a,onClick:o,type:"button",children:[e.jsx(ie.Trash2,{className:"h-4 w-4"}),"Delete"]})]})]}),i?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 Vi({result:t}){const a=vn(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(br,{label:"Device token",value:t.token}),e.jsx(br,{label:"Supervisor command",value:a})]})}function br({label:t,value:a}){async function s(){var r;try{await((r=navigator.clipboard)==null?void 0:r.writeText(a))}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 s(),type:"button",children:[e.jsx(ie.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:a})]})}function Gi({tone:t,children:a}){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:a})}function vn(t){const a=Ji();return[`REMOTE_CODEX_RELAY_SERVER_URL=${vr(a)} \\`,`REMOTE_CODEX_RELAY_AGENT_TOKEN=${vr(t)} \\`,"REMOTE_CODEX_RELAY_SUPERVISOR_PORT=45679 \\","remote-codex relay-supervisor"].join(`
5
+ `)}function vr(t){return/^[A-Za-z0-9_./:@%+=,~-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function Ji(){return typeof window>"u"?"wss://relay.example.com":window.location.origin.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://")}function oa(t){return t?new Date(t).toLocaleString():"never"}function Xa(t){var a,s;return((a=t.threadTitle)==null?void 0:a.trim())||((s=t.label)==null?void 0:s.trim())||"Thread unavailable"}function Ki(t){switch(t){case"write":return"Workspace write";case"read":return"Workspace read";case"none":default:return"No workspace"}}function Qa(t,a){return t instanceof te?t.payload.message:t instanceof Error?t.message:a}function yn(){var P,K;const t=He(),[a,s]=n.useState(null),[r,l]=n.useState(null),[o,i]=n.useState(!0),[d,f]=n.useState(null),[g,C]=n.useState(null),[h,S]=n.useState(null),[k,p]=n.useState(null);async function v(){var m;i(!0),f(null);try{Xe();const H=await Rt();if(s(H),H.authenticated){if(((m=H.user)==null?void 0:m.role)==="admin"){t("/relay-admin",{replace:!0});return}l(await Va())}else l(null)}catch(H){f(Qa(H,"Unable to load relay portal."))}finally{i(!1)}}n.useEffect(()=>{v()},[]);async function q(){C(null),await v()}async function _(m){const H=await an({name:m});C(H),await v()}async function D(m){window.confirm(`Delete relay device "${m.name}"?`)&&(await sn(m.id),await v())}async function L(m){await Ga(m),await v()}async function E(m,H){await rn(m.id,H),p(null),await v()}async function z(){await tn(),s(await Rt()),l(null),C(null)}function Q(m){It(m),At(null),t(Fa(m))}function c(m,H){It(m),At(H),t(Wa(H,m))}return o?e.jsx(Aa,{children:"Checking relay session..."}):a!=null&&a.authenticated?e.jsx(Aa,{children:e.jsxs("div",{className:"mx-auto flex w-full max-w-6xl flex-col gap-5",children:[e.jsxs("header",{className:"flex flex-col gap-3 border-b border-[var(--theme-border)] pb-5 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Portal"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:(P=a.user)==null?void 0:P.username}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Manage devices and shared Remote Codex sessions."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[((K=a.user)==null?void 0:K.role)==="admin"?e.jsx(ze,{className:"relay-button-secondary",to:"/relay-admin",children:"Admin"}):null,e.jsx("button",{className:"relay-button-secondary",onClick:()=>void v(),type:"button",children:"Refresh"}),e.jsx("button",{className:"relay-button-secondary",onClick:()=>void z(),type:"button",children:"Sign out"})]})]}),d?e.jsx(la,{tone:"danger",children:d}):null,g?e.jsxs(la,{tone:"accent",children:["Device token for ",g.device.name,". Store it on the device as REMOTE_CODEX_RELAY_AGENT_TOKEN. It will not be shown again.",e.jsx("code",{className:"mt-2 block break-all rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-2 font-mono text-xs",children:g.token}),e.jsx("code",{className:"mt-2 block break-all rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-2 font-mono text-xs",children:ed(g.token)})]}):null,e.jsx("section",{className:"grid gap-4",children:e.jsxs(yr,{title:"Devices",description:"Owned devices and sessions shared with you.",children:[e.jsx(Zi,{onCreate:_}),e.jsx("div",{className:"mt-4 divide-y divide-[var(--theme-border)] rounded-lg border border-[var(--theme-border)]",children:r!=null&&r.devices.length?r.devices.map(m=>e.jsxs("div",{className:"flex flex-col gap-3 p-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`h-2.5 w-2.5 rounded-full ${m.connected?"bg-emerald-500":"bg-[var(--theme-fg-muted)]"}`}),e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:m.name})]}),e.jsx("p",{className:"mt-1 font-mono text-xs text-[var(--theme-fg-muted)]",children:m.tokenPreview}),e.jsx("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:m.connected?`Online. Last heartbeat: ${ia(m.lastHeartbeatAt??m.connectedAt)}`:`Offline. Last online: ${ia(m.lastHeartbeatAt??m.connectedAt)}`})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{className:"relay-button-primary",disabled:!m.connected,onClick:()=>Q(m.id),type:"button",children:"Connect"}),e.jsx("button",{className:"relay-button-secondary",onClick:()=>void D(m),type:"button",children:"Delete"})]})]},m.id)):e.jsx("p",{className:"p-3 text-sm text-[var(--theme-fg-muted)]",children:"No devices yet."})}),e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-[var(--theme-fg)]",children:"Shared"}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5 text-[11px] text-[var(--theme-fg-muted)]",children:(r==null?void 0:r.sharedWithMe.length)??0})]}),e.jsx("div",{className:"mt-3 space-y-3",children:r!=null&&r.sharedWithMe.length?r.sharedWithMe.map(m=>e.jsx("article",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:da(m)}),e.jsxs("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:[m.workspaceLabel??"Workspace unavailable"," / ",m.ownerUsername," / ",m.deviceName]})]}),e.jsx("button",{className:"relay-button-primary",onClick:()=>c(m.deviceId,m.threadId),type:"button",children:"Continue"})]})},m.id)):e.jsx("p",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3 text-sm text-[var(--theme-fg-muted)]",children:"No shared sessions."})})]})]})}),e.jsx("section",{children:e.jsx(yr,{title:"Shared By Me",description:"Active invitations you created.",children:e.jsx("div",{className:"space-y-3",children:r!=null&&r.sharedByMe.length?r.sharedByMe.map(m=>e.jsx(Xi,{expanded:h===m.id,onEdit:()=>p(m),onOpen:()=>c(m.deviceId,m.threadId),onRevoke:()=>void L(m.id),onToggleAccess:()=>S(H=>H===m.id?null:m.id),share:m},m.id)):e.jsx("p",{className:"text-sm text-[var(--theme-fg-muted)]",children:"No active shares."})})})}),k?e.jsx(Qi,{onClose:()=>p(null),onSave:m=>void E(k,m),share:k}):null]})}):e.jsx(Aa,{children:e.jsx(Yi,{registrationEnabled:(a==null?void 0:a.registrationEnabled)??!0,initialError:d,onAuthenticated:q})})}function Yi({registrationEnabled:t,initialError:a,onAuthenticated:s}){const[r,l]=n.useState("login"),[o,i]=n.useState(""),[d,f]=n.useState(""),[g,C]=n.useState(""),[h,S]=n.useState(""),[k,p]=n.useState(""),[v,q]=n.useState(a),[_,D]=n.useState(null),[L,E]=n.useState(!1);async function z(Q){Q.preventDefault(),E(!0),q(null),D(null);try{if(r==="login")await il({identifier:o,password:h});else if((await ul({email:d,username:g,password:h,registrationPassword:k})).pendingApproval){D("Registration request sent. An admin must approve it before you can sign in."),l("login");return}await s()}catch(c){q(Qa(c,"Unable to authenticate with relay."))}finally{E(!1)}}return e.jsxs("section",{className:"w-full max-w-sm rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-xl shadow-black/10",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Access"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:r==="login"?"Sign in":"Create account"}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:z,children:[r==="login"?e.jsx(ft,{autoComplete:"username",label:"Email or username",onChange:i,value:o}):e.jsxs(e.Fragment,{children:[e.jsx(ft,{autoComplete:"email",label:"Email",onChange:f,value:d}),e.jsx(ft,{autoComplete:"username",label:"Username",onChange:C,value:g}),e.jsx(ft,{autoComplete:"one-time-code",label:"Registration password",onChange:p,type:"password",value:k})]}),e.jsx(ft,{autoComplete:r==="login"?"current-password":"new-password",label:"Password",onChange:S,type:"password",value:h}),v?e.jsx(la,{tone:"danger",children:v}):null,_?e.jsx(la,{tone:"accent",children:_}):null,e.jsx("button",{className:"relay-button-primary h-11 w-full",disabled:L,type:"submit",children:L?"Working...":r==="login"?"Sign in":"Register"})]}),e.jsx("button",{className:"mt-4 text-sm text-[var(--theme-accent-strong)] disabled:text-[var(--theme-fg-muted)]",disabled:r==="login"?!t:!1,onClick:()=>l(r==="login"?"register":"login"),type:"button",children:r==="login"?t?"Create relay account":"Registration is disabled":"Use an existing account"})]})}function Zi({onCreate:t}){const[a,s]=n.useState(""),[r,l]=n.useState(!1),[o,i]=n.useState(null);async function d(f){f.preventDefault(),l(!0),i(null);try{await t(a),s("")}catch(g){i(Qa(g,"Unable to create device."))}finally{l(!1)}}return e.jsxs("form",{className:"flex flex-col gap-2 sm:flex-row",onSubmit:d,children:[e.jsx("input",{className:"relay-input min-w-0 flex-1",onChange:f=>s(f.target.value),placeholder:"Device name",value:a}),e.jsx("button",{className:"relay-button-primary",disabled:r||!a.trim(),type:"submit",children:"Create"}),o?e.jsx("p",{className:"text-sm text-[var(--status-danger-fg)]",children:o}):null]})}function Xi({expanded:t,onEdit:a,onOpen:s,onRevoke:r,onToggleAccess:l,share:o}){const i=o.lastAccessedAt?`${o.lastAccessedByUsername??"unknown"} at ${ia(o.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 lg:flex-row lg:items-center lg: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:da(o)}),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:o.workspaceLabel??"Workspace unavailable"})]}),e.jsxs("p",{className:"truncate",children:["Thread: ",e.jsx("span",{className:"text-[var(--theme-fg-soft)]",children:da(o)})]}),e.jsxs("p",{className:"truncate",children:["To ",o.targetUsername," on ",o.deviceName]}),e.jsxs("p",{className:"truncate",children:["Last access: ",i]})]}),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:o.threadAccess==="read"?"View only":"Collaborator"}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5",children:ad(o.workspaceAccess)}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5",children:o.revokedAt?"Revoked":"Active"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{className:"relay-button-primary",onClick:s,type:"button",children:"Open"}),e.jsx("button",{className:"relay-button-secondary",onClick:a,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(ie.ChevronDown,{className:`h-4 w-4 transition-transform ${t?"rotate-180":""}`})]}),e.jsx("button",{className:"relay-button-secondary text-[var(--status-danger-fg)]",onClick:r,type:"button",children:"Revoke"})]})]}),t?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:o.accessEvents.length?e.jsx("ul",{className:"space-y-2 text-xs text-[var(--theme-fg-muted)]",children:o.accessEvents.map(d=>e.jsxs("li",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"font-medium text-[var(--theme-fg)]",children:d.username}),e.jsx("span",{children:ia(d.accessedAt)})]},d.id))}):e.jsx("p",{className:"text-xs text-[var(--theme-fg-muted)]",children:"This shared thread has not been accessed yet."})}):null]})}function Qi({onClose:t,onSave:a,share:s}){const[r,l]=n.useState(s.label??""),[o,i]=n.useState(s.threadAccess),[d,f]=n.useState(s.workspaceAccess),g=!s.workspaceId;function C(h){h.preventDefault(),a({label:r.trim()||null,threadAccess:o,workspaceAccess:g?"none":d})}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-lg rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-2xl",onSubmit:C,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:[s.targetUsername," can access ",da(s),"."]}),e.jsxs("div",{className:"mt-5 space-y-4",children:[e.jsx(ft,{label:"Label",onChange:l,value:r}),e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Thread access",e.jsxs("select",{className:"relay-input mt-2 w-full",onChange:h=>i(h.target.value),value:o,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:g,onChange:h=>f(h.target.value),value:g?"none":d,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("div",{className:"mt-5 flex justify-end gap-2",children:[e.jsx("button",{className:"relay-button-secondary",onClick:t,type:"button",children:"Cancel"}),e.jsx("button",{className:"relay-button-primary",type:"submit",children:"Save permissions"})]})]})})}function Aa({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(xn,{}),e.jsx("div",{className:"flex min-h-[calc(100vh-3rem)] items-center justify-center",children:t})]})}function yr({title:t,description:a,children:s}){return e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:t}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:a})]}),s]})}function ft({label:t,value:a,onChange:s,type:r="text",autoComplete:l}){return e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:[t,e.jsx("input",{autoComplete:l,className:"relay-input mt-2 w-full",onChange:o=>s(o.target.value),type:r,value:a})]})}function la({tone:t,children:a}){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:a})}function ed(t){return`REMOTE_CODEX_RELAY_SERVER_URL=${td()} REMOTE_CODEX_RELAY_AGENT_TOKEN=${t} remote-codex relay-supervisor`}function td(){return typeof window>"u"?"wss://relay.example.com":window.location.origin.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://")}function ia(t){return t??"never"}function da(t){var a,s;return((a=t.threadTitle)==null?void 0:a.trim())||((s=t.label)==null?void 0:s.trim())||"Thread unavailable"}function ad(t){switch(t){case"write":return"Workspace write";case"read":return"Workspace read";case"none":default:return"No workspace"}}function sd(t,a){const s=new Set(a.map(r=>r.id));return[...a,...t.filter(r=>!s.has(r.id))]}function Ye(t,a){const s=new Set(a.map(r=>r.id));return[...t.filter(r=>!s.has(r.id)),...a]}function rd(t,a){return!a||a.items.length===0?t:t.map(s=>{if(s.id!==a.turnId)return s;const r=a.items.filter(f=>f.kind==="agentMessage"&&f.createdAt);if(r.length===0)return s;const l=new Map(r.map(f=>[f.id,f])),o=new Set;let i=!1;const d=s.items.map(f=>{if(f.kind!=="agentMessage"||f.createdAt&&f.createdAt!==s.startedAt)return f;let g=l.get(f.id);return g||(g=r.find(C=>!o.has(C.id)&&C.text.trim().length>=8&&f.text.trim().includes(C.text.trim()))),!(g!=null&&g.createdAt)||g.createdAt===s.startedAt?f:(o.add(g.id),i=!0,{...f,createdAt:g.createdAt})});return i?{...s,items:d}:s})}function nd(t,a){return{...t,pendingRequests:[...t.pendingRequests.filter(s=>s.id!==a.id),a]}}function od(t,a){const s=t.pendingRequests.filter(r=>r.id!==a);return s.length===t.pendingRequests.length?t:{...t,pendingRequests:s}}function wr(t,a,s){const r=a.filter(d=>!s.has(d.id)),l=t.filter(d=>!s.has(d.id));if(l.length===0)return r;const o=new Map(r.map(d=>[d.id,d]));return[...l.map(d=>o.get(d.id)??d),...r.filter(d=>!l.some(f=>f.id===d.id))].sort((d,f)=>d.createdAt.localeCompare(f.createdAt))}function ld(t){if(!t||typeof t!="object")return!1;const a=t;return typeof a.id=="string"&&(a.kind==="requestUserInput"||a.kind==="planDecision")&&typeof a.title=="string"&&typeof a.createdAt=="string"&&Array.isArray(a.questions)}function wn(t,a){var o,i;if(!t||t.kind!==a.kind)return a;const s=d=>{let f=d;const g=typeof a.sequence=="number"&&Number.isFinite(a.sequence)?a.sequence:typeof t.sequence=="number"&&Number.isFinite(t.sequence)?t.sequence:null;g!==null&&f.sequence!==g&&(f={...f,sequence:g});const C=typeof a.transcriptOrder=="number"&&Number.isFinite(a.transcriptOrder)?a.transcriptOrder:typeof t.transcriptOrder=="number"&&Number.isFinite(t.transcriptOrder)?t.transcriptOrder:null;return C!==null&&f.transcriptOrder!==C&&(f={...f,transcriptOrder:C}),f};if(t.kind==="agentMessage"&&a.kind==="agentMessage")return s(t.text.length>a.text.length?{...a,text:t.text,sequence:a.sequence??t.sequence??null}:a);const r=((o=t.detailText)==null?void 0:o.trim())||t.text.trim(),l=((i=a.detailText)==null?void 0:i.trim())||a.text.trim();return s(r.length>l.length?t:a)}function id(t,a,s){if(!t||a&&a.turnId!==t.turnId)return a;const r=s.find(h=>h.id===t.turnId),l=new Map((r==null?void 0:r.items.map(h=>[h.id,h]))??[]),o=(r==null?void 0:r.items.filter(h=>h.kind==="agentMessage").map(h=>h.text.trim()).filter(Boolean))??[],i=h=>h.kind==="agentMessage"&&h.text.trim().length>0&&o.some(S=>S.includes(h.text.trim()));if(!a){const h=t.items.filter(S=>{const k=l.get(S.id);return k?k.kind!==S.kind||typeof S.sequence=="number"&&Number.isFinite(S.sequence)&&k.sequence!==S.sequence:!i(S)});return h.length===0?null:{...t,items:h}}const d=new Map(t.items.map(h=>[h.id,h])),f=new Map(a.items.map(h=>[h.id,h])),C=[...t.items.map(h=>h.id),...a.items.map(h=>h.id).filter(h=>!d.has(h))].map(h=>{const S=f.get(h),k=d.get(h);if(!S){const p=l.get(h);return!p&&k&&i(k)||p&&p.kind===(k==null?void 0:k.kind)&&!(k&&typeof k.sequence=="number"&&Number.isFinite(k.sequence)&&p.sequence!==k.sequence)?null:k??null}return wn(k,S)}).filter(h=>!!h);return C.length===0?null:{turnId:a.turnId,items:C,updatedAt:a.updatedAt.localeCompare(t.updatedAt)>=0?a.updatedAt:t.updatedAt}}function Tt(t,a){const s=t.filter(r=>r.id!==a.id);return[a,...s]}function dd(t){return`${t.threadId}:${t.objective}:${t.createdAt}`}function cd(t,a){const s=Date.parse(t.updatedAt)||0,l=(Date.parse(a.updatedAt)||0)>=s?a:t,o=l===a?t:a;return{...l,localGoalId:l.localGoalId??o.localGoalId??null}}function jn(t){const a=new Map;for(const s of t){const r=dd(s),l=a.get(r);a.set(r,l?cd(l,s):s)}return[...a.values()].sort((s,r)=>Date.parse(r.updatedAt)-Date.parse(s.updatedAt))}function ca(t,a){return jn([a,...t])}function ud(t){const a=new Intl.NumberFormat(void 0,{notation:"compact",maximumFractionDigits:1});return t.tokenBudget===null?`${a.format(t.tokensUsed)} tok`:`${a.format(t.tokensUsed)}/${a.format(t.tokenBudget)} tok`}function md(t){const a=Math.max(0,Math.floor(t/60)),s=Math.floor(a/60),r=a%60;return s>0?`${s}h ${r}m`:`${a}m`}function jr(t,a){if(!a)return null;const s=t.find(r=>r.model===a);return s?s.supportedReasoningEfforts.length>1:null}function hd(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`client-${Date.now()}-${Math.random().toString(16).slice(2,10)}`}function St(t,a){return(t==null?void 0:t.items.some(s=>s.kind==="userMessage"&&s.text.trim()===a))??!1}const pd=/\s*\[(?:PHOTO\s+[^\]]+|localImage)\]\s*/g;function Ct(t){return/\[(?:PHOTO\s+[^\]]+|localImage)\]/.test(t)}function Nr(t){return t.replace(pd," ").replace(/\s+/g," ").trim()}function ta(t,a){const s=Nr(a);return s?(t==null?void 0:t.items.some(r=>r.kind==="userMessage"&&Nr(r.text)===s))??!1:!1}function Ra(t){return(t==null?void 0:t.items.some(a=>a.kind==="userMessage"&&/\[(?:PHOTO\s+\.\/\.temp\/threads\/[^\]]+|localImage)\]/.test(a.text)))??!1}function fd(t,a){return t.find(s=>St(s,a))??(Ct(a)?t.find(s=>ta(s,a))??null:null)}function xd(t,a,s,r){let l=!1;const o=t.map(i=>i.id!==a?i:(l=!0,{...i,tokenUsage:s,priceEstimate:r}));return l?o:t}function gd({activeView:t,composerHostRef:a,threadId:s}){const[r,l]=n.useState(!1),[o,i]=n.useState(0),[d,f]=n.useState(0),[g,C]=n.useState(0),[h,S]=n.useState(!1);n.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const D=window.matchMedia("(max-width: 639px)"),L=()=>l(D.matches);return L(),D.addEventListener("change",L),()=>{D.removeEventListener("change",L)}},[]),n.useEffect(()=>{var L,E;if(typeof window>"u")return;const D=()=>{const z=window.visualViewport,Q=z?Math.max(0,Math.round(window.innerHeight-z.height-z.offsetTop)):0;C(Q),document.documentElement.style.setProperty("--thread-detail-keyboard-inset",`${Q}px`)};return D(),(L=window.visualViewport)==null||L.addEventListener("resize",D),(E=window.visualViewport)==null||E.addEventListener("scroll",D),window.addEventListener("resize",D),()=>{var z,Q;(z=window.visualViewport)==null||z.removeEventListener("resize",D),(Q=window.visualViewport)==null||Q.removeEventListener("scroll",D),window.removeEventListener("resize",D),document.documentElement.style.removeProperty("--thread-detail-keyboard-inset")}},[]),n.useEffect(()=>{if(typeof document>"u")return;const D=()=>{const L=document.activeElement,E=a.current,z=E==null?void 0:E.querySelector('[aria-label="Prompt"]');S(!!(L&&z&&(L===z||z.contains(L))))};return D(),document.addEventListener("focusin",D),document.addEventListener("focusout",D),()=>{document.removeEventListener("focusin",D),document.removeEventListener("focusout",D)}},[t,a,r,s]),n.useEffect(()=>{const D=a.current;if(!D||typeof ResizeObserver>"u")return;const L=D.querySelector("form")??D,E=()=>{i(Math.max(D.getBoundingClientRect().height,L.getBoundingClientRect().height))};E();const z=new ResizeObserver(()=>{E()});return z.observe(L),()=>{z.disconnect()}},[t,a,r]),n.useEffect(()=>{var z,Q;const D=a.current;if(!D||!r||t!=="chat"){f(0);return}const L=()=>{const c=D.getBoundingClientRect();f(Math.max(0,Math.ceil(window.innerHeight-c.top)))};L(),window.addEventListener("resize",L),(z=window.visualViewport)==null||z.addEventListener("resize",L),(Q=window.visualViewport)==null||Q.addEventListener("scroll",L);let E=null;return typeof ResizeObserver<"u"&&(E=new ResizeObserver(L),E.observe(D)),()=>{var c,P;window.removeEventListener("resize",L),(c=window.visualViewport)==null||c.removeEventListener("resize",L),(P=window.visualViewport)==null||P.removeEventListener("scroll",L),E==null||E.disconnect()}},[t,a,r,g,h,s]);const k=r&&t==="chat",p=k&&h?g:0,v=Math.max(o,144),q=Math.max(d,v+p),_=k?q+12:0;return{floatingMobileComposerBottomOffset:p,timelineBottomSpacer:_,useFloatingMobileComposer:k}}const $e=()=>({status:"idle",data:null,error:null});function bd({detailRef:t,id:a,navigate:s,setDetail:r,setError:l,setThreads:o}){const[i,d]=n.useState($e),[f,g]=n.useState($e),[C,h]=n.useState($e),[S,k]=n.useState($e),[p,v]=n.useState($e),[q,_]=n.useState(!1),[D,L]=n.useState(!1),[E,z]=n.useState(()=>new Set),[Q,c]=n.useState(!1),[P,K]=n.useState(!1),[m,H]=n.useState($e);n.useEffect(()=>{d($e),g($e),h($e),k($e),v($e),_(!1),z(new Set),c(!1),H($e)},[a]);const I=n.useCallback(async()=>{if(a){H(A=>({status:"loading",data:A.data,error:null}));try{const A=await ql(a);H({status:"ready",data:A,error:null})}catch(A){const T=A instanceof te?A.payload.message:"Unable to load export turns.";H(ae=>({status:"failed",data:ae.data,error:T}))}}},[a]);async function X(A){if(a){l(null),K(!0);try{const{blob:T,filename:ae}=await Vl(a,A),Oe=URL.createObjectURL(T),x=document.createElement("a");x.href=Oe,x.download=ae,document.body.append(x),x.click(),x.remove(),window.setTimeout(()=>URL.revokeObjectURL(Oe),3e4),c(!1)}catch(T){const ae=T instanceof te?T.payload.message:"Unable to export transcript.";l(ae)}finally{K(!1)}}}async function he(){if(a){v(A=>{var T;return{status:"loading",data:A.data??((T=t.current)==null?void 0:T.goal)??null,error:null}});try{const A=await ri(a);v({status:"ready",data:A.goal,error:null}),r(T=>T&&(A.goal?{...T,goal:A.goal,goalHistory:ca(T.goalHistory??[],A.goal)}:{...T,goal:A.goal}))}catch(A){v(T=>({status:"failed",data:T.data,error:A instanceof te?A.payload.message:"Unable to load goal."}))}}}async function pe(A){if(a){v(T=>{var ae;return{status:"loading",data:T.data??((ae=t.current)==null?void 0:ae.goal)??null,error:null}});try{const T=await ni(a,A);v({status:"ready",data:T.goal,error:null}),r(ae=>ae&&(T.goal?{...ae,goal:T.goal,goalHistory:ca(ae.goalHistory??[],T.goal)}:{...ae,goal:T.goal}))}catch(T){throw v(ae=>({status:"failed",data:ae.data,error:T instanceof te?T.payload.message:"Unable to update goal."})),T}}}async function B(){if(a){v(A=>{var T;return{status:"loading",data:A.data??((T=t.current)==null?void 0:T.goal)??null,error:null}});try{const A=await oi(a);v({status:"ready",data:null,error:null}),r(T=>T&&(A.goalHistory?{...T,goal:null,goalHistory:A.goalHistory}:{...T,goal:null}))}catch(A){throw v(T=>({status:"failed",data:T.data,error:A instanceof te?A.payload.message:"Unable to clear goal."})),A}}}async function J(A){L(!0);try{await pe({status:A})}finally{L(!1)}}async function ue(){L(!0);try{await B()}finally{L(!1)}}async function Y(){if(a){d(A=>({status:"loading",data:A.data,error:null}));try{const A=await ii(a);d({status:"ready",data:A,error:null})}catch(A){d(T=>({status:"failed",data:T.data,error:A instanceof te?A.payload.message:"Unable to load skills."}))}}}async function G(){if(a){g(A=>({status:"loading",data:A.data,error:null}));try{const A=await di(a);g({status:"ready",data:A,error:null})}catch(A){g(T=>({status:"failed",data:T.data,error:A instanceof te?A.payload.message:"Unable to load MCP servers."}))}}}async function me(){if(a){h(A=>({status:"loading",data:A.data,error:null}));try{const A=await ci(a);h({status:"ready",data:A,error:null})}catch(A){h(T=>({status:"failed",data:T.data,error:A instanceof te?A.payload.message:"Unable to load hooks."}))}}}async function de(A){if(a){h(T=>({status:"loading",data:T.data,error:null}));try{const T=await ui(a,A);h({status:"ready",data:T,error:null})}catch(T){throw h(ae=>({status:"failed",data:ae.data,error:T instanceof te?T.payload.message:"Unable to create hook."})),T}}}async function Ce(A){if(a){h(T=>({status:"loading",data:T.data,error:null}));try{const T=await mi(a,A);h({status:"ready",data:T,error:null})}catch(T){throw h(ae=>({status:"failed",data:ae.data,error:T instanceof te?T.payload.message:"Unable to update hook."})),T}}}async function U(A){if(a){h(T=>({status:"loading",data:T.data,error:null}));try{const T=await hi(a,A);h({status:"ready",data:T,error:null})}catch(T){throw h(ae=>({status:"failed",data:ae.data,error:T instanceof te?T.payload.message:"Unable to trust hook."})),T}}}async function ee(A){if(a){h(T=>({status:"loading",data:T.data,error:null}));try{const T=await pi(a,A);h({status:"ready",data:T,error:null})}catch(T){throw h(ae=>({status:"failed",data:ae.data,error:T instanceof te?T.payload.message:"Unable to untrust hook."})),T}}}async function ve(){if(a){k(A=>({status:"loading",data:A.data,error:null}));try{const A=await li(a);k({status:"ready",data:A,error:null})}catch(A){k(T=>({status:"failed",data:T.data,error:A instanceof te?A.payload.message:"Unable to load turns for forking."}))}}}async function ke(){if(!a)return;const A=await ur(a,{mode:"latest"});o(T=>Tt(T,A.thread.thread)),s(Ue(A.thread.thread.id))}async function we(A){if(!a)return;const T=await ur(a,{mode:"turn",turnId:A});o(ae=>Tt(ae,T.thread.thread)),s(Ue(T.thread.thread.id))}return{expandedGoalIds:E,exportBusy:P,exportDialogOpen:Q,exportTurnsState:m,forkTurnOptionsState:S,goalActionBusy:D,goalMonitorOpen:q,goalState:p,handleCreateHook:de,handleExportTranscript:X,handleForkLatest:ke,handleForkTurn:we,handleGoalStatusAction:J,handleOpenForkTurns:ve,handleOpenGoal:he,handleOpenHooks:me,handleOpenMcp:G,handleOpenSkills:Y,handleTerminateGoal:ue,handleTrustHook:U,handleUntrustHook:ee,handleUpdateGoal:pe,handleUpdateHook:Ce,hooksState:C,loadExportTurns:I,mcpState:f,setExpandedGoalIds:z,setExportDialogOpen:c,setGoalMonitorOpen:_,setGoalState:v,skillsState:i}}const vd=5e3;function kr(t){return JSON.stringify(t)}function yd(t,a){return kr(t)===kr(a)}function wd(t,a){const s=new Map(t.map(o=>[o.id,o]));let r=t.length!==a.length;const l=a.map((o,i)=>{var f;const d=s.get(o.id);return d&&yd(d,o)?(((f=t[i])==null?void 0:f.id)!==o.id&&(r=!0),d):(r=!0,o)});return r?l:t}function Nn(t){const{enabled:a,setThreads:s,intervalMs:r=vd}=t,l=n.useRef(!1),o=n.useCallback(async()=>{if(!(!a||l.current)&&!(typeof document<"u"&&document.visibilityState==="hidden")){l.current=!0;try{const i=await Ka();s(d=>wd(d,i))}catch{}finally{l.current=!1}}},[a,s]);n.useEffect(()=>{if(!a||typeof window>"u")return;const i=window.setInterval(()=>{o()},r),d=()=>{document.visibilityState==="visible"&&o()};return document.addEventListener("visibilitychange",d),()=>{window.clearInterval(i),document.removeEventListener("visibilitychange",d)}},[a,r,o])}function jd({setError:t,workspaceId:a,access:s="write"}){return n.useMemo(()=>!a||s==="none"?null:{listTree:r=>Pl(a,{path:r.path??""}),readFile:r=>Ol(a,{path:r.path,...r.offset!==void 0?{offset:r.offset}:{},...r.limit!==void 0?{limit:r.limit}:{}}),getRawFileUrl:r=>Ll(a,{path:r.path}),...s==="write"?{uploadFile:r=>$l(a,{file:r.file}),writeFile:async r=>{await Ml(a,{path:r.path,content:r.content})}}:{},downloadNode:async r=>{t(null);try{const l=await Dl(a,{path:r.path}),o=URL.createObjectURL(l.blob),i=document.createElement("a");i.href=o,i.download=l.filename,document.body.append(i),i.click(),i.remove(),URL.revokeObjectURL(o)}catch(l){t(l instanceof te?l.payload.message:l instanceof Error?l.message:"Workspace download failed.")}}},[s,t,a])}function Ze(t){return t.enabled&&t.capabilities.sessions.resume&&t.capabilities.turns.start}function Sr(t,a){var r;const s=t.find(l=>l.provider===a);return s&&Ze(s)?s.provider:((r=t.find(Ze))==null?void 0:r.provider)??qe}function es({initialWorkspaceId:t,initialTitle:a="",onCreated:s,onCancel:r,variant:l="panel"}){const o=ot(),i=n.useId(),[d,f]=n.useState([]),[g,C]=n.useState([]),[h,S]=n.useState([]),[k,p]=n.useState((o==null?void 0:o.defaultBackend)??qe),[v,q]=n.useState(""),[_,D]=n.useState(""),[L,E]=n.useState(()=>a??""),[z,Q]=n.useState("yolo"),[c,P]=n.useState(!0),[K,m]=n.useState(!1),[H,I]=n.useState(null),[X,he]=n.useState(null),pe=(o==null?void 0:o.defaultBackend)??qe,B=g.find(U=>U.provider===k),J=l==="dialog",ue=J?"host-form-control mt-1.5 h-10 w-full rounded-xl border px-3 text-sm outline-none transition":"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",Y=J?"host-secondary-button rounded-full border px-3 py-2 text-sm font-medium transition disabled:cursor-not-allowed disabled:opacity-60":"host-secondary-button rounded-full border px-5 py-3 font-medium transition disabled:cursor-not-allowed disabled:opacity-60",G=J?"ui-action-primary rounded-full px-4 py-2.5 text-sm font-medium transition disabled:cursor-not-allowed":"ui-action-primary rounded-full px-5 py-3 font-medium transition disabled:cursor-not-allowed";n.useEffect(()=>{E(a??"")},[a]),n.useEffect(()=>{let U=!1;return Promise.all([Ja(),sa()]).then(async([ee,ve])=>{var ae,Oe,x;if(U)return;const ke=Sr(ve,pe);p(ke),C(ve);const we=await ea(ke);if(U)return;f(ee),S(we);const A=t??null,T=ee.some(w=>w.id===A)?A:((ae=ee[0])==null?void 0:ae.id)??"";q(T),D(((Oe=we.find(w=>w.isDefault))==null?void 0:Oe.model)??((x=we[0])==null?void 0:x.model)??"")}).catch(ee=>{U||he(ee instanceof Error?ee.message:"Unable to load creation form data.")}).finally(()=>{U||P(!1)}),()=>{U=!0}},[pe,t]),n.useEffect(()=>{if(!k)return;let U=!1;return S([]),D(""),he(null),ea(k).then(ee=>{var ve,ke;U||(S(ee),D(((ve=ee.find(we=>we.isDefault))==null?void 0:ve.model)??((ke=ee[0])==null?void 0:ke.model)??""))}).catch(ee=>{U||(S([]),D(""),he(ee instanceof Error?ee.message:"Unable to load backend models."))}),()=>{U=!0}},[k]);async function me(U=k){var A,T;const ee=await sa();C(ee);const ve=ee.find(ae=>ae.provider===U),ke=ve&&Ze(ve)?U:Sr(ee,pe);p(ke);const we=await ea(ke);S(we),D(((A=we.find(ae=>ae.isDefault))==null?void 0:A.model)??((T=we[0])==null?void 0:T.model)??"")}async function de(U){const ee=U.installation.installed?"update":"install";I(U.provider),he(null);try{await on(U.provider,ee),await me(U.provider)}catch(ve){ve instanceof te?he(ve.payload.message):he(ve instanceof Error?ve.message:`Unable to ${ee} ${U.displayName}.`);try{await me(k)}catch{}}finally{I(null)}}async function Ce(U){U.preventDefault(),m(!0),he(null);try{const ee=await Jl(L.trim()?{workspaceId:v,provider:k,model:_,approvalMode:z,title:L.trim()}:{workspaceId:v,provider:k,model:_,approvalMode:z});s(ee)}catch(ee){ee instanceof te?he(ee.payload.message):he(ee instanceof Error?ee.message:"Unable to create thread.")}finally{m(!1)}}return c?e.jsx("div",{className:"host-empty-state rounded-3xl border px-6 py-12 text-center",children:"Loading creation form..."}):e.jsxs("form",{onSubmit:Ce,className:J?"max-h-[min(76vh,36rem)] space-y-3 overflow-y-auto pr-1 text-sm":"space-y-5",children:[J?e.jsxs("div",{className:"pr-8",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Create New Chat"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Choose the workspace, 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:k,onChange:U=>{const ee=U.target.value;p(ee)},className:ue,children:g.map(U=>e.jsxs("option",{value:U.provider,disabled:!Ze(U),children:[U.displayName,Ze(U)?"":" (not available)"]},U.provider))}),J?B&&!Ze(B)?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(U=>{const ee=Ze(U),ve=U.provider===k,ke=U.installation.installed?!!U.installation.updateCommand:!!U.installation.installCommand,we=U.installation.installed?"Update":"Install",A=H===U.provider||U.installation.busy;return e.jsxs("div",{className:`rounded-2xl border px-4 py-3 transition ${ve?"host-surface-strong":"host-surface"} ${ee?"":"opacity-75"}`,children:[e.jsxs("div",{className:"flex flex-wrap items-start gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>{ee&&p(U.provider)},disabled:!ee||K||A,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:U.displayName}),ve?e.jsx("span",{className:"host-pill rounded-full px-2 py-0.5 text-xs",children:"Selected"}):null,ee?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:U.installation.installed?`Installed${U.installation.installedVersion?`: ${U.installation.installedVersion}`:""}`:U.installation.lastError??U.status.lastError??"Runtime is not installed."}),!ee&&U.installation.lastError?e.jsx("p",{className:"mt-1 text-xs opacity-70",children:U.installation.lastError}):null]}),ke?e.jsx("button",{type:"button",onClick:()=>de(U),disabled:K||A||H!==null,className:"host-secondary-button rounded-full border px-3 py-2 text-sm font-medium transition disabled:cursor-not-allowed disabled:opacity-60","aria-label":`${we} ${U.displayName}`,children:A?`${we}ing...`:we}):null]}),!ee&&ke?e.jsx("p",{className:"mt-2 text-xs opacity-70",children:"Relay connections install or update the runtime on the selected device."}):null]},U.provider)})}),!J&&B&&!Ze(B)?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:v,onChange:U=>q(U.target.value),className:ue,children:d.map(U=>e.jsxs("option",{value:U.id,children:[U.label," · ",U.absPath]},U.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:_,onChange:U=>D(U.target.value),disabled:h.length===0,className:ue,children:[h.length===0?e.jsx("option",{value:"",children:"No models available"}):null,h.map(U=>e.jsxs("option",{value:U.model,children:[U.displayName," · ",U.model]},U.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:L,onChange:U=>E(U.target.value),placeholder:"Optional. Falls back to first prompt.",className:ue})]}),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:z,onChange:U=>Q(U.target.value),className:ue,children:[e.jsx("option",{value:"yolo",children:"yolo"}),e.jsx("option",{value:"guarded",children:"guarded"})]})]}),X&&e.jsx("div",{className:"host-error rounded-2xl border px-4 py-3 text-sm",children:X}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[e.jsx("button",{type:"submit",disabled:K||!v||!_,className:G,children:K?"Creating...":"Create Thread"}),r?e.jsx("button",{type:"button",onClick:r,disabled:K,className:Y,children:"Cancel"}):null]})]})}const Cr=3,Nd=3,kd=1e3,Sd=2e3,Pa=5500,Cd=3e3,Oa=0,ht=1,Kt=3,Td=[],Ed=[],Id=[],Ad={workspace:!0,toolUsage:!1,guide:!1,threadGraph:!1,extensions:!1,defaultTab:"workspace"};function Yt(t,a){return t instanceof te?t.payload.message:t instanceof Error?t.message:a}function Tr(t){return t==="read"?"View only":"Collaborator"}function Er(t){switch(t){case"write":return"Workspace write";case"read":return"Workspace read";case"none":default:return"No workspace"}}function Rd(t){var a,s;return((s=(a=t.match(/^\[PHOTO\s+([^\]]+)\]$/))==null?void 0:a[1])==null?void 0:s.trim())??null}function Ir(t){return!(t!=null&&t.length)||typeof URL.createObjectURL!="function"?[]:t.flatMap(a=>{if(a.kind!=="photo")return[];const s=Rd(a.placeholder);return s?[{path:s,url:URL.createObjectURL(a.file)}]:[]})}function Pd(t){if(typeof URL.revokeObjectURL=="function")for(const a of t)URL.revokeObjectURL(a.url)}function Od(t,a){const s=t.trim().replace(/\\/g,"/").replace(/\/+$/,""),r=a.trim().replace(/\\/g,"/").replace(/\/+$/,"");if(!s)return null;if(!s.startsWith("/"))return s.replace(/^\.\/+/,"").replace(/^\/+/,"");if(s===r)return"";const l=`${r}/`;return s.startsWith(l)?s.slice(l.length):null}function Ld(){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 Ud(){return e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-none stroke-current",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M4.25 2.25h5.2l2.3 2.3v9.2h-7.5a2 2 0 0 1-2-2v-7.5a2 2 0 0 1 2-2Z"}),e.jsx("path",{d:"M9.25 2.5v2.25h2.25"}),e.jsx("path",{d:"M7 6.75v4"}),e.jsx("path",{d:"m5.45 9.35 1.55 1.55 1.55-1.55"})]})}function Zt({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 Dd(t,a){if(!t)return"Thread disconnected";switch(a.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 Ar(){var ar;const{id:t=""}=fo(),a=ua(),s=He(),r=ot(),l=_r(),o=n.useRef(""),i=n.useRef(null),d=n.useRef(null),f=n.useRef(null),g=n.useRef(!1),C=n.useRef(null),h=n.useRef(null),S=n.useRef(typeof navigator>"u"?!0:navigator.onLine),k=n.useRef(!1),p=n.useRef(null),v=n.useRef(null),q=n.useRef(0),_=n.useRef(0),D=n.useRef(null),L=n.useRef(null),E=n.useRef(null),z=n.useRef(null),Q=n.useRef(new Set),[c,P]=n.useState(null),[K,m]=n.useState([]),[H,I]=n.useState([]),[X,he]=n.useState(null),[pe,B]=n.useState(null),[J,ue]=n.useState(null),[Y,G]=n.useState(""),[me,de]=n.useState(null),[Ce,U]=n.useState(null),ee=n.useRef(null),[ve,ke]=n.useState(!0),[we,A]=n.useState(0),[T,ae]=n.useState(!0),[Oe,x]=n.useState(!1),[w,M]=n.useState(!1),[V,fe]=n.useState("chat"),[Re,Qe]=n.useState(null),Je=l.getThreadPanels().some(u=>u.kind==="terminal");n.useEffect(()=>{ee.current=Ce},[Ce]);const Lt=n.useMemo(()=>({fetchState:Gl,createShell:Yl,terminateShell:Zl,updateShell:Xl,connectSocket:yi}),[]),et=n.useCallback(u=>Ue(u),[]),lt=n.useCallback(u=>{s(Ue(u))},[s]),tt=n.useCallback(u=>aa(u),[]),ts=n.useCallback(({close:u,closeNavigation:y,currentWorkspaceId:b})=>e.jsx(es,{variant:"dialog",initialWorkspaceId:b,onCancel:u,onCreated:N=>{u(),y(),s(Ue(N.id))}}),[s]),as=n.useCallback(({threadId:u,path:y})=>Ul(u,{path:y}),[]),[ss,pa]=n.useState({prompt:"",attachments:[]}),[se,rs]=n.useState(null),[ns,gt]=n.useState(!1),[An,os]=n.useState(!1),[Rn,ls]=n.useState(!1),[is,ds]=n.useState(null),[at,Ut]=n.useState("idle"),[Ke,cs]=n.useState({status:S.current?"checking":"offline",browserOnline:S.current,healthOk:!1,socketOpen:!1,lastHealthyAt:null}),[le,_e]=n.useState(null),[Dt,it]=n.useState([]);n.useEffect(()=>{const u=(le==null?void 0:le.attachmentPreviews)??[];return()=>{Pd(u)}},[le]);const[Be,fa]=n.useState(null),[xa,us]=n.useState(!1),[Pn,re]=n.useState(null),ga=((ar=J==null?void 0:J.hostConfigFiles.find(u=>{var y;return(y=u.roles)==null?void 0:y.includes("mcp")}))==null?void 0:ar.name)??null,{expandedGoalIds:On,exportBusy:ba,exportDialogOpen:$t,exportTurnsState:ms,forkTurnOptionsState:Ln,goalActionBusy:va,goalMonitorOpen:Un,goalState:Mt,handleCreateHook:Dn,handleExportTranscript:hs,handleForkLatest:$n,handleForkTurn:Mn,handleGoalStatusAction:ps,handleOpenForkTurns:Hn,handleOpenGoal:fs,handleOpenHooks:_n,handleOpenMcp:Bn,handleOpenSkills:Wn,handleTerminateGoal:Fn,handleTrustHook:qn,handleUntrustHook:zn,handleUpdateGoal:Vn,handleUpdateHook:Gn,hooksState:Jn,loadExportTurns:xs,mcpState:Kn,setExpandedGoalIds:Yn,setExportDialogOpen:gs,setGoalMonitorOpen:bs,setGoalState:ya,skillsState:Zn}=bd({detailRef:E,id:t,navigate:s,setDetail:P,setError:re,setThreads:m}),[wa,Ht]=n.useState(!1),[vs,We]=n.useState({status:"idle",shares:[],error:null}),[_t,Bt]=n.useState({status:"idle",access:null,error:null}),ys=qr(a.pathname),st=rt()&&!!ys,ne=_t.access,bt=!st||(ne==null?void 0:ne.kind)==="owner",Le=bt||(ne==null?void 0:ne.kind)==="shared"&&ne.threadAccess==="control",ws=st&&(ne==null?void 0:ne.kind)==="owner",Xn=(c==null?void 0:c.workspace.id)??(c==null?void 0:c.thread.workspaceId)??null,Qn=st?(ne==null?void 0:ne.kind)==="owner"?"write":(ne==null?void 0:ne.kind)==="shared"&&ne.workspaceId&&ne.workspaceId===Xn?ne.workspaceAccess:"none":"write",dt=n.useCallback(async()=>{const u=E.current,y=Ve();if(!rt()||!u||!y){We({status:"ready",shares:[],error:null});return}We(b=>({...b,status:"loading",error:null}));try{const N=(await Va()).sharedByMe.filter($=>$.deviceId===y&&$.threadId===u.thread.id).map($=>({id:$.id,targetUsername:$.targetUsername,label:$.label,threadAccess:$.threadAccess,workspaceAccess:$.workspaceAccess,createdAt:$.createdAt}));We({status:"ready",shares:N,error:null})}catch(b){We(N=>({...N,status:"failed",error:Yt(b,"Unable to load active shares.")}))}},[E]),js=n.useCallback(async u=>{const y=E.current,b=Ve();if(!rt()||!y||!b){We($=>({...$,status:"failed",error:"Relay sharing is only available from a relay device route."}));return}const N=u.workspaceAccess==="none"?null:y.workspace.id??y.thread.workspaceId??null;if(u.workspaceAccess!=="none"&&!N){We($=>({...$,status:"failed",error:"This thread is not attached to a workspace."}));return}Ht(!0),We($=>({...$,error:null}));try{await fl({targetIdentifier:u.targetIdentifier,deviceId:b,threadId:y.thread.id,workspaceId:N,label:u.label??null,threadAccess:u.threadAccess,workspaceAccess:u.workspaceAccess}),await dt()}catch($){const Z=Yt($,"Unable to create share.");We(oe=>({...oe,status:"failed",error:Z})),re(Z)}finally{Ht(!1)}},[E,dt]),Ns=n.useCallback(async u=>{Ht(!0),We(y=>({...y,error:null}));try{await Ga(u),await dt()}catch(y){const b=Yt(y,"Unable to revoke share.");We(N=>({...N,status:"failed",error:b})),re(b)}finally{Ht(!1)}},[dt]);n.useEffect(()=>{$t&&dt()},[$t,dt]),n.useEffect(()=>{const u=E.current,y=Ve();if(!rt()||!u||!y){Bt({status:"idle",access:null,error:null});return}let b=!1;return Bt(N=>({...N,status:"loading",error:null})),ml({deviceId:y,threadId:u.thread.id}).then(N=>{b||Bt({status:"ready",access:N,error:null})}).catch(N=>{b||Bt({status:"failed",access:null,error:Yt(N,"Unable to verify relay permissions.")})}),()=>{b=!0}},[c==null?void 0:c.thread.id,c==null?void 0:c.workspace.id,E]),Nn({enabled:!!t,setThreads:m});const ks=n.useCallback(()=>{const u=o.current;o.current="",i.current=null,u&&n.startTransition(()=>{G(y=>y+u)})},[]),Ss=n.useCallback(u=>{o.current+=u,i.current===null&&(i.current=window.requestAnimationFrame(()=>{ks()}))},[ks]),Cs=n.useCallback((u,y)=>{U(b=>{const N=(b==null?void 0:b.turnId)===u?b.items:[],$=N.findIndex(xe=>xe.id===y.id),Z=wn(N[$],y),oe=$>=0?N.map((xe,be)=>be===$?Z:xe):[...N,Z];return{turnId:u,items:oe,updatedAt:new Date().toISOString()}})},[]),Ts=n.useCallback((u,y,b,N,$)=>{U(Z=>{const oe=(Z==null?void 0:Z.turnId)===u?Z.items:[],xe=oe.find(Se=>Se.id===y),be=(xe==null?void 0:xe.kind)==="agentMessage"?{...xe,text:`${xe.text}${b}`,sequence:N??xe.sequence??null}:{id:y,createdAt:$??new Date().toISOString(),kind:"agentMessage",text:b,sequence:N},W=oe.findIndex(Se=>Se.id===y),Ie=W>=0?oe.map((Se,Ee)=>Ee===W?be:Se):[...oe,be];return{turnId:u,items:Ie,updatedAt:new Date().toISOString()}})},[]),Fe=n.useCallback(()=>{o.current="",i.current!==null&&(window.cancelAnimationFrame(i.current),i.current=null)},[]),Es=n.useCallback(u=>{const y=z.current,b=y&&Object.keys(y).length>0?{...u,thread:{...u.thread,...y}}:u,N={...b,turns:rd(b.turns,ee.current)},$=E.current;E.current=N,de(N.livePlan??null);const Z=$?Ye($.turns,N.turns):N.turns;U(W=>id(W,N.liveItems??null,Z)),ya(W=>W.status==="idle"?W:{...W,data:N.goal??null});const oe=N.thread.activeTurnId===null&&N.thread.status!=="running";P(W=>W&&!N.goalHistory?{...N,turns:Ye(W.turns,N.turns),pendingRequests:wr(W.pendingRequests,N.pendingRequests,Q.current),...W.goalHistory?{goalHistory:W.goalHistory}:{}}:W?{...N,turns:Ye(W.turns,N.turns),pendingRequests:wr(W.pendingRequests,N.pendingRequests,Q.current)}:N),m(W=>Tt(W,N.thread));const xe=new Map(N.turns.map(W=>[W.id,W])),be=new Set((N.pendingSteers??[]).map(W=>W.clientRequestId).filter(W=>!!W));it(W=>W.filter(Ie=>{if(be.has(Ie.clientRequestId))return!1;const Se=xe.get(Ie.turnId);return!(!Se||St(Se,Ie.prompt)||N.thread.activeTurnId!==Ie.turnId&&Se.status!=="inProgress")})),_e(W=>{if(!W)return W;const Ie=W.serverTurnId??W.id,Se=N.turns.some(F=>F.id===Ie),Ee=xe.get(Ie)??null,j=fd(N.turns,W.prompt),O=!!j;if(j&&!W.serverTurnId)return{...W,id:j.id,serverTurnId:j.id,status:W.status==="failed"?W.status:j.status==="inProgress"?"inProgress":W.status};if(Ee&&W.serverTurnId)return St(Ee,W.prompt)||Ct(W.prompt)&&(ta(Ee,W.prompt)||Ra(Ee))?Ee.status==="inProgress"?{...W,id:Ee.id,serverTurnId:Ee.id,status:W.status==="failed"?W.status:"inProgress"}:null:{...W,id:Ee.id,serverTurnId:Ee.id,status:W.status==="failed"?W.status:"inProgress"};if(!W.serverTurnId&&Ct(W.prompt)&&N.thread.activeTurnId&&N.thread.status==="running"){const F=xe.get(N.thread.activeTurnId);if(F&&Ra(F))return{...W,id:F.id,serverTurnId:F.id,status:W.status==="failed"?W.status:"inProgress"}}return Se||oe&&O?null:W}),(oe||L.current&&N.turns.some(W=>W.id===L.current))&&(L.current=null,Fe(),G(""),de(null),U(null))},[Fe]);n.useEffect(()=>{E.current=c},[c]);const Is=n.useCallback(async({seedThread:u}={})=>{var oe;const y=_.current+1;_.current=y;const b=(u==null?void 0:u.provider)??((oe=E.current)==null?void 0:oe.thread.provider)??"codex",[N,$,Z]=await Promise.allSettled([Ka(),nn(b),ea(b)]);_.current===y&&(N.status==="fulfilled"?m(u?Tt(N.value,u):N.value):u&&m(xe=>Tt(xe,u)),$.status==="fulfilled"&&(D.current=b,he($.value.status),B($.value.capabilities),ue($.value.managementSchema)),Z.status==="fulfilled"&&(D.current=b,I(Z.value)))},[]),ct=n.useCallback(async({showLoading:u=!0,clearError:y=!0,reportError:b=!0,limit:N=Cr}={})=>{const $=q.current+1;q.current=$,u&&ae(!0),y&&re(null);try{const Z=await ir(t,{limit:N});if(q.current!==$)return;Es(Z),D.current!==Z.thread.provider&&Is({seedThread:Z.thread})}catch(Z){if(q.current!==$||!b)return;re(Z instanceof Error?Z.message:"Unable to load thread detail.")}finally{q.current===$&&ae(!1)}},[Es,t,Is]),Te=n.useCallback(()=>{var xe;const u=((xe=d.current)==null?void 0:xe.readyState)??Kt,y=u===ht,b=S.current,N=Date.now(),$=C.current!==null&&N-Date.parse(C.current)<=Pa,Z=h.current!==null&&N-h.current<=Pa;let oe;b?y&&Z?oe="connected":u===Oa||f.current!==null||$||Z||g.current?oe="reconnecting":oe="checking":oe="offline",cs(be=>be.status===oe&&be.browserOnline===b&&be.healthOk===$&&be.socketOpen===y&&be.lastHealthyAt===C.current?be:{status:oe,browserOnline:b,healthOk:$,socketOpen:y,lastHealthyAt:C.current})},[]);n.useEffect(()=>{q.current+=1,_.current+=1,P(null),re(null),ae(!0),pa({prompt:"",attachments:[]}),x(!1),Ut("idle"),_e(null),it([]),U(null),z.current=null,L.current=null,Q.current=new Set,C.current=null,h.current=null,k.current=!1,S.current=typeof navigator>"u"?!0:navigator.onLine,cs({status:S.current?"checking":"offline",browserOnline:S.current,healthOk:!1,socketOpen:!1,lastHealthyAt:null})},[t,ys]),n.useEffect(()=>{if(at==="idle")return;const u=window.setTimeout(()=>{Ut("idle")},at==="copied"?1200:1600);return()=>{window.clearTimeout(u)}},[at]),n.useEffect(()=>{if(typeof document>"u")return;const{documentElement:u,body:y}=document;return u.classList.add("thread-detail-scroll-locked"),y.classList.add("thread-detail-scroll-locked"),()=>{u.classList.remove("thread-detail-scroll-locked"),y.classList.remove("thread-detail-scroll-locked")}},[]),n.useEffect(()=>{ct({showLoading:!0,limit:Cr})},[ct]),n.useEffect(()=>{let u=!1,y=null;const b=()=>{ct({showLoading:!1,clearError:!1,reportError:!1})},N=()=>{f.current!==null&&(window.clearTimeout(f.current),f.current=null)},$=()=>{u||!S.current||f.current!==null||(f.current=window.setTimeout(()=>{f.current=null,!u&&be()},kd),Te())},Z=()=>{const j=d.current;if(d.current=null,j)try{j.close()}catch{}},oe=j=>{if(j.threadId===t){if(j.type==="thread.output.delta"&&typeof j.payload.delta=="string"){const O=typeof j.payload.turnId=="string"?j.payload.turnId:null,F=typeof j.payload.itemId=="string"?j.payload.itemId:null,ge=typeof j.payload.sequence=="number"&&Number.isFinite(j.payload.sequence)?j.payload.sequence:null;O&&F?Ts(O,F,j.payload.delta,ge,j.payload.createdAt??j.timestamp):Ss(j.payload.delta),O&&_e(ce=>ce&&(ce.serverTurnId===null||ce.serverTurnId===O)?{...ce,serverTurnId:O,id:O,status:ce.status==="failed"?ce.status:"inProgress",tokenUsage:ce.tokenUsage}:ce)}if(j.type==="thread.context.updated"){const O=j.payload.contextUsage&&typeof j.payload.contextUsage=="object"?j.payload.contextUsage:null;if(O){const F=O;P(ge=>ge&&{...ge,thread:{...ge.thread,contextUsage:F}}),m(ge=>ge.map(ce=>ce.id===t?{...ce,contextUsage:F}:ce))}}if(j.type==="thread.turn.token.updated"&&typeof j.payload.turnId=="string"&&j.payload.tokenUsage&&typeof j.payload.tokenUsage=="object"){const O=j.payload.turnId,F=j.payload.tokenUsage,ge=j.payload.priceEstimate&&typeof j.payload.priceEstimate=="object"?j.payload.priceEstimate:null;P(ce=>{if(!ce)return ce;const wt=xd(ce.turns,O,F,ge);return wt===ce.turns?ce:{...ce,turns:wt}}),_e(ce=>ce&&(ce.serverTurnId===O||ce.id===O)?{...ce,tokenUsage:F,priceEstimate:ge}:ce)}if(j.type==="thread.turn.started"||j.type==="thread.turn.completed"||j.type==="thread.turn.failed"||j.type==="thread.updated"||j.type==="thread.goal.updated"||j.type==="thread.goal.cleared"||j.type==="thread.request.created"||j.type==="thread.request.resolved"){if(j.type==="thread.goal.updated"){const O=j.payload.goal&&typeof j.payload.goal=="object"?j.payload.goal:null,F=Array.isArray(j.payload.goalHistory)?j.payload.goalHistory:null;ya({status:"ready",data:O,error:null}),P(ge=>ge&&(F?{...ge,goal:O,goalHistory:F}:O?{...ge,goal:O,goalHistory:ca(ge.goalHistory??[],O)}:{...ge,goal:O}))}if(j.type==="thread.goal.cleared"){const O=Array.isArray(j.payload.goalHistory)?j.payload.goalHistory:null;ya({status:"ready",data:null,error:null}),P(F=>F&&(O?{...F,goal:null,goalHistory:O}:{...F,goal:null}))}if(b(),j.type==="thread.turn.started"){Fe(),G(""),U(null),L.current=null;const O=typeof j.payload.turnId=="string"?j.payload.turnId:null;O&&_e(F=>F&&{...F,serverTurnId:O,id:O,status:F.status==="failed"?F.status:"inProgress",error:null,tokenUsage:F.tokenUsage})}if(j.type==="thread.turn.completed"||j.type==="thread.turn.failed"){Fe(),G("");const O=typeof j.payload.turnId=="string"?j.payload.turnId:null;O&&(L.current=O,j.type==="thread.turn.failed"&&_e(F=>F&&(F.serverTurnId===O||F.id===O)?{...F,status:"failed",error:typeof j.payload.error=="string"?j.payload.error:"Unable to complete the turn.",tokenUsage:F.tokenUsage}:F))}}if(j.type==="thread.request.created"&&ld(j.payload.request)&&(Q.current.delete(j.payload.request.id),P(O=>O&&nd(O,j.payload.request))),j.type==="thread.request.resolved"&&typeof j.payload.requestId=="string"){const O=j.payload.requestId;Q.current.add(O),P(F=>F&&od(F,O))}if((j.type==="thread.item.started"||j.type==="thread.item.completed")&&j.payload.item&&typeof j.payload.item=="object"&&typeof j.payload.turnId=="string"){const O=j.payload.turnId,F=j.payload.item;typeof F.id=="string"&&typeof F.text=="string"&&Cs(O,F)}j.type==="thread.plan.updated"&&Array.isArray(j.payload.plan)&&de({turnId:String(j.payload.turnId??""),explanation:typeof j.payload.explanation=="string"?j.payload.explanation:null,plan:j.payload.plan})}},xe=()=>{const j=d.current;if(!(!j||j.readyState!==ht))try{j.send(JSON.stringify({type:"supervisor.ping",timestamp:new Date().toISOString()}))}catch{k.current=!0,Z(),$(),Te()}},be=()=>{var F;if(u||!S.current){Te();return}const j=((F=d.current)==null?void 0:F.readyState)??Kt;if(j===Oa||j===ht){Te();return}const O=mn(oe);d.current=O,Te(),O.addEventListener("message",ge=>{if(d.current===O)try{const ce=JSON.parse(ge.data);(ce.type==="supervisor.connected"||ce.type==="supervisor.pong")&&(h.current=Date.now(),Te())}catch{}}),O.addEventListener("open",()=>{d.current===O&&(k.current=!0,b(),xe(),Te())}),O.addEventListener("close",()=>{d.current===O&&(d.current=null),k.current=!0,$(),Te()}),O.addEventListener("error",()=>{d.current===O&&(d.current=null),k.current=!0,$(),Te()})},W=async()=>{var j;if(!(u||!S.current||g.current)){g.current=!0,Te();try{await Rl();const O=k.current;C.current=new Date().toISOString(),O&&(k.current=!1,b()),(((j=d.current)==null?void 0:j.readyState)??Kt)!==ht&&be()}catch{C.current=null,k.current=!0,$()}finally{g.current=!1,Te()}}},Ie=()=>{S.current=!0,k.current=!0,Te(),be(),W()},Se=()=>{S.current=!1,C.current=null,h.current=null,k.current=!0,N(),Z(),Te()},Ee=()=>{var F;if(u||!S.current){Te();return}const j=((F=d.current)==null?void 0:F.readyState)??Kt,O=h.current===null?null:Date.now()-h.current;j===ht&&O!==null&&O>Pa?(k.current=!0,Z(),$()):j===ht?xe():j!==Oa&&be(),W(),Te()};return window.addEventListener("online",Ie),window.addEventListener("offline",Se),be(),W(),y=window.setInterval(Ee,Sd),()=>{u=!0,window.removeEventListener("online",Ie),window.removeEventListener("offline",Se),N(),y!==null&&window.clearInterval(y),Fe(),Z()}},[Ts,Fe,t,ct,Ss,Te,Cs]),n.useEffect(()=>{if(!((c==null?void 0:c.thread.activeTurnId)!==null||(c==null?void 0:c.thread.status)==="running"||le!==null||Dt.length>0||Y.length>0||me!==null||Ce!==null))return;const y=window.setInterval(()=>{ct({showLoading:!1,clearError:!1,reportError:!1})},Cd);return()=>{window.clearInterval(y)}},[c==null?void 0:c.thread.activeTurnId,c==null?void 0:c.thread.status,Y.length,Ce,me,ct,Dt.length,le]);const As=n.useCallback(async()=>{var u;if(!(!c||c.turns.length===0||Oe)){x(!0),re(null);try{const y=(u=c.turns[0])==null?void 0:u.id,b=await ir(t,{limit:Nd,...y?{beforeTurnId:y}:{}});P(N=>N?{...b,turns:sd(N.turns,b.turns)}:b),m(N=>N.map($=>$.id===b.thread.id?b.thread:$))}catch(y){re(y instanceof Error?y.message:"Unable to load earlier turns.")}finally{x(!1)}}},[c,t,Oe]);async function Rs(u){var Ie,Se,Ee;if(V==="shell"){if((c==null?void 0:c.thread.isLoaded)===!1)return await ja({attachShell:!0}),!1;let j=!1;if((se==null?void 0:se.shellInputEnabled)!==!0&&((se==null?void 0:se.loading)===!1&&(se==null?void 0:se.isConnecting)!==!0&&(se==null?void 0:se.status)!=="creating"&&(se==null?void 0:se.status)!=="workspace_missing"&&(await((Ie=p.current)==null?void 0:Ie.toggleConnection()),j=!0),(se==null?void 0:se.isConnecting)===!0))return re("Connecting to the shell. Try again after it attaches."),!1;if(((Se=p.current)==null?void 0:Se.sendCommand(u.prompt))??!1)re(null);else return re(j?"Shell is still attaching. Try again after it connects.":"Connect the shell before sending commands."),!1;return!0}if(vt)return re(vt),!1;M(!0),re(null),A(j=>j+1);const y=E.current,b=y?{...y.thread,...z.current??{}}:null,N=(b==null?void 0:b.model)??null,$=(b==null?void 0:b.reasoningEffort)??null,Z=hd(),oe=`optimistic-${Date.now()}`,xe=`optimistic-steer-${Z}`,be=new Date().toISOString();let W=[];try{let j=E.current;if(j&&!j.thread.isLoaded){const ye={...j.thread,...z.current??{}},De=await dr(t,{...j.thread.model?{model:j.thread.model}:{}}),Pe={...De,thread:{...De.thread,model:ye.model??De.thread.model,reasoningEffort:ye.reasoningEffort??De.thread.reasoningEffort,collaborationMode:ye.collaborationMode??De.thread.collaborationMode}};j=Pe,E.current=Pe,P(Gt=>Gt?{...Pe,turns:Ye(Gt.turns,Pe.turns)}:Pe),m(Gt=>Gt.map(sr=>sr.id===Pe.thread.id?Pe.thread:sr))}const O=j?{...j.thread,...z.current??{}}:null,F=(O==null?void 0:O.status)==="running"?O.activeTurnId:null,ge=V==="chat"&&!!F;ge&&F?it(ye=>[...ye,{id:xe,clientRequestId:Z,turnId:F,prompt:u.prompt,createdAt:be,status:"steering"}]):(W=Ir(u.attachments),Fe(),G(""),_e({id:oe,serverTurnId:null,startedAt:be,status:"sending",error:null,prompt:u.prompt,attachmentPreviews:W,model:N,reasoningEffort:$,reasoningEffortAvailable:jr(H,N),tokenUsage:null,priceEstimate:null}));const ce={prompt:u.prompt,clientRequestId:Z,...O!=null&&O.model?{model:O.model}:{},...O!=null&&O.reasoningEffort?{reasoningEffort:O.reasoningEffort}:{},...O!=null&&O.collaborationMode?{collaborationMode:O.collaborationMode}:{},...(Ee=u.attachments)!=null&&Ee.length?{attachments:u.attachments}:{}},wt=await ei(t,ce),Me=z.current&&Object.keys(z.current).length>0?{...wt,...z.current}:wt;P(ye=>ye&&{...ye,thread:Me}),m(ye=>ye.map(De=>De.id===Me.id?Me:De)),ge&&F?Me.activeTurnId!==null&&Me.activeTurnId!==F&&Me.lastTurnStartedAt!==(O==null?void 0:O.lastTurnStartedAt)?(W=Ir(u.attachments),Fe(),G(""),de(null),it(De=>De.filter(Pe=>Pe.id!==xe)),_e({id:oe,serverTurnId:Me.activeTurnId,startedAt:Me.lastTurnStartedAt??be,status:"inProgress",error:null,prompt:u.prompt,attachmentPreviews:W,model:N,reasoningEffort:$,reasoningEffortAvailable:jr(H,N),tokenUsage:null,priceEstimate:null})):it(De=>De.map(Pe=>Pe.id===xe?{...Pe,turnId:Me.activeTurnId??Pe.turnId,status:"accepted"}:Pe)):(_e(ye=>ye&&ye.id===oe?{...ye,id:Me.activeTurnId??ye.id,serverTurnId:Me.activeTurnId??ye.serverTurnId,status:"inProgress",error:null,tokenUsage:ye.tokenUsage,priceEstimate:ye.priceEstimate}:ye),de(null)),pa({prompt:"",attachments:[]})}catch(j){const O=j instanceof te?j.payload.message:j instanceof Error?j.message:"Unable to send prompt.";j instanceof te?re(j.payload.message):re(O),it(F=>F.filter(ge=>ge.clientRequestId!==Z)),_e(F=>F&&F.id===oe?{...F,status:"failed",error:O}:F)}finally{M(!1)}}async function eo(){const u=c==null?void 0:c.thread.providerSessionId;if(u)try{await navigator.clipboard.writeText(u),Ut("copied")}catch{Ut("failed")}}async function ja(u){if(c){M(!0),re(null),Fe(),G("");try{if(c.thread.isLoaded){const b=await Ql(t);P(N=>N?{...b,turns:Ye(N.turns,b.turns)}:b),rs(null),m(N=>N.map($=>$.id===b.thread.id?b.thread:$)),gt(!1);return}const y=await dr(t,{...c.thread.model?{model:c.thread.model}:{}});P(b=>b?{...y,turns:Ye(b.turns,y.turns)}:y),m(b=>b.map(N=>N.id===y.thread.id?y.thread:N)),u!=null&&u.attachShell&&V==="shell"&&gt(!0)}catch(y){re(y instanceof Error?y.message:"Unable to change connection state.")}finally{M(!1)}}}async function Wt(){var u;if(V==="shell"){const y=((u=p.current)==null?void 0:u.sendControl("ctrl_c"))??!1;re(y?null:"Connect the shell before sending Ctrl-C.");return}M(!0),re(null);try{const y=c!=null&&c.thread.activeTurnId?await cr(t,{turnId:c.thread.activeTurnId}):await cr(t);P(b=>b&&{...b,thread:y}),m(b=>b.map(N=>N.id===y.id?y:N)),Fe(),G("")}catch(y){re(y instanceof Error?y.message:"Unable to interrupt turn.")}finally{M(!1)}}async function Na(u){if(!c)return;const y=c,b={...z.current??{},...u.model!==void 0?{model:u.model}:{},...u.reasoningEffort!==void 0?{reasoningEffort:u.reasoningEffort}:{},...u.fastMode!==void 0?{fastMode:u.fastMode}:{},...u.collaborationMode!==void 0?{collaborationMode:u.collaborationMode}:{}},N={...c.thread,...b};os(!0),z.current=b,E.current={...c,thread:N},P($=>$&&{...$,thread:N}),m($=>$.map(Z=>Z.id===N.id?{...Z,...N}:Z));try{const $=await ai(t,{...u.model!==void 0?{model:u.model}:{},...u.reasoningEffort!==void 0?{reasoningEffort:u.reasoningEffort}:{},...u.fastMode!==void 0?{fastMode:u.fastMode}:{},...u.collaborationMode!==void 0?{collaborationMode:u.collaborationMode}:{}});z.current=null,E.current=y?{...y,thread:$}:null,P(Z=>Z&&{...Z,thread:$}),m(Z=>Z.map(oe=>oe.id===$.id?$:oe))}catch($){z.current=null,E.current=y,P(y),m(Z=>Z.map(oe=>oe.id===y.thread.id?y.thread:oe)),re($ instanceof Error?$.message:"Unable to update thread settings.")}finally{os(!1)}}const Ps=n.useCallback(async(u,y)=>{if((ne==null?void 0:ne.kind)==="shared"&&ne.threadAccess==="read"){re("This shared session is view only.");return}ds(u),re(null);try{const b=await fi(t,u,y);P(N=>N?{...b,turns:Ye(N.turns,b.turns)}:b),de(b.livePlan??null),U(b.liveItems??null)}catch(b){re(b instanceof Error?b.message:"Unable to answer this request.")}finally{ds(null)}},[t]),Os=n.useCallback(u=>Hl(t,u),[t]),Ls=n.useCallback(async(u,y)=>{re(null);try{const b=await ti(u,y);P(N=>N?{...b,turns:Ye(N.turns,b.turns)}:b),m(N=>N.map($=>$.id===b.thread.id?b.thread:$))}catch(b){throw re(b instanceof Error?b.message:"Unable to cancel queued prompt."),b}},[]);async function ka(){if(c){ls(!0),re(null);try{const u=await si(t);P(y=>y&&{...y,thread:u}),m(y=>y.map(b=>b.id===u.id?u:b))}catch(u){re(u instanceof Error?u.message:"Unable to compact this thread context.")}finally{ls(!1)}}}async function Us(u,y){try{const b=await cn(u,{title:y});m(N=>N.map($=>$.id===b.id?{...$,title:b.title,updatedAt:b.updatedAt}:$)),P(N=>N&&N.thread.id===b.id?{...N,thread:{...N.thread,title:b.title,updatedAt:b.updatedAt}}:N)}catch(b){throw re(b instanceof Error?b.message:"Unable to rename thread."),b}}async function Ds(){if(Be){us(!0),re(null);try{await un(Be.id),m(y=>y.filter(b=>b.id!==Be.id));const u=Be.id===(c==null?void 0:c.thread.id);if(fa(null),u){const y=K.find(b=>b.id!==Be.id&&b.workspaceId===(c==null?void 0:c.thread.workspaceId))??K.find(b=>b.id!==Be.id);s(y?Ue(y.id):Et())}}catch(u){re(u instanceof Error?u.message:"Unable to delete thread.")}finally{us(!1)}}}function $s(){fe(u=>u==="chat"?(c!=null&&c.thread.isLoaded&&gt(!0),"shell"):"chat")}async function Ms(){var y;const u=await((y=p.current)==null?void 0:y.copyLastCommandOutput());re(u?null:"Unable to copy the last shell command output.")}function Hs(u){var b,N;const y=u==="clear"?((b=p.current)==null?void 0:b.sendCommand("clear"))??!1:((N=p.current)==null?void 0:N.sendControl(u))??!1;re(y?null:"Connect the shell before sending control input.")}n.useEffect(()=>{if(!(!ns||V!=="shell"||!p.current||(c==null?void 0:c.thread.isLoaded)===!1||(se==null?void 0:se.loading)!==!1)){if((se==null?void 0:se.status)==="attached"){gt(!1);return}gt(!1),p.current.toggleConnection()}},[V,c==null?void 0:c.thread.isLoaded,ns,se==null?void 0:se.loading,se==null?void 0:se.status]),n.useEffect(()=>{if(V!=="shell")return;const u=window.requestAnimationFrame(()=>{var y;(y=p.current)==null||y.refreshLayout({syncBackendSize:!1})});return()=>{window.cancelAnimationFrame(u)}},[V]);const vt=c?c.workspacePathStatus==="missing"?"Restore this workspace path on the current machine before continuing.":st&&_t.status==="loading"?"Checking relay permissions...":st&&_t.status==="failed"?_t.error??"Unable to verify relay permissions.":(ne==null?void 0:ne.kind)==="shared"&&ne.threadAccess==="read"?"This shared session is view only.":null:null,{floatingMobileComposerBottomOffset:to,timelineBottomSpacer:_s,useFloatingMobileComposer:ao}=gd({activeView:V,composerHostRef:v,threadId:(c==null?void 0:c.thread.id)??t}),so=c?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:c.thread.providerSessionId??"Unavailable"}),c.thread.providerSessionId&&e.jsx("button",{type:"button","aria-label":"Copy session ID",title:at==="copied"?"Copied":at==="failed"?"Copy failed":"Copy session ID",onClick:()=>void eo(),className:`thread-mobile-hit-target absolute bottom-0 right-0 inline-flex h-5 w-5 items-center justify-center rounded-full border shadow-sm shadow-stone-950/25 backdrop-blur transition ${at==="copied"?"ui-status-info":at==="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(Ld,{})})})]}),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:c.thread.source==="local_codex_import"?`Imported local ${c.thread.provider} session`:`${c.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:wo(c.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:Sa(c.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:c.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:c.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:c.thread.activeTurnId??"None"})]})]}):null,ro=null,Bs=(le==null?void 0:le.serverTurnId)??null,Ws=le&&c?c.turns.find(u=>(St(u,le.prompt)||Ct(le.prompt)&&(ta(u,le.prompt)||Ra(u)))&&(Bs&&u.id===Bs||u.id===le.id||St(u,le.prompt)||Ct(le.prompt)&&ta(u,le.prompt)))??null:null,Fs=n.useMemo(()=>le&&!Ws?{id:le.id,startedAt:le.startedAt,status:le.status,error:le.error,model:le.model,reasoningEffort:le.reasoningEffort,reasoningEffortAvailable:le.reasoningEffortAvailable,tokenUsage:le.tokenUsage,priceEstimate:le.priceEstimate,items:[{id:`${le.id}-user-message`,kind:"userMessage",text:le.prompt,attachmentPreviewUrls:Object.fromEntries(le.attachmentPreviews.map(u=>[u.path,u.url]))}]}:null,[Ws,le]),yt=(c==null?void 0:c.thread.isLoaded)??!1,Ft=yt?Ke.status==="connected"?"ui-action-success shadow-lg shadow-stone-950/20":Ke.status==="reconnecting"?"thread-live-connection-reconnecting ui-status-success shadow-lg shadow-stone-950/20":Ke.status==="offline"?"ui-status-danger shadow-lg shadow-stone-950/20":"ui-status-warning shadow-lg shadow-stone-950/20":"host-icon-button border shadow-lg shadow-black/10",qs=Dd(yt,Ke),qt=[qs,yt?null:"Tap to connect this thread",Ke.lastHealthyAt?`Last healthy ${Sa(Ke.lastHealthyAt)}`:null].filter(Boolean).join(" · "),zs=yt?e.jsx("div",{role:"status","aria-live":"polite","aria-label":qs,title:qt,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition ${Ft}`,children:e.jsx(Zt,{status:Ke.status})}):e.jsx("button",{type:"button",onClick:()=>void ja(),disabled:w||!c,"aria-label":w?"Connecting thread":"Connect thread",title:w?"Connecting thread":qt,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition ${Ft}`,children:e.jsx(Zt,{status:"detached"})}),Vs=yt?e.jsx("div",{title:qt,className:`hidden lg:inline-flex h-9 w-9 items-center justify-center rounded-full transition ${Ft}`,children:e.jsx(Zt,{status:Ke.status})}):e.jsx("button",{type:"button",onClick:()=>void ja(),disabled:w||!c,title:w?"Connecting thread":qt,className:`hidden lg:inline-flex h-9 w-9 items-center justify-center rounded-full transition ${Ft}`,children:e.jsx(Zt,{status:"detached"})}),Gs=Mt.data??(c==null?void 0:c.goal)??null,Js=(c==null?void 0:c.goalHistory)??[],Ks=Gs?ca(Js,Gs):jn(Js),Ys=(pe==null?void 0:pe.controls.goals)??!1,no=e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-none stroke-current",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"8",cy:"8",r:"5.5"}),e.jsx("circle",{cx:"8",cy:"8",r:"2"}),e.jsx("path",{d:"M8 1.7v2M8 12.3v2M1.7 8h2M12.3 8h2"})]}),oo=Un&&Ys?e.jsxs("div",{className:"host-dialog w-96 max-w-[calc(100vw-1.5rem)] rounded-3xl border p-3 text-left shadow-2xl shadow-black/20 backdrop-blur-xl",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"host-page-title text-sm font-semibold",children:"Goal monitor"}),e.jsx("p",{className:"host-muted text-xs",children:"Current thread only"})]}),e.jsx("button",{type:"button",onClick:()=>bs(!1),className:"host-secondary-button rounded-full border px-2.5 py-1 text-xs transition",children:"Close"})]}),Mt.error?e.jsx("p",{className:"host-error mt-3 rounded-2xl border px-3 py-2 text-xs",children:Mt.error}):null,e.jsx("div",{className:"mt-3 max-h-[28rem] space-y-2 overflow-auto pr-1",children:Ks.length===0?e.jsx("p",{className:"host-empty-state rounded-2xl border px-3 py-3 text-sm",children:"No goals in this thread yet."}):Ks.map(u=>{const y=`${u.threadId}:${u.objective}:${u.createdAt}`,b=On.has(y),N=["active","paused","budgetLimited"].includes(u.status);return e.jsxs("div",{className:`rounded-2xl border px-3 py-3 ${N?"ui-status-info":"host-surface-strong"}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("button",{type:"button",onClick:()=>Yn($=>{const Z=new Set($);return Z.has(y)?Z.delete(y):Z.add(y),Z}),className:"min-w-0 flex-1 text-left",children:e.jsx("p",{className:`text-sm font-medium leading-5 ${b?"":"line-clamp-2"}`,children:u.objective})}),e.jsx("span",{className:"host-muted shrink-0 rounded-full border border-[var(--theme-border)] px-2 py-1 text-[10px] uppercase tracking-[0.14em]",children:u.status})]}),e.jsxs("div",{className:"host-muted mt-2 flex flex-wrap gap-2 text-[11px]",children:[e.jsx("span",{children:md(u.timeUsedSeconds)}),e.jsx("span",{children:ud(u)}),e.jsxs("span",{title:Sa(u.updatedAt),children:["Updated ",new Date(u.updatedAt).toLocaleTimeString()]})]}),N?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",disabled:va||u.status==="active",onClick:()=>void ps("active"),className:"ui-status-info rounded-full px-3 py-1.5 text-xs transition disabled:cursor-not-allowed disabled:opacity-50",children:"Continue"}),e.jsx("button",{type:"button",disabled:va||u.status==="paused",onClick:()=>void ps("paused"),className:"host-secondary-button rounded-full border px-3 py-1.5 text-xs transition disabled:cursor-not-allowed disabled:opacity-50",children:"Pause"}),e.jsx("button",{type:"button",disabled:va,onClick:()=>void Fn(),className:"rounded-full border border-[var(--status-danger-border)] px-3 py-1.5 text-xs text-[var(--status-danger-fg)] transition hover:bg-[var(--status-danger-bg)] disabled:cursor-not-allowed disabled:opacity-50",children:"Terminate"})]}):null]},y)})})]}):null,zt=Ys?e.jsx("button",{type:"button","aria-label":"Open goal monitor",title:"Open goal monitor",onClick:()=>{bs(u=>!u),fs()},className:"ui-status-info inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full shadow-lg shadow-stone-950/20 transition lg:h-9 lg:w-9",children:no}):null,Vt=n.useMemo(()=>(ne==null?void 0:ne.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:`${Tr(ne.threadAccess)} / ${Er(ne.workspaceAccess)}`,children:[e.jsx("span",{children:Tr(ne.threadAccess)}),e.jsx("span",{className:"host-muted",children:"/"}),e.jsx("span",{className:"truncate",children:Er(ne.workspaceAccess)})]}):null,[ne]),lo=n.useMemo(()=>e.jsx("button",{type:"button","aria-label":"Thread actions",title:"Thread actions",onClick:()=>gs(!0),disabled:!c,className:"host-icon-button inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border shadow-lg shadow-black/10 transition disabled:cursor-not-allowed disabled:opacity-50 lg:h-9 lg:w-9",children:e.jsx(Ud,{})}),[c]),io=n.useMemo(()=>e.jsxs("div",{className:"relative flex items-center justify-end gap-1.5",children:[zt,Vt,zs]}),[zt,zs,Vt]),co=n.useMemo(()=>e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[Vt,zt,Vs]}),[Vs,zt,Vt]),uo=n.useMemo(()=>({livePlan:me,liveItems:Ce,respondingRequestId:is,onRespondToRequest:Ps,scrollRequestKey:we,bottomSpacer:_s,className:"thread-timeline-surface min-h-0 flex-1",onTailVisibilityChange:ke,loadingEarlier:Oe,onLoadEarlier:As,onOpenThread:lt,answeredRequestNotes:(c==null?void 0:c.answeredRequestNotes)??Td,activityNotes:(c==null?void 0:c.activityNotes)??Ed,pendingSteers:(c==null?void 0:c.pendingSteers)??Id,optimisticSteers:Dt,optimisticTurn:Fs}),[c==null?void 0:c.answeredRequestNotes,c==null?void 0:c.activityNotes,c==null?void 0:c.pendingSteers,As,Ps,Ce,me,Oe,lt,Dt,is,we,_s,Fs]),Zs=c?{busy:V==="chat"?w:!1,settingsBusy:An,error:null,model:c.thread.model,reasoningEffort:c.thread.reasoningEffort,fastMode:c.thread.fastMode??!1,collaborationMode:c.thread.collaborationMode,sandboxMode:null,modelOptions:H,contextUsage:c.thread.contextUsage,capabilities:pe,toolboxItems:(J==null?void 0:J.toolboxItems)??[],hookCommandTemplates:(J==null?void 0:J.hookCommandTemplates)??[],mcpConfigFormat:(J==null?void 0:J.mcpConfigFormat)??"none",followTail:ve,threadConnected:c.thread.isLoaded,shellAvailable:Je,disabled:!!vt,...vt?{disabledPlaceholder:vt}:{},shellControlState:se,draftPrompt:ss.prompt,draftAttachments:ss.attachments,onDraftChange:pa,canInterrupt:!!(c.thread.activeTurnId&&Le),...Le?{onInterrupt:Wt}:{},...Le?{onCompact:ka,onOpenForkTurns:Hn,onForkLatest:$n,onForkTurn:Mn,onOpenSkills:Wn,onOpenMcp:Bn,onOpenHooks:_n,onCreateHook:Dn,onUpdateHook:Gn,onTrustHook:qn,onUntrustHook:zn}:{},goalState:Mt,...Le?{onOpenGoal:fs,onUpdateGoal:Vn}:{},...ga?{...bt?{onReadProviderConfig:()=>ln(c.thread.provider,ga),onWriteProviderConfig:u=>dn(c.thread.provider,ga,{content:u})}:{}}:{},onToggleFollow:()=>A(u=>u+1),...Le?{onUpdateSettings:Na}:{},onToggleView:$s,onShellCopy:Ms,...Le?{onShellControl:Hs}:{},compactBusy:Rn,skillsState:Zn,mcpState:Kn,hooksState:Jn,forkTurnOptionsState:Ln}:null,Xs=c?{busy:w,settingsBusy:!1,error:c.thread.isLoaded?(se==null?void 0:se.error)??null:null,followTail:!1,capabilities:pe,toolboxItems:(J==null?void 0:J.toolboxItems)??[],hookCommandTemplates:(J==null?void 0:J.hookCommandTemplates)??[],mcpConfigFormat:(J==null?void 0:J.mcpConfigFormat)??"none",threadConnected:c.thread.isLoaded,shellAvailable:Je,shellControlState:se,canInterrupt:!!(c.thread.isLoaded&&(se!=null&&se.isCommandRunning)&&Le),...Le?{onInterrupt:Wt}:{},onToggleView:$s,onShellCopy:Ms,...Le?{onShellControl:Hs}:{}}:null,Qs=n.useCallback(u=>c?as({threadId:c.thread.id,path:u}):"",[c==null?void 0:c.thread.id,as]),er=jd({setError:re,workspaceId:(c==null?void 0:c.workspace.id)??null,access:Qn}),tr=n.useCallback(u=>{const y=E.current;if(!y)return;const b=Od(u.path,y.workspace.absPath);if(b===null){re(`Cannot open ${u.path}; it is outside this workspace.`);return}fe("chat"),Qe(N=>({path:b,...u.line!==void 0?{line:u.line}:{},requestId:((N==null?void 0:N.requestId)??0)+1}))},[]),mo=n.useMemo(()=>({openThread:lt,getThreadHref:et,getNewThreadHref:tt,renderNewThreadDialogContent:ts,...bt?{renameThread:Us}:{},...bt?{deleteThread:fa}:{},cancelPendingSteer:Ls,sendPrompt:Rs,...Le?{interrupt:Wt}:{},...Le?{compact:ka}:{},...Le?{updateSettings:Na}:{},loadHistoryItemDetail:Os,getImageAssetUrl:Qs,openWorkspaceFile:tr,workspace:er,shell:Lt}),[Qs,tt,et,ts,ka,Ls,Wt,Os,tr,Rs,Us,Na,Lt,lt,Le,bt,er]),ho=c!=null&&c.thread.workspaceId?Et(c.thread.workspaceId):Ot(),po=n.useMemo(()=>e.jsxs(e.Fragment,{children:[e.jsx(jo,{open:$t,busy:ba||wa,turnsState:ms,shareAvailable:ws,...st&&(ne==null?void 0:ne.kind)==="shared"?{shareUnavailableMessage:"Only the owner can share this session."}:{},shareState:vs,onCancel:()=>{!ba&&!wa&&gs(!1)},onLoadTurns:xs,onExport:hs,...ws?{onCreateShare:js,onRevokeShare:Ns}:{}}),e.jsx(Ba,{open:Be!==null,title:"Delete Thread",description:Be?`Delete ${Mo(Be.title)} from supervisor. The backend session id will no longer appear in this workspace list.`:"",confirmLabel:"Delete Thread",busy:xa,onCancel:()=>{xa||fa(null)},onConfirm:()=>void Ds()})]}),[Be,xa,ba,$t,ms,js,Ds,hs,Ns,xs,st,wa,vs]);return e.jsx(No,{threads:K,detail:c,status:X,loading:T,error:T?null:Pn,plugins:l,adapter:mo,metaContent:so,settingsContent:ro,globalSettingsContent:e.jsx(Ya,{embedded:!0}),mobileHeaderAction:io,workspaceReturnHref:ho,onCloseAppNavigation:(r==null?void 0:r.closeNav)??(()=>{}),threadActionsButton:lo,surfaceActions:co,floatingPanel:oo,workspaceFeatures:Ad,workspaceFocusPathRequest:Re,activeView:V,liveOutput:Y,timelineProps:uo,timelineComponent:So,useFloatingMobileComposer:ao,floatingMobileComposerBottomOffset:to,composerHostRef:v,shellPanelRef:p,shellPanelComponent:ko,shellEffectiveTheme:(r==null?void 0:r.effectiveTheme)??"dark",shellThemeMode:(r==null?void 0:r.themeMode)??"system",...r!=null&&r.setThemeMode?{onShellThemeModeChange:r.setThemeMode}:{},onShellStateChange:rs,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:po,...Zs?{composerProps:Zs}:{},...Xs?{shellComposerProps:Xs}:{}})}function Rr(){const t=He(),[a,s]=n.useState(""),[r,l]=n.useState(qe),[o,i]=n.useState([]),[d,f]=n.useState(!0),[g,C]=n.useState(!1),[h,S]=n.useState(null);n.useEffect(()=>{let v=!1;return f(!0),sa().then(q=>{var D,L;if(v)return;i(q);const _=((D=q.find(E=>E.isDefault&&E.enabled))==null?void 0:D.provider)??((L=q.find(E=>E.enabled))==null?void 0:L.provider)??qe;l(_)}).catch(()=>{v||i([])}).finally(()=>{v||f(!1)}),()=>{v=!0}},[]);const k=n.useMemo(()=>o.length>0?o:[{provider:qe,displayName:rr[qe].displayName,enabled:!0}],[o]);async function p(v){v.preventDefault();const q=a.trim();if(!q){S("Session ID is required.");return}C(!0),S(null);try{const _=await Kl({sessionId:q,provider:r});t(Ue(_.thread.id))}catch(_){_ instanceof te?S(_.payload.message):S(_ instanceof Error?_.message:"Unable to import session.")}finally{C(!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:p,className:"host-panel space-y-5 rounded-3xl border p-6",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"backend-provider",className:"host-form-label text-sm font-medium",children:"Backend"}),e.jsx("select",{id:"backend-provider",value:r,onChange:v=>l(v.target.value),disabled:g||d,className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:k.map(v=>e.jsxs("option",{value:v.provider,children:[v.displayName||rr[v.provider].displayName,v.enabled?"":" (not ready)"]},v.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:a,onChange:v=>s(v.target.value),placeholder:"019d6fb7-7033-7a30-a2c7-74d0919e87d4",className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"})]}),h&&e.jsx("div",{className:"host-error rounded-2xl border px-4 py-3 text-sm",children:h}),e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:e.jsx("button",{type:"submit",disabled:g,className:"ui-action-primary rounded-full px-5 py-3 font-medium transition disabled:cursor-not-allowed",children:g?"Importing...":"Import Session"})})]})]})}function kn({eyebrow:t,title:a,description:s,children:r,maxWidthClassName:l="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 ${l} overflow-hidden rounded-[1.6rem] border shadow-2xl`,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:a}),s?e.jsx("p",{className:"host-page-description mt-2 max-w-2xl text-sm leading-6",children:s}):null]}),e.jsx("div",{className:"px-5 py-5 sm:px-6",children:r})]})})}function Pr(){const t=He(),[a]=Mr(),s=a.get("workspaceId"),r=a.get("title");function l(){if(window.history.length>1){t(-1);return}if(s){t(Et(s));return}t(Ot())}return e.jsx(kn,{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(es,{initialWorkspaceId:s,initialTitle:r,onCancel:l,onCreated:o=>t(Ue(o.id))})})}function $d(t){return aa(t)}function Md({getThreadHref:t,onOpenThread:a,getNewThreadHref:s,renderThreadLink:r,onCloseAppNavigation:l,...o}){const i=He(),d=ot(),f=l??(d==null?void 0:d.closeNav),g=o.effectiveTheme??(d==null?void 0:d.effectiveTheme),C=o.themeMode??(d==null?void 0:d.themeMode),h=o.onThemeModeChange??(d==null?void 0:d.setThemeMode);return e.jsx(Co,{...o,workspaceReturnHref:o.workspaceReturnHref??Ot(),globalSettingsContent:o.globalSettingsContent??e.jsx(Ya,{embedded:!0}),...g?{effectiveTheme:g}:{},...C?{themeMode:C}:{},...h?{onThemeModeChange:h}:{},getThreadHref:t??(S=>Ue(S)),onOpenThread:a??(S=>i(Ue(S))),getNewThreadHref:s??$d,renderNewThreadDialogContent:o.renderNewThreadDialogContent??(({close:S,closeNavigation:k,currentWorkspaceId:p})=>e.jsx(es,{variant:"dialog",initialWorkspaceId:p,onCancel:S,onCreated:v=>{S(),k(),i(Ue(v.id))}})),renderThreadLink:r??(({thread:S,children:k,className:p,onClick:v})=>e.jsx(ze,{to:Ue(S.id),className:p,onClick:v,children:k})),...f?{onCloseAppNavigation:f}:{}})}function Sn({open:t,title:a,label:s,value:r,busy:l=!1,onChange:o,onCancel:i,onSubmit:d}){if(n.useEffect(()=>{if(!t)return;function g(C){C.key==="Escape"&&!l&&i()}return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[l,i,t]),!t)return null;function f(g){g.preventDefault(),d()}return xo.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:l,className:"ui-overlay-scrim absolute inset-0 backdrop-blur-sm disabled:cursor-not-allowed"}),e.jsxs("form",{role:"dialog","aria-modal":"true","aria-label":a,onSubmit:f,className:"host-dialog relative z-[1] w-full max-w-md rounded-[1.6rem] border p-5 shadow-2xl shadow-black/20 sm:p-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"host-page-title text-sm font-medium",children:a}),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:l,className:"host-icon-button inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full border transition disabled:cursor-not-allowed disabled:opacity-60",children:e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-current",children:e.jsx("path",{d:"M3.22 2.47 8 7.25l4.78-4.78 1.06 1.06L9.06 8.31l4.78 4.78-1.06 1.06L8 9.37l-4.78 4.78-1.06-1.06 4.78-4.78-4.78-4.78 1.06-1.06Z"})})})]}),e.jsxs("div",{className:"mt-5",children:[e.jsx("label",{htmlFor:"rename-dialog-input",className:"host-form-label text-sm font-medium",children:s}),e.jsx("input",{id:"rename-dialog-input","aria-label":s,autoFocus:!0,value:r,onChange:g=>o(g.target.value),className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"})]}),e.jsxs("div",{className:"mt-5 flex items-center justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:i,disabled:l,className:"host-secondary-button rounded-full border px-4 py-2 text-sm font-medium transition disabled:cursor-not-allowed disabled:opacity-60",children:"Cancel"}),e.jsx("button",{type:"submit",disabled:l||!r.trim(),className:"ui-action-success rounded-full px-4 py-2 text-sm font-medium transition disabled:cursor-not-allowed",children:"Save"})]})]})]}),document.body)}function Or(){const[t]=Mr(),a=He(),s=ot(),r=t.get("workspaceId"),[l,o]=n.useState([]),[i,d]=n.useState([]),[f,g]=n.useState(null),[C,h]=n.useState(!0),[S,k]=n.useState(null),[p,v]=n.useState(null),[q,_]=n.useState(""),[D,L]=n.useState(null),[E,z]=n.useState(null),[Q,c]=n.useState(!1),P=(s==null?void 0:s.defaultBackend)??qe,K=n.useCallback(async()=>{h(!0),k(null);try{const[Y,G,me]=await Promise.all([nn(P).then(de=>de.status),Ka(),Ja()]);g(Y),o(G),d(me)}catch(Y){k(Y instanceof Error?Y.message:"Unable to load threads.")}finally{h(!1)}},[P]);n.useEffect(()=>{if(r===null)return;K();const Y=mn(G=>{o(me=>me.map(de=>de.id===G.threadId?{...de,status:G.type==="thread.updated"&&typeof G.payload.status=="string"?G.payload.status:de.status,lastError:(G.type==="thread.turn.failed"||G.type==="thread.turn.completed")&&typeof G.payload.error=="string"?G.payload.error:de.lastError,title:G.type==="thread.updated"&&typeof G.payload.title=="string"?G.payload.title:de.title}:de))});return()=>{Y.close()}},[K,r]);const m=Object.fromEntries(i.map(Y=>[Y.id,Y.label])),H=i.find(Y=>Y.id===r)??null,I=n.useMemo(()=>r?l.filter(Y=>Y.workspaceId===r):[],[r,l]),X=I.filter(Y=>Y.status==="running").length,he=r?aa(r):aa();if(Nn({enabled:r!==null,setThreads:o}),r===null)return e.jsx(ma,{to:Ot(),replace:!0});function pe(){switch(f==null?void 0:f.state){case"ready":return"bg-emerald-400 shadow-[0_0_0_3px_rgba(52,211,153,0.14)]";case"starting":return"bg-amber-300 shadow-[0_0_0_3px_rgba(252,211,77,0.12)]";case"degraded":case"failed":return"bg-rose-400 shadow-[0_0_0_3px_rgba(251,113,133,0.14)]";default:return"bg-stone-500 shadow-[0_0_0_3px_rgba(120,113,108,0.14)]"}}async function B(Y,G){try{const me=await cn(Y,{title:G});o(de=>de.map(Ce=>Ce.id===me.id?{...Ce,title:me.title,updatedAt:me.updatedAt}:Ce))}catch(me){throw k(me instanceof Error?me.message:"Unable to rename thread."),me}}async function J(){if(!p)return;const Y=q.trim();if(Y){L(p);try{await B(p,Y),v(null),_("")}finally{L(null)}}}async function ue(){if(E){c(!0);try{await un(E.id),o(Y=>Y.filter(G=>G.id!==E.id)),z(null)}catch(Y){k(Y instanceof Error?Y.message:"Unable to delete thread.")}finally{c(!1)}}}return e.jsx(Md,{threads:l,workspaceLabels:m,status:f,loading:C,error:S,viewportConstrained:r!==null,showMobileAppMenu:!0,showMobileThreadNavToggle:!1,showMobileNewThreadShortcut:!1,currentWorkspaceId:r,currentWorkspaceLabel:(H==null?void 0:H.label)??null,onRenameThread:B,onDeleteThread:z,children:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"host-panel flex min-h-0 flex-1 flex-col overflow-hidden rounded-[2rem] border shadow-2xl shadow-black/10",children:[e.jsx("div",{className:"border-b border-[var(--theme-border)] px-4 py-3 sm:px-6 sm:py-4",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("h2",{className:"host-page-title min-w-0 truncate text-base font-semibold sm:text-lg",title:H?`${H.label} threads`:"All threads",children:H?H.label:"All Threads"}),e.jsx(ze,{to:he,className:"ui-action-primary inline-flex h-9 shrink-0 items-center rounded-full px-3.5 text-xs font-medium uppercase tracking-[0.18em] transition",children:"New Thread"})]})}),e.jsx("div",{className:"px-4 py-3 sm:px-6 sm:py-4",children:e.jsxs("article",{className:"host-surface-strong inline-flex min-w-[12rem] max-w-full items-center gap-3 rounded-[1.25rem] border px-3.5 py-2.5",children:[e.jsx("span",{"aria-hidden":"true",className:`h-2.5 w-2.5 shrink-0 rounded-full ${pe()}`}),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")})]})]})}),!C&&!S&&I.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:[I.length," total"]}),X>0&&e.jsxs("span",{className:"host-muted text-xs",children:["· ",X," running"]})]}),e.jsx("div",{className:"mt-3 min-h-0 flex-1",children:e.jsx(To,{threads:I,currentWorkspaceId:r,workspaceLabels:m,onOpenThread:Y=>a(Ue(Y)),onBeginRenameThread:Y=>{v(Y.id),_(Y.title)},onDeleteThread:Y=>z(Y),scrollable:!0,maxHeightClassName:"max-h-full",showDeleteButton:!0,showSessionCopyButton:!0})})]}),!C&&!S&&I.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(Sn,{open:p!==null,title:"Rename Thread",label:"Thread Title",value:q,busy:D!==null,onChange:_,onCancel:()=>{v(null),_("")},onSubmit:()=>void J()}),e.jsx(Ba,{open:E!==null,title:"Delete Thread",description:E?`Delete ${Uo(E.title)} from supervisor. The backend session id will no longer appear in this workspace list.`:"",confirmLabel:"Delete Thread",busy:Q,onCancel:()=>{Q||z(null)},onConfirm:()=>void ue()})]})})}function Lr(t){const a=t.trim(),s=a.replace(/[\\/]+$/,"");if(!s)return"";if(Cn(a)){const l=(s.split(/[?#]/)[0]??s).split(/[/:]/).filter(Boolean).at(-1)??"";return l.endsWith(".git")?l.slice(0,-4):l}return s.split(/[\\/]/).filter(Boolean).at(-1)??""}function Cn(t){const a=t.trim();return/^https?:\/\/.+/i.test(a)||/^ssh:\/\/.+/i.test(a)||/^git@[^:]+:.+/.test(a)}function Hd({initialPath:t="",initialLabel:a="",submitLabel:s="Save Workspace",error:r,busy:l=!1,surface:o=!0,onSubmit:i}){const d=Lr(t),[f,g]=n.useState(t),[C,h]=n.useState(a||d),[S,k]=n.useState(null),p=n.useRef(d);n.useEffect(()=>{const _=Lr(f);h(D=>!D.trim()||D===p.current?_:D),p.current=_},[f]);async function v(_){_.preventDefault();const D=f.trim();if(!D){k("Workspace path or Git URL is required.");return}k(null);const L=C.trim(),E=Cn(D)?"gitUrl":"absPath";await i(L?{[E]:D,label:L}:{[E]:D})}const q=o?"host-panel space-y-5 rounded-3xl border p-6":"space-y-5";return e.jsxs("form",{onSubmit:v,className:q,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:_=>g(_.target.value),placeholder:"/Users/name/project or https://github.com/owner/repo.git",className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"}),e.jsx("p",{className:"host-muted mt-2 text-xs",children:"Absolute paths register local directories. Git URLs clone into the configured dev home."})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"workspace-label",className:"host-form-label text-sm font-medium",children:"Display label"}),e.jsx("input",{id:"workspace-label",name:"label",value:C,onChange:_=>h(_.target.value),placeholder:"Optional override",className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"}),e.jsx("p",{className:"host-muted mt-2 text-xs",children:"Defaults to the last folder name. You can override it."})]}),(S||r)&&e.jsx("div",{className:"host-error rounded-2xl border px-4 py-3 text-sm",children:S??r}),e.jsx("button",{type:"submit",disabled:l,className:"ui-action-primary rounded-full px-5 py-3 font-medium transition disabled:cursor-not-allowed",children:l?"Saving...":s})]})}function Ur(){const t=He(),[a,s]=n.useState(null),[r,l]=n.useState(!1);async function o(i){l(!0),s(null);try{const d=await xi(i);t(Et(d.id))}catch(d){d instanceof te?s(d.payload.message):s(d instanceof Error?d.message:"Unable to create workspace.")}finally{l(!1)}}return e.jsx(kn,{eyebrow:"Add Workspace",title:"Create a workspace",description:"Register a local directory, create one missing child directory under dev home, or clone a Git repository into dev home.",children:e.jsx(Hd,{busy:r,error:a,submitLabel:"Create Workspace",surface:!1,onSubmit:o})})}function Dr(t){return Date.parse(t.lastOpenedAt??t.createdAt)}function _d(t,a){return t.isFavorite!==a.isFavorite?t.isFavorite?-1:1:Dr(a)-Dr(t)}function Bd(t){return t?new Date(t).toLocaleString():"Never opened"}function Wd(t,a=28){return t.length<=a?t:`...${t.slice(-(a-3))}`}function Fd({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 qd(){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 $r(){const t=He(),[a,s]=n.useState([]),[r,l]=n.useState(!0),[o,i]=n.useState(null),[d,f]=n.useState(null),[g,C]=n.useState(null),[h,S]=n.useState(null),[k,p]=n.useState(""),[v,q]=n.useState(null),[_,D]=n.useState(null),[L,E]=n.useState(null),[z,Q]=n.useState(!1);async function c(){l(!0),C(null);try{s(await Ja())}catch(B){C(B instanceof Error?B.message:"Unable to load workspaces.")}finally{l(!1)}}n.useEffect(()=>{c(),nl().then(B=>{i(B),f(null)}).catch(B=>{f(B instanceof Error?B.message:"Unable to load supervisor config.")})},[]);async function P(B){const J={...B,isFavorite:!B.isFavorite};s(ue=>ue.map(Y=>Y.id===B.id?J:Y));try{const ue=await vi(B.id,{isFavorite:!B.isFavorite});s(Y=>Y.map(G=>G.id===ue.id?ue:G))}catch(ue){s(Y=>Y.map(G=>G.id===B.id?B:G)),C(ue instanceof Error?ue.message:"Unable to update workspace.")}}async function K(B){const J=k.trim();if(J){q(B);try{const ue=await gi(B,{label:J});s(Y=>Y.map(G=>G.id===ue.id?ue:G)),S(null),p("")}catch(ue){C(ue instanceof Error?ue.message:"Unable to rename workspace.")}finally{q(null)}}}function m(B){S(B.id),p(B.label)}function H(){S(null),p("")}function I(B){t(Et(B))}async function X(){if(L){Q(!0);try{await bi(L.id,{confirmWorkspaceId:L.id,confirmLabel:L.label}),s(B=>B.filter(J=>J.id!==L.id)),E(null)}catch(B){C(B instanceof Error?B.message:"Unable to delete workspace.")}finally{Q(!1)}}}function he(B,J){(B.key==="Enter"||B.key===" ")&&(B.preventDefault(),I(J))}const pe=n.useMemo(()=>[...a].sort(_d),[a]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"host-topbar sticky top-[env(safe-area-inset-top)] z-20 -mx-4 border-b px-2.5 py-2 backdrop-blur sm:mx-0 sm:rounded-[1.4rem] sm:border sm:px-4",children:e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 sm:gap-2",children:[e.jsx(pn,{}),e.jsx(ze,{to:Ua("/threads/import"),className:"host-info-pill inline-flex h-8 shrink-0 items-center rounded-full border px-2.5 text-[11px] font-medium uppercase tracking-[0.14em] transition sm:px-3 sm:text-xs sm:tracking-[0.18em]",children:"Import"}),e.jsx(ze,{to:Ua("/workspaces/new"),className:"ui-action-primary inline-flex h-8 shrink-0 items-center rounded-full px-2.5 text-[11px] font-medium uppercase tracking-[0.14em] transition sm:px-3 sm:text-xs sm:tracking-[0.18em]",children:"Create"}),e.jsx("div",{className:"min-w-0 flex-1 text-right",children:e.jsx("p",{className:"host-page-eyebrow truncate text-[11px] uppercase tracking-[0.24em]",children:"Workspaces"})})]}),e.jsx(fn,{className:"absolute left-0 top-[calc(100%+0.5rem)] z-30 w-[min(22rem,calc(100vw-1rem))]"})]})}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_20rem]",children:[e.jsxs("section",{className:"min-w-0 space-y-4",children:[r&&e.jsx("div",{className:"host-empty-state rounded-[1.6rem] border px-6 py-12 text-center",children:"Loading workspace registry..."}),g&&e.jsx("div",{className:"host-error rounded-[1.4rem] border px-4 py-4",children:g}),!r&&!g&&a.length===0&&e.jsxs("div",{className:"host-empty-state rounded-[1.6rem] border border-dashed px-6 py-12 text-center",children:[e.jsx("p",{className:"host-page-title text-lg font-medium",children:"No workspaces yet"}),e.jsx("p",{className:"host-muted mt-2 text-sm",children:"Add a local directory inside the configured workspace root to start building the registry."})]}),!r&&pe.length>0&&e.jsx("div",{className:"space-y-2 overflow-x-hidden",children:pe.map(B=>e.jsxs("article",{role:"link",tabIndex:0,onClick:()=>I(B.id),onKeyDown:J=>he(J,B.id),className:"host-card relative overflow-hidden rounded-[1.35rem] border px-4 py-3 transition",children:[e.jsxs("div",{className:"absolute right-2.5 top-2.5 flex items-center gap-1.5",children:[e.jsx("button",{type:"button","aria-label":`Delete workspace ${B.label}`,title:"Delete workspace",onClick:J=>{J.stopPropagation(),E(B)},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(qd,{})}),e.jsx("button",{type:"button","aria-label":B.isFavorite?`Unpin workspace ${B.label}`:`Pin workspace ${B.label}`,title:B.isFavorite?"Unpin workspace":"Pin workspace",onClick:J=>{J.stopPropagation(),P(B)},className:`inline-flex h-7 w-7 items-center justify-center rounded-full border transition ${B.isFavorite?"host-warning-pill":"host-icon-button"}`,children:e.jsx(Fd,{active:B.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:B.label,children:B.label}),e.jsx("button",{type:"button",onClick:J=>{J.stopPropagation(),m(B)},"aria-label":`Rename workspace ${B.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":B.absPath,title:B.absPath,onClick:J=>{J.stopPropagation(),D(B.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:Wd(B.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: ",Bd(B.lastOpenedAt)]})})]})})]},B.id))})]}),e.jsx(zd,{config:o,error:d,workspaceCount:a.length})]}),e.jsx(Sn,{open:h!==null,title:"Rename Workspace",label:"Workspace Label",value:k,busy:v!==null,onChange:p,onCancel:H,onSubmit:()=>h?K(h):void 0}),e.jsx(Eo,{open:_!==null,title:"Workspace Path",text:_??"",onClose:()=>D(null)}),e.jsx(Ba,{open:L!==null,title:"Delete Workspace",description:L?`Delete ${L.label} from supervisor. This also removes its threads and local supervisor metadata.`:"",confirmLabel:"Delete Workspace",busy:z,onCancel:()=>{z||E(null)},onConfirm:()=>void X()})]})}function zd({config:t,error:a,workspaceCount:s}){return e.jsxs("aside",{className:"space-y-3 xl:sticky xl:top-[calc(env(safe-area-inset-top)+4.25rem)] xl:self-start",children:[e.jsxs("section",{className:"rounded-[1.2rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-[var(--theme-fg-muted)]",children:"Supervisor"}),e.jsxs("dl",{className:"mt-4 space-y-3",children:[e.jsx(Xt,{label:"Workspace root",value:(t==null?void 0:t.workspaceRoot)??"Loading..."}),e.jsx(Xt,{label:"Environment",value:t?`${t.environment} · ${t.host}:${t.port}`:a??"Loading..."}),e.jsx(Xt,{label:"Version",value:t?`${t.appName} ${t.appVersion}`:"Loading..."}),e.jsx(Xt,{label:"Workspaces",value:String(s)})]})]}),a?e.jsx("section",{className:"rounded-[1.2rem] border border-[var(--status-warning-border)] bg-[var(--status-warning-bg)] p-4 text-sm text-[var(--status-warning-fg)]",children:"Runtime metadata is unavailable. Workspace actions may still work if a relay device is connected."}):null]})}function Xt({label:t,value:a}){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:a})]})}const Tn="remote-codex-theme-mode",En="remote-codex-default-backend",In="remote-codex-auto-collapse-completed-turns";function Vd({children:t}){const a=n.useMemo(()=>({fetchPlugins:_l,importPlugin:Bl,updatePlugin:Wl,deletePlugin:Fl}),[]);return e.jsx(Io,{adapter:a,children:t})}function Gd(){if(typeof window>"u")return"system";const t=window.localStorage.getItem(Tn);return t==="light"||t==="dark"||t==="system"?t:"system"}function Jd(){if(typeof window>"u")return qe;const t=window.localStorage.getItem(En);return Oo(t)??qe}function Kd(){return typeof window>"u"?!0:window.localStorage.getItem(In)!=="false"}function Yd(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Zd({themeMode:t,setThemeMode:a,effectiveTheme:s}){const[r,l]=n.useState(!1),[o,i]=n.useState(!1),[d,f]=n.useState(Jd),[g,C]=n.useState(Kd),h=ua(),k=!(/^\/threads\/(?:import|new)$/.test(h.pathname)||/^\/devices\/[^/]+\/threads\/(?:import|new)$/.test(h.pathname))&&(/^\/threads\/[^/]+$/.test(h.pathname)||/^\/devices\/[^/]+\/threads\/[^/]+$/.test(h.pathname)),p=h.pathname==="/threads"||/^\/devices\/[^/]+\/threads$/.test(h.pathname),v=k||p,q=p||k,_=k,D=h.pathname==="/workspaces"||/^\/devices\/[^/]+\/workspaces$/.test(h.pathname),L=D||p;n.useEffect(()=>{l(!1)},[h.pathname,h.search]);function E(c){f(c),window.localStorage.setItem(En,c)}function z(c){C(c),window.localStorage.setItem(In,c?"true":"false")}const Q={navOpen:r,openNav:()=>l(!0),toggleNav:()=>l(c=>!c),closeNav:()=>l(!1),settingsOpen:o,openSettings:()=>{l(!1),i(!0)},closeSettings:()=>i(!1),themeMode:t,setThemeMode:a,effectiveTheme:s,defaultBackend:d,setDefaultBackend:E,autoCollapseCompletedTurns:g,setAutoCollapseCompletedTurns:z};return e.jsxs(Ao.Provider,{value:Q,children:[e.jsxs("div",{className:`bg-[var(--app-bg)] text-[var(--app-fg)] ${v?"fixed inset-0 overflow-hidden overscroll-none":"min-h-screen"}`,children:[D?e.jsx(xn,{}):null,!L&&!_&&e.jsxs("div",{className:"fixed left-4 top-4 z-50",children:[e.jsx(pn,{}),e.jsx(fn,{className:"mt-3 w-[min(22rem,calc(100vw-2rem))]"})]}),e.jsx("main",{className:`mx-auto w-full ${q?"max-w-none":"max-w-[1600px]"} ${v?"absolute inset-0 pb-0 sm:pb-4":"pb-4"} ${q?k?"pt-0":p?"pt-[env(safe-area-inset-top)] sm:pt-4":"pt-[calc(env(safe-area-inset-top)+4rem)] sm:pt-4":D?"pt-[env(safe-area-inset-top)] sm:pt-4":"pt-4"} ${v?k?"overflow-hidden overscroll-none px-0":"overflow-hidden overscroll-none px-0 sm:px-6":"px-4 sm:px-6"}`,children:e.jsx("section",{className:`min-w-0 ${v?k?"h-full min-h-0 overflow-hidden overscroll-none":"h-full overflow-hidden overscroll-none":""}`,children:e.jsx(bo,{})})})]}),e.jsx(Ya,{})]})}function Xd({children:t}){const[a,s]=n.useState({status:"checking"});async function r(i){try{const d=await ol();if(i!=null&&i())return;s(!d.authRequired||d.authenticated?{status:"authenticated"}:{status:"loginRequired",session:d,error:null})}catch(d){if(i!=null&&i())return;if(d instanceof te&&d.statusCode===401){s({status:"loginRequired",session:{authenticated:!1,username:null,expiresAt:null,mode:"server",authRequired:!0},error:null});return}s({status:"unavailable",error:d instanceof Error?d.message:"Unable to check supervisor access."})}}n.useEffect(()=>{let i=!1;return r(()=>i),()=>{i=!0}},[]);async function l(i){await ll(i),s({status:"authenticated"})}function o(){s({status:"checking"}),r()}return a.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..."}):a.status==="unavailable"?e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-[var(--app-bg)] px-4 text-[var(--app-fg)]",children:e.jsxs("section",{className:"w-full max-w-md rounded-[1.35rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-2xl shadow-[color-mix(in_oklch,var(--app-fg)_14%,transparent)] sm:p-6",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-muted)]",children:"Supervisor Access"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold tracking-normal text-[var(--theme-fg)]",children:"Unable to reach supervisor"}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-[var(--theme-muted)]",children:a.error}),e.jsx("button",{className:"mt-5 h-11 rounded-xl bg-[var(--theme-accent-solid)] px-4 text-sm font-semibold text-[var(--theme-accent-solid-fg)] transition hover:bg-[var(--theme-accent-solid-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--theme-accent-border)]",onClick:o,type:"button",children:"Retry"})]})}):a.status==="loginRequired"?e.jsxs(e.Fragment,{children:[a.error&&e.jsx("div",{className:"fixed left-1/2 top-4 z-50 w-[min(28rem,calc(100vw-2rem))] -translate-x-1/2 rounded-xl border border-[var(--status-warning-border)] bg-[var(--status-warning-bg)] px-3 py-2 text-sm text-[var(--status-warning-fg)]",children:a.error}),e.jsx(gn,{onLogin:l})]}):t}function Qd({children:t}){var r;const[a,s]=n.useState({status:"checking"});return n.useEffect(()=>{let l=!1;return Rt().then(o=>{l||s(o.authenticated?{status:"authenticated",session:o}:{status:"loginRequired"})}).catch(()=>{l||s({status:"loginRequired"})}),()=>{l=!0}},[]),a.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..."}):a.status==="loginRequired"?e.jsx(yn,{}):((r=a.session.user)==null?void 0:r.role)==="admin"?e.jsx(ma,{to:"/relay-admin",replace:!0}):t}function ec({children:t}){return rt()?e.jsx(Qd,{children:t}):e.jsx(Xd,{children:t})}function tc({themeMode:t,setThemeMode:a,effectiveTheme:s}){return e.jsxs(Hr,{children:[e.jsx(je,{path:"/",element:e.jsx(ma,{to:"/workspaces",replace:!0})}),e.jsxs(je,{element:e.jsx(Zd,{themeMode:t,setThemeMode:a,effectiveTheme:s}),children:[e.jsx(je,{path:"/workspaces",element:e.jsx($r,{})}),e.jsx(je,{path:"/workspaces/new",element:e.jsx(Ur,{})}),e.jsx(je,{path:"/relay-account",element:e.jsx(ki,{})}),e.jsx(je,{path:"/relay-devices",element:e.jsx(Fi,{})}),e.jsx(je,{path:"/threads",element:e.jsx(Or,{})}),e.jsx(je,{path:"/threads/import",element:e.jsx(Rr,{})}),e.jsx(je,{path:"/threads/new",element:e.jsx(Pr,{})}),e.jsx(je,{path:"/threads/:id",element:e.jsx(Ar,{})}),e.jsx(je,{path:"/devices/:relayDeviceId/workspaces",element:e.jsx($r,{})}),e.jsx(je,{path:"/devices/:relayDeviceId/workspaces/new",element:e.jsx(Ur,{})}),e.jsx(je,{path:"/devices/:relayDeviceId/threads",element:e.jsx(Or,{})}),e.jsx(je,{path:"/devices/:relayDeviceId/threads/import",element:e.jsx(Rr,{})}),e.jsx(je,{path:"/devices/:relayDeviceId/threads/new",element:e.jsx(Pr,{})}),e.jsx(je,{path:"/devices/:relayDeviceId/threads/:id",element:e.jsx(Ar,{})})]})]})}function ac(){const[t,a]=n.useState(()=>Gd()),[s,r]=n.useState(()=>Yd()),l=t==="system"?s:t;return n.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const o=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>{r(o.matches?"dark":"light")};return i(),typeof o.addEventListener=="function"?o.addEventListener("change",i):o.addListener(i),()=>{typeof o.removeEventListener=="function"?o.removeEventListener("change",i):o.removeListener(i)}},[]),n.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Tn,t)},[t]),n.useEffect(()=>{const o=document.documentElement;o.dataset.themeMode=t,o.dataset.themeEffective=l,o.style.colorScheme=l},[l,t]),e.jsx("div",{className:"theme-shell theme-scrollbar",children:e.jsx(go,{children:e.jsx(Vd,{children:e.jsxs(Hr,{children:[e.jsx(je,{path:"/",element:e.jsx(ma,{to:"/workspaces",replace:!0})}),e.jsx(je,{path:"/relay-portal",element:e.jsx(yn,{})}),e.jsx(je,{path:"/relay-admin",element:e.jsx(Si,{})}),e.jsx(je,{path:"/*",element:e.jsx(ec,{children:e.jsx(tc,{themeMode:t,setThemeMode:a,effectiveTheme:l})})})]})})})})}vo.createRoot(document.getElementById("root")).render(e.jsx(yo.StrictMode,{children:e.jsx(ac,{})}));