remote-codex 0.11.23 → 0.11.24

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