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