remote-codex 0.11.21 → 0.11.23

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