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