Skip to content

Commit aa829d5

Browse files
authored
feat(dashboard): Codex CLI update tab over the existing plan/apply/jobs API (#8540)
Adds Codex -> Codex CLI: a read-only Check over the existing plan route, and one explicitly confirmed Apply of exactly the displayed planId, followed to its final job state. Idempotent resend only for busy/admission/network failures; 403 shows local pairing and the CLI command; connected dashboards send nothing. No server change. Closes #2811
1 parent b8548fb commit aa829d5

24 files changed

Lines changed: 867 additions & 8 deletions

‎docs-site/src/content/docs/guides/web-dashboard.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -381,9 +381,11 @@ they have been synchronized. See
381381

382382
In **Connect → API Keys**, every row of the key table has its own delete button, which asks for confirmation in place. Clicking a key can show its full value with a **Copy** button only from an independently authorized session.
383383

384-
### Applying a Codex CLI update over HTTP
384+
### Applying a Codex CLI update from the dashboard
385385

386-
The CLI-update HTTP API has no dashboard job UI. Its apply route requires a current explicitly paired browser session on trusted loopback ingress, matching Origin and CSRF headers, and `confirmed: true`. Automatic local sign-in, a remembered admin session, an admin token or Tailscale sign-in alone cannot authorize this action.
386+
**Codex → Codex CLI** checks and updates the Codex CLI installation OpenCodex uses, separately from OpenCodex's own updates; it never touches the Codex desktop app. **Check for update** is read-only: it shows who installed the CLI, whether OpenCodex manages it, the installed and available versions, running Codex sessions, and why an update is refused (for example a version-manager install, an active session, or already current). An update is offered only for an applicable plan, and **Update Codex CLI** stays disabled until you tick the confirmation that only this installation changes. The dashboard applies exactly the plan on screen, then follows the job to its result (updated, not updated, refused, or unclear). An unclear result is never retried or rolled back; check the installation yourself. Running **Check for update** again discards the previous plan and confirmation. A dashboard connected to a Remote Hub shows a notice instead, because the update must run on the computer that owns the installation.
387+
388+
The apply route requires a current explicitly paired browser session on trusted loopback ingress, matching Origin and CSRF headers, and `confirmed: true`. Automatic local sign-in, a remembered admin session, an admin token or Tailscale sign-in alone cannot authorize this action; when apply is refused for that reason the tab shows the local pairing form and the equivalent `ocx system codex-cli-update apply` command.
387389

388390
For standalone local pairing, open the dashboard at its configured literal `http://127.0.0.1:<port>` or `http://[::1]:<port>` origin. Use the existing local pairing form in **Connect → API Keys** or Remote Link setup: run the displayed `ocx gui pair --origin "<browser-origin>"` command locally, then redeem its one-time code in that form. Pairing does not apply an update; a subsequent confirmed API request is still required. A server configured with hostname `localhost`, a wildcard bind, or a connected-client role cannot issue this local pairing authority. Remote pairing does not remove the apply route's trusted-loopback requirement.
389391

‎docs-site/src/content/docs/reference/cli.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,8 @@ See [planning details](/reference/cli/agents/#read-only-codex-cli-update-plan).
179179
For a reviewed applicable npm-global plan, `ocx system codex-cli-update apply --plan-id <id> --yes`
180180
performs the exact update and returns a durable job. `ocx system codex-cli-update status <job-id> --json`
181181
reads its result; use a stable `--request-id` for a lost-response retry. See
182-
[confirmation and job states](/reference/cli/agents/#confirmed-codex-cli-apply-and-job-status).
182+
[confirmation and job states](/reference/cli/agents/#confirmed-codex-cli-apply-and-job-status). The dashboard's **Codex → Codex CLI** tab uses the
183+
same plan, apply and job routes; see [the dashboard guide](/guides/web-dashboard/#applying-a-codex-cli-update-from-the-dashboard).
183184

184185
For Windows x64 installation observation, see [the `attest` command](/reference/cli/agents/#explicit-installation-observation-on-windows-x64). Without explicit paths it observes the selected candidate identified from the proof-bound launcher snapshot; it does not grant update authority or attest runtime selection.
185186

‎gui/src/app-routing.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ export function hashBelongsToPage(rawHash: string, page: Page): boolean {
180180
|| (page === "logs" && rawHash === "logs/debug")
181181
|| (page === "startup" && rawHash === "startup/desktop")
182182
|| (page === "usage" && rawHash === "usage/companion")
183-
|| (page === "codex-set" && (rawHash === "codex-set/prompt" || rawHash === "codex-set/desktop"))
183+
|| (page === "codex-set" && (rawHash === "codex-set/prompt" || rawHash === "codex-set/desktop" || rawHash === "codex-set/cli"))
184184
|| (page === "models" && (
185185
(MODELS_TAB_HASHES as readonly string[]).includes(rawHash)
186186
|| rawHash === JEV_AUTO_CREATE_HASH

‎gui/src/codex-cli-update-api.ts‎

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
/**
2+
* Dashboard client for the Codex CLI update workflow (#2811). The server owns every decision:
3+
* the read-only plan, the planId it binds, admission, the install and its readback
4+
* (src/server/management/codex-cli-update-routes.ts). This module only reads those DTOs and
5+
* posts the one confirmed request; it never regenerates a plan or retries an ambiguous result.
6+
*/
7+
8+
export type CodexCliProvenance = "npm-global" | "app-bundle" | "version-manager" | "standalone-unverified" | "unknown";
9+
export type CodexCliSessionState = "none" | "active" | "unknown" | "not-evaluated";
10+
export type CodexCliJobStatus = "queued" | "running" | "applied" | "not_applied" | "refused" | "ambiguous";
11+
12+
export interface CodexCliUpdatePlanView {
13+
applicable: boolean;
14+
refusal: string | null;
15+
planId: string | null;
16+
provenance: CodexCliProvenance;
17+
managed: boolean;
18+
installedVersion: string | null;
19+
targetVersion: string | null;
20+
location: string | null;
21+
session: { state: CodexCliSessionState; matches: number | null };
22+
command: readonly string[] | null;
23+
}
24+
25+
export interface CodexCliUpdateJobView {
26+
jobId: string;
27+
status: CodexCliJobStatus;
28+
ownerState: "active" | "unknown" | "finished";
29+
planId: string;
30+
reason: string | null;
31+
}
32+
33+
/** A refused or failed request. `retryable` is true only where the same requestId may be sent again. */
34+
export class CodexCliUpdateError extends Error {
35+
readonly code: string;
36+
readonly status: number;
37+
readonly retryable: boolean;
38+
constructor(code: string, status: number, retryable: boolean) {
39+
super(code);
40+
this.code = code;
41+
this.status = status;
42+
this.retryable = retryable;
43+
}
44+
}
45+
46+
const PROVENANCE = new Set(["npm-global", "app-bundle", "version-manager", "standalone-unverified", "unknown"]);
47+
const SESSION = new Set(["none", "active", "unknown", "not-evaluated"]);
48+
const STATUS = new Set(["queued", "running", "applied", "not_applied", "refused", "ambiguous"]);
49+
const OWNER = new Set(["active", "unknown", "finished"]);
50+
/** Failures after which resending the same request is idempotent: the server returns the job it already admitted, if any, and never admits a second. */
51+
const RETRYABLE_APPLY = new Set(["job_store_busy", "admission_failed", "network"]);
52+
53+
const str = (value: unknown): string | null => typeof value === "string" ? value : null;
54+
55+
export function readPlan(value: unknown): CodexCliUpdatePlanView | null {
56+
if (!value || typeof value !== "object") return null;
57+
const row = value as Record<string, unknown>;
58+
const session = row.session as Record<string, unknown> | undefined;
59+
if (typeof row.applicable !== "boolean" || typeof row.managed !== "boolean"
60+
|| !PROVENANCE.has(row.provenance as string) || !session || !SESSION.has(session.state as string)) return null;
61+
const command = Array.isArray(row.command) && row.command.every(part => typeof part === "string") ? row.command as string[] : null;
62+
return {
63+
applicable: row.applicable, refusal: str(row.refusal), planId: str(row.planId),
64+
provenance: row.provenance as CodexCliProvenance, managed: row.managed,
65+
installedVersion: str(row.installedVersion), targetVersion: str(row.targetVersion), location: str(row.location),
66+
session: { state: session.state as CodexCliSessionState, matches: typeof session.matches === "number" ? session.matches : null },
67+
command,
68+
};
69+
}
70+
71+
export function readJob(value: unknown): CodexCliUpdateJobView | null {
72+
if (!value || typeof value !== "object") return null;
73+
const row = value as Record<string, unknown>;
74+
if (typeof row.jobId !== "string" || !STATUS.has(row.status as string) || !OWNER.has(row.ownerState as string)
75+
|| typeof row.planId !== "string") return null;
76+
return { jobId: row.jobId, status: row.status as CodexCliJobStatus, ownerState: row.ownerState as CodexCliUpdateJobView["ownerState"],
77+
planId: row.planId, reason: str(row.reason) };
78+
}
79+
80+
/** Apply is offered only for an applicable plan with a bound id, after the operator confirmed it. */
81+
export function canApply(plan: CodexCliUpdatePlanView | null, confirmed: boolean): boolean {
82+
return !!plan && plan.applicable && plan.refusal === null && plan.planId !== null && confirmed;
83+
}
84+
85+
/** A job is settled once its status is final and no owner is still writing it. */
86+
export function isTerminalJob(job: CodexCliUpdateJobView): boolean {
87+
return job.status !== "queued" && job.status !== "running" && job.ownerState !== "active";
88+
}
89+
90+
async function errorCode(res: Response, fallback: string): Promise<string> {
91+
try {
92+
const body = await res.json() as { error?: unknown };
93+
return typeof body.error === "string" ? body.error : fallback;
94+
} catch { return fallback; }
95+
}
96+
97+
export async function fetchCodexCliUpdatePlan(apiBase: string, signal: AbortSignal): Promise<CodexCliUpdatePlanView> {
98+
const res = await fetch(`${apiBase}/api/codex/cli-update/plan`, { signal, cache: "no-store" });
99+
if (!res.ok) throw new CodexCliUpdateError(await errorCode(res, "plan_unavailable"), res.status, false);
100+
const plan = readPlan(await res.json());
101+
if (!plan) throw new CodexCliUpdateError("plan_unavailable", res.status, false);
102+
return plan;
103+
}
104+
105+
export async function applyCodexCliUpdate(apiBase: string, request: { requestId: string; planId: string }, signal: AbortSignal): Promise<CodexCliUpdateJobView> {
106+
let res: Response;
107+
try {
108+
res = await fetch(`${apiBase}/api/codex/cli-update/apply`, {
109+
method: "POST", signal, headers: { "Content-Type": "application/json" },
110+
body: JSON.stringify({ requestId: request.requestId, planId: request.planId, confirmed: true }),
111+
});
112+
} catch (error) {
113+
if (signal.aborted) throw error;
114+
throw new CodexCliUpdateError("network", 0, true);
115+
}
116+
if (!res.ok) {
117+
const code = await errorCode(res, "admission_failed");
118+
throw new CodexCliUpdateError(code, res.status, RETRYABLE_APPLY.has(code));
119+
}
120+
const job = readJob(((await res.json()) as { job?: unknown }).job);
121+
if (!job) throw new CodexCliUpdateError("job_result_unknown", res.status, false);
122+
return job;
123+
}
124+
125+
export async function fetchCodexCliUpdateJob(apiBase: string, jobId: string, signal: AbortSignal): Promise<CodexCliUpdateJobView> {
126+
let res: Response;
127+
try {
128+
res = await fetch(`${apiBase}/api/codex/cli-update/jobs/${encodeURIComponent(jobId)}`, { signal, cache: "no-store" });
129+
} catch (error) {
130+
if (signal.aborted) throw error;
131+
throw new CodexCliUpdateError("network", 0, true);
132+
}
133+
if (!res.ok) {
134+
const code = await errorCode(res, "job_state_unavailable");
135+
throw new CodexCliUpdateError(code, res.status, code !== "job_not_found");
136+
}
137+
const job = readJob(await res.json());
138+
if (!job) throw new CodexCliUpdateError("job_state_unavailable", res.status, true);
139+
return job;
140+
}
141+
142+
/** The terminal equivalents the panel offers when the dashboard cannot apply or read a job. */
143+
export function codexCliApplyCommand(planId: string | null): string {
144+
return planId ? `ocx system codex-cli-update apply --plan-id ${planId} --yes` : "ocx system codex-cli-update plan";
145+
}
146+
147+
export function codexCliStatusCommand(jobId: string): string {
148+
return `ocx system codex-cli-update status ${jobId} --json`;
149+
}
150+
151+
/**
152+
* A fresh request id. `crypto.randomUUID` exists only in secure contexts; `getRandomValues`
153+
* does not need one. Null means no id could be made, and the caller must not send.
154+
*/
155+
export function newCodexCliRequestId(): string | null {
156+
const api = globalThis.crypto;
157+
try {
158+
if (api && typeof api.randomUUID === "function") return api.randomUUID();
159+
} catch { /* not a secure context: fall through */ }
160+
if (api && typeof api.getRandomValues === "function") {
161+
const bytes = api.getRandomValues(new Uint8Array(16));
162+
bytes[6] = (bytes[6]! & 0x0f) | 0x40;
163+
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
164+
const hex = [...bytes].map(byte => byte.toString(16).padStart(2, "0")).join("");
165+
return [hex.slice(0, 8), hex.slice(8, 12), hex.slice(12, 16), hex.slice(16, 20), hex.slice(20)].join("-");
166+
}
167+
return null;
168+
}

0 commit comments

Comments
 (0)