remote-codex 0.11.25 → 0.11.26

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