remote-codex 0.11.18 → 0.11.20

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