Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: report Codex ChatGPT account readiness and run sign-in from PortOS (#5589)

[._.]/ Adam Eivy0e5eb88c531d
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 8d0ec359b4..73464a8b0b 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -51,7 +51,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiHistory.js` | Historical logs / runs. |
| `apiLogs.js` | PM2 system logs: fetch a process's recent log tail (process list comes from `apiCommands.getProcessesList`). |
| `apiPorts.js` | Port forwarding / allocation. |
-| `apiProviders.js` | AI provider configuration, plus provider-runtime (CLI) install readiness for the per-card Install buttons. |
+| `apiProviders.js` | AI provider configuration, plus provider-runtime (CLI) install readiness for the per-card Install buttons, and the Codex / ChatGPT-subscription account calls (`getCodexAccount`, `startCodexLogin`, `cancelCodexLogin`, `codexLogout`) — sign-in STATE only, never a token. |
| `apiPrompts.js` | Prompt Manager: stage templates, variables, and job-skill templates (providers list reuses `apiProviders.getProviders`). |
| `apiReferenceRepos.js` | Per-app reference-repo registry. |
| `apiReview.js` | Review hub. |
diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.js
index f2a844aaf7..9d8b3be7ea 100644
--- a/client/src/services/apiProviders.js
+++ b/client/src/services/apiProviders.js
@@ -46,3 +46,30 @@ export const serveProviderModel = (id, options) => request(
export const getProviderStatuses = () => request('/providers/status');
export const getProviderStatus = (id) => request(`/providers/${id}/status`);
export const recoverProvider = (id, options) => request(`/providers/${id}/status/recover`, { method: 'POST', ...options });
+
+// Codex / ChatGPT subscription account (#5589). The Codex app-server owns the
+// credentials: these calls report and change SIGN-IN STATE only, and no
+// response ever carries a token, an account id, or a credential path.
+//
+// `fresh` skips the server's short readiness TTL — use it for the poll that
+// follows a sign-in, not for the page's idle refresh.
+export const getCodexAccount = (options = {}) => {
+ const { fresh = false, ...rest } = options;
+ return request(`/providers/codex/account${fresh ? '?fresh=1' : ''}`, rest);
+};
+// Starts the ChatGPT OAuth flow and resolves to { login: { loginId, authUrl,
+// verificationUrl, userCode, expiresAt } }. Only ever call this from an
+// explicit user action — it opens a real sign-in.
+export const startCodexLogin = (deviceCode = false, options) => request('/providers/codex/account/login', {
+ method: 'POST',
+ body: JSON.stringify({ deviceCode }),
+ ...options,
+});
+// Abandons a sign-in this browser started. The id must be the one
+// `startCodexLogin` returned; a stale tab's id is refused with a 409.
+export const cancelCodexLogin = (loginId, options) => request('/providers/codex/account/login/cancel', {
+ method: 'POST',
+ body: JSON.stringify({ loginId }),
+ ...options,
+});
+export const codexLogout = (options) => request('/providers/codex/account/logout', { method: 'POST', ...options });
diff --git a/docs/API.md b/docs/API.md
index a2c119c7e3..ce7fe40e07 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -117,6 +117,10 @@ own wire contract in [FEDERATED_MEDIA_PROVIDERS.md](./FEDERATED_MEDIA_PROVIDERS.
| GET | `/providers/readiness` | Requirements checklist per provider backed by a LOCAL daemon (llama.cpp / Ollama / LM Studio / MTPLX), keyed by provider id: is the daemon installed, is it answering at the endpoint THIS provider points at, and is it serving the provider's default model. Each entry also carries `setup` — what the one-click fix below can do about the unmet checks (`null` when nothing is auto-fixable here). Providers with no local dependency are absent from the map. Complements `/providers/runtimes` (which answers "can PortOS run this CLI?"). Booleans, labels, and the provider's own endpoint only — never a resolved binary path. Skips disabled providers; 15s endpoint-probe cache (one probe per distinct endpoint), 60s binary-PATH cache, both dropped by the llama-server start/stop/install routes. |
| POST | `/providers/readiness/setup?provider=<id>` | Install and/or start the LOCAL DAEMON that provider points at (llama.cpp / Ollama / LM Studio / MTPLX), streaming progress as SSE — the "do it for me" half of `/providers/readiness`, so an unmet requirement is fixed from the card instead of from a vendor setup doc. The request names a PROVIDER only: the runtime kind and endpoint are re-derived server-side from the stored record, so no query value reaches a spawn argument (an optional `runtime=` is cross-checked and 409s on a mismatch). Every command comes from a fixed per-runtime table. Never downloads model weights, never starts llama-server (it needs a checkpoint you choose), and never runs MTPLX's privileged fan-control helper. Single-flight. |
| POST | `/providers/readiness/serve-model?provider=<id>` | Relaunch the local daemon so it answers under the model id THIS provider sends — the other half of the readiness model mismatch. `llama-server` serves one model per process under the `--alias` on its launch line, so the fix keeps the loaded weights and changes only the name; the whole launch line is carried forward and the previous one restored if the relaunch is rejected or never answers. The model id is re-derived server-side from the stored record. 400s for a runtime that has no such label (Ollama / LM Studio / MTPLX name a model after its weights), 409s when PortOS did not start the daemon. |
+| GET | `/providers/codex/account?fresh=1` | Is a ChatGPT subscription signed in, and usable right now? Answers `{ readiness }` with a `status` of `runtime-missing` / `unknown` / `signed-out` / `login-pending` / `ready` / `quota-exhausted` / `reauth-required`, plus the plan name and quota percentages. Read from the Codex app-server's own `account/read` — PortOS never opens Codex's credential file and the payload carries no token, account id, or credential path. This is the ONLY call that may spawn `codex app-server`, and it runs from an explicit page fetch: nothing on the boot path calls it, and `GET /providers` decorates its Codex cards from the cached snapshot only. `fresh=1` skips the 15s TTL for the poll after a sign-in. |
+| POST | `/providers/codex/account/login` | Start an explicit ChatGPT sign-in. Returns `{ login }` — a bounded `loginId` plus `authUrl` (browser flow) or `verificationUrl` + `userCode` (device-code flow, via `{ "deviceCode": true }`). A POST because it begins an OAuth flow; never a side effect of a read. 409s while another sign-in is already pending. |
+| POST | `/providers/codex/account/login/cancel` | Abandon the pending sign-in named by `{ loginId }`, then re-read. 409s for an id that is not the pending login, so a stale tab cannot cancel a flow the user started afterwards. |
+| POST | `/providers/codex/account/logout` | Sign out of ChatGPT and re-read. Codex drops its own credentials; PortOS holds none to clear. |
| GET | `/providers/opencode/installation` | **Legacy alias**, kept so a stale client bundle still renders: `{ installed, npmAvailable }` for the `opencode` runtime. New code uses `/providers/runtimes`. |
| POST | `/providers/opencode/install` | **Legacy alias** for `/providers/runtimes/install?runtime=opencode`. |
diff --git a/server/lib/README.md b/server/lib/README.md
index 9bdc0caf6f..7983d2318c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -192,6 +192,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `grokVideoClip.js` | Clip lengths grok's `image_to_video` actually delivers — `GROK_VIDEO_DURATIONS` (`[6, 10]`, measured in #3022: a 2s/3s request returns the same 6.04s clip), `GROK_VIDEO_DEFAULT_DURATION`, `resolveGrokDuration()` (validate an already-grok-shaped request, else default), and `nearestGrokDuration()` (round a length authored against another backend's continuous contract UP to the shortest clip that covers it — for translating a CD/commission `targetDurationSeconds`). Dependency-free so `validation.js` / `routes/videoGen.js` can derive their schemas from the same list the services gate on. |
| `kimi.js` | Moonshot AI Kimi Code (`kimi`) provider helpers — id constants (`KIMI_CLI_ID`/`KIMI_TUI_ID`), `isKimiCommand`/`isKimiCliProvider`/`isKimiTuiProvider` predicates, `ensureKimiHeadlessArgs` (model flag only — non-interactive mode is implicit in `--prompt`, and kimi has no `--print`/`--afk` and refuses approval flags alongside `--prompt`) / `ensureKimiTuiArgs` (`--yolo`) argv builders (model selection uses the `KIMI_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Grok/Antigravity), and `prepareKimiPrompt` (delivers the prompt as the `--prompt <value>` argv, not stdin). |
| `runners.js` | Image-runner family constants (`RUNNER_FAMILIES`, `loraCompatKey`), video LoRA families, MiniMax H3 runtime predicates, and the shared `AUDIO_TO_VIDEO_RUNTIMES` / `isAudioToVideoRuntime` capability gate (LTX plus H3 Ref2VA). Mirrored to `client/src/lib/runnerFamilies.js`. |
+| `codexAccount.js` | The ChatGPT-subscription half of the Codex providers (#5589), pure. The fixed `codex app-server` invocation, the `account/*` method + notification names, `CODEX_ACCOUNT_STATUS` (`runtime-missing` / `unknown` / `signed-out` / `login-pending` / `ready` / `quota-exhausted` / `reauth-required`) and `CODEX_ERROR_CODES`, `isCodexSubscriptionProvider` (keyed on the `codex` COMMAND, so a renamed clone still resolves), the `normalizeCodexAccount` / `normalizeCodexRateLimits` / `normalizeCodexLoginStart` payload normalizers, `redactCodexPayload` (every log/error/response path runs through it, so "PortOS never writes down a Codex token" is one function rather than a rule per call site), and `deriveCodexAccountStatus`. Sentinels are load-bearing: `runtimeInstalled: null` = NOT PROBED, `accountFetched: false` ≠ signed out, `rateLimits: null` (failed fetch) ≠ a fetched window with nothing to report. The process half is `services/codexAppServer.js`. |
| `codexAssistantExtract.js` | Strip Codex CLI banner + echoed metadata from session transcript. |
| `codexCliOutput.js` | Network/system error patterns for `agentErrorAnalysis.js`. |
| `contextBudget.js` | Context-window budgeter for editorial passes. `estimateTokens`/`estimateTokensFromChars` (chars/4), `usableInputTokens`, `manuscriptContentBudgetChars` (single-block content cap floored at a manuscript minimum so a standalone stage trims to fit a small window instead of overflowing a fixed 48–60K floor, #1488), `planManuscriptPass({ contextWindow, sections })` → `{ mode: 'whole' \| 'chunked', chunks }`. Also `fitContextToManuscriptFloor`/`capContextOverhead`/`trimContextToBudget` — trim a re-sent context block (scene map, character arcs, …) so a large reverse outline on a small window can't starve the manuscript chunk below a budget floor (#1459). Decides whole-manuscript vs chunked given a model's window. |
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index c05d9a20f7..013d273a49 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -18552,7 +18552,7 @@
},
{
"source": "server/routes/providers.js",
- "line": 159
+ "line": 169
}
]
},
@@ -18567,7 +18567,7 @@
},
{
"source": "server/routes/providers.js",
- "line": 686
+ "line": 750
}
]
},
@@ -18593,7 +18593,7 @@
},
{
"source": "server/routes/providers.js",
- "line": 640
+ "line": 704
}
]
},
@@ -18608,7 +18608,7 @@
},
{
"source": "server/routes/providers.js",
- "line": 652
+ "line": 716
}
]
},
@@ -18630,7 +18630,7 @@
"sources": [
{
"source": "server/routes/providers.js",
- "line": 600
+ "line": 664
}
]
},
@@ -18641,7 +18641,7 @@
"sources": [
{
"source": "server/routes/providers.js",
- "line": 608
+ "line": 672
}
]
},
@@ -18663,7 +18663,7 @@
"sources": [
{
"source": "server/routes/providers.js",
- "line": 619
+ "line": 683
}
]
},
@@ -18674,7 +18674,7 @@
"sources": [
{
"source": "server/routes/providers.js",
- "line": 614
+ "line": 678
}
]
},
@@ -18685,7 +18685,7 @@
"sources": [
{
"source": "server/routes/providers.js",
- "line": 633
+ "line": 697
}
]
},
@@ -18700,7 +18700,7 @@
},
{
"source": "server/routes/providers.js",
- "line": 174
+ "line": 189
}
]
},
@@ -18715,7 +18715,51 @@
},
{
"source": "server/routes/providers.js",
- "line": 181
+ "line": 196
+ }
+ ]
+ },
+ {
+ "method": "GET",
+ "path": "/api/providers/codex/account",
+ "mountPath": "/api/providers",
+ "sources": [
+ {
+ "source": "server/routes/providers.js",
+ "line": 263
+ }
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/providers/codex/account/login",
+ "mountPath": "/api/providers",
+ "sources": [
+ {
+ "source": "server/routes/providers.js",
+ "line": 275
+ }
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/providers/codex/account/login/cancel",
+ "mountPath": "/api/providers",
+ "sources": [
+ {
+ "source": "server/routes/providers.js",
+ "line": 284
+ }
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/providers/codex/account/logout",
+ "mountPath": "/api/providers",
+ "sources": [
+ {
+ "source": "server/routes/providers.js",
+ "line": 290
}
]
},
@@ -18726,7 +18770,7 @@
"sources": [
{
"source": "server/routes/providers.js",
- "line": 565
+ "line": 629
}
]
},
@@ -18737,7 +18781,7 @@
"sources": [
{
"source": "server/routes/providers.js",
- "line": 560
+ "line": 624
}
]
},
@@ -18748,7 +18792,7 @@
"sources": [
{
"source": "server/routes/providers.js",
- "line": 225
+ "line": 240
}
]
},
@@ -18759,7 +18803,7 @@
"sources": [
{
"source": "server/routes/providers.js",
- "line": 478
+ "line": 542
}
]
},
@@ -18770,7 +18814,7 @@
"sources": [
{
"source": "server/routes/providers.js",
- "line": 380
+ "line": 444
}
]
},
@@ -18781,7 +18825,7 @@
"sources": [
{
"source": "server/routes/providers.js",
- "line": 206
+ "line": 221
}
]
},
@@ -18792,7 +18836,7 @@
"sources": [
{
"source": "server/routes/providers.js",
- "line": 553
+ "line": 617
}
]
},
@@ -18807,7 +18851,7 @@
},
{
"source": "server/routes/providers.js",
- "line": 194
+ "line": 209
}
]
},
@@ -18818,7 +18862,7 @@
"sources": [
{
"source": "server/routes/providers.js",
- "line": 587
+ "line": 651
}
]
},
@@ -23764,8 +23808,8 @@
],
"stats": {
"mounts": 146,
- "operations": 2144,
- "declarations": 2147,
+ "operations": 2148,
+ "declarations": 2151,
"sourceFiles": 227
}
}
diff --git a/server/lib/codexAccount.js b/server/lib/codexAccount.js
new file mode 100644
index 0000000000..cc53e2aaf3
--- /dev/null
+++ b/server/lib/codexAccount.js
@@ -0,0 +1,307 @@
+/**
+ * The ChatGPT-subscription half of the Codex providers, as PortOS models it.
+ *
+ * PortOS already ships `codex` (CLI) and `codex-tui` provider records, and
+ * `providerPrerequisites.js` can tell you whether the `codex` binary is on
+ * PATH. That is only half of "can this provider run": Codex authenticates
+ * against a ChatGPT subscription (or an API key, or Bedrock), and until now
+ * nothing in PortOS could say whether that sign-in exists, which plan backs it,
+ * whether it has expired, or whether the subscription's usage window is spent.
+ * The user found out inside a failed agent transcript.
+ *
+ * OpenAI's documented Codex **app-server** owns that lifecycle, so this is the
+ * clean-room boundary PortOS consumes: `account/read` is the source of truth
+ * and `account/login/start` runs the browser flow. PortOS never reads, copies,
+ * returns, logs, or persists `~/.codex/auth.json`, an access token, or a
+ * refresh token — Codex keeps its own credentials and refreshes them itself.
+ *
+ * This module is the PURE half: constants, protocol-payload normalization, the
+ * redactor every log/error path runs through, and the readiness state machine.
+ * The process/JSON-RPC half is `services/codexAppServer.js`.
+ *
+ * **SENTINEL DISCIPLINE** (AGENTS.md). Three different "nothing here" answers
+ * must never collapse into each other:
+ *
+ * - `runtimeInstalled: null` — NOT PROBED. Never reads as "the binary is
+ * missing".
+ * - `accountFetched: false` — `account/read` has not answered. Never reads as
+ * SIGNED OUT; that is a claim only a successful read may make.
+ * - `rateLimits: null` — the quota read failed or never ran, which is NOT the
+ * same as a successful read that legitimately reported no active window.
+ * An empty-but-fetched answer normalizes to an object, so a subscription
+ * with no limit window in flight is never mistaken for a broken fetch.
+ */
+
+import { commandBasename } from './providerModels.js';
+
+/**
+ * The one invocation PortOS is allowed to spawn. Fixed argv, never assembled
+ * from a provider record or a request: the app-server is a protocol endpoint,
+ * not a user-configurable command line, and a config write must not be able to
+ * choose the exec target.
+ */
+export const CODEX_APP_SERVER_COMMAND = 'codex';
+export const CODEX_APP_SERVER_ARGS = Object.freeze(['app-server']);
+
+/** JSON-RPC methods this phase speaks. Read-only plus the explicit auth verbs. */
+export const CODEX_RPC = Object.freeze({
+ initialize: 'initialize',
+ initialized: 'initialized',
+ accountRead: 'account/read',
+ rateLimitsRead: 'account/rateLimits/read',
+ loginStart: 'account/login/start',
+ loginCancel: 'account/login/cancel',
+ logout: 'account/logout',
+});
+
+/** Server-to-client notifications that invalidate PortOS's cached readiness. */
+export const CODEX_NOTIFICATIONS = Object.freeze({
+ accountUpdated: 'account/updated',
+ rateLimitsUpdated: 'account/rateLimits/updated',
+ loginCompleted: 'account/login/completed',
+});
+
+/**
+ * Every state the Providers page has to be able to paint differently, because
+ * each one has a different fix. `unknown` is deliberately its own state rather
+ * than a pessimistic `signedOut`: telling a signed-in user to sign in again
+ * because a probe failed is worse than saying PortOS could not tell.
+ */
+export const CODEX_ACCOUNT_STATUS = Object.freeze({
+ runtimeMissing: 'runtime-missing',
+ unknown: 'unknown',
+ signedOut: 'signed-out',
+ loginPending: 'login-pending',
+ ready: 'ready',
+ quotaExhausted: 'quota-exhausted',
+ reauthRequired: 'reauth-required',
+});
+
+/** Typed failures the routes and the client both branch on. */
+export const CODEX_ERROR_CODES = Object.freeze({
+ runtimeMissing: 'CODEX_RUNTIME_MISSING',
+ startFailed: 'CODEX_APP_SERVER_START_FAILED',
+ exited: 'CODEX_APP_SERVER_EXITED',
+ timeout: 'CODEX_APP_SERVER_TIMEOUT',
+ protocol: 'CODEX_APP_SERVER_PROTOCOL_ERROR',
+ authRevoked: 'CODEX_AUTH_REVOKED',
+ loginTimeout: 'CODEX_LOGIN_TIMEOUT',
+ loginCancelled: 'CODEX_LOGIN_CANCELLED',
+ loginFailed: 'CODEX_LOGIN_FAILED',
+ unknownLogin: 'CODEX_UNKNOWN_LOGIN',
+});
+
+/**
+ * Which provider records this account state belongs to.
+ *
+ * Keyed on the COMMAND, not the id: a user who cloned `codex` into
+ * `codex-review` still runs the same binary against the same ChatGPT sign-in,
+ * and hard-coding two ids would leave that card blank. API providers are
+ * excluded — an OpenAI API-key provider authenticates with its own stored key
+ * and has nothing to do with a subscription.
+ */
+export const isCodexSubscriptionProvider = (provider) => {
+ if (provider?.type !== 'cli' && provider?.type !== 'tui') return false;
+ const command = typeof provider?.command === 'string' ? provider.command.trim() : '';
+ if (command === '') return false;
+ return commandBasename(command) === CODEX_APP_SERVER_COMMAND;
+};
+
+/**
+ * Keys whose VALUES may carry a credential. Matched case-insensitively as a
+ * substring so a field PortOS has never seen (`chatgptAuthTokens`,
+ * `refresh_token`, `clientSecret`) is redacted the first time it appears rather
+ * than the first time someone notices it in a log.
+ */
+const SECRET_KEY_RE = /(token|secret|password|credential|apikey|api_key|accesskey|authorization|bearer|cookie|codeverifier|code_verifier)/i;
+const REDACTED = '[redacted]';
+const MAX_REDACT_DEPTH = 6;
+
+/**
+ * A copy of `value` safe to put in a log line, an error `context`, or an HTTP
+ * response: every credential-shaped key replaced, strings clamped, recursion
+ * bounded.
+ *
+ * Applied to protocol payloads on BOTH directions before anything is written
+ * anywhere, so "we never log a token" is a property of one function rather than
+ * a rule every call site has to remember.
+ */
+export const redactCodexPayload = (value, depth = 0) => {
+ if (value === null || value === undefined) return value ?? null;
+ if (typeof value === 'string') return value.length > 200 ? `${value.slice(0, 200)}…` : value;
+ if (typeof value === 'number' || typeof value === 'boolean') return value;
+ if (depth >= MAX_REDACT_DEPTH) return REDACTED;
+ if (Array.isArray(value)) return value.slice(0, 20).map((entry) => redactCodexPayload(entry, depth + 1));
+ if (typeof value !== 'object') return REDACTED;
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [
+ key,
+ SECRET_KEY_RE.test(key) ? REDACTED : redactCodexPayload(entry, depth + 1),
+ ]));
+};
+
+const trimmedString = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : null);
+
+/**
+ * The non-secret shape of `account/read`.
+ *
+ * Returns `null` for a successful read that found no account — the ONE input
+ * from which "signed out" may be concluded. A response PortOS cannot understand
+ * is not that, so it throws rather than inventing a signed-out verdict; the
+ * caller turns that into `unknown`.
+ *
+ * Only three fields survive: how Codex authenticates, which plan backs it, and
+ * whether the credentials are Codex-managed. No id, no email, no token — the
+ * page needs "is this ready and on which plan", not who the user is.
+ */
+export const normalizeCodexAccount = (result) => {
+ if (result === null || result === undefined) return null;
+ if (typeof result !== 'object') throw new Error('account/read returned a non-object result');
+ // The documented envelope nests the record; tolerate a bare record too, since
+ // an install may be running a Codex older or newer than the one studied.
+ const raw = ('account' in result) ? result.account : result;
+ if (raw === null || raw === undefined) return null;
+ if (typeof raw !== 'object') throw new Error('account/read returned a non-object account');
+ const authMethod = trimmedString(raw.type) || trimmedString(raw.authMethod);
+ if (!authMethod) throw new Error('account/read returned an account with no auth method');
+ return {
+ authMethod,
+ planType: trimmedString(raw.planType) || trimmedString(raw.chatgptPlanType),
+ usesCodexManagedCredentials: raw.usesCodexManagedCredentials === true,
+ };
+};
+
+/** One rate-limit window, or `null` when the payload has nothing usable in it. */
+const normalizeWindow = (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ const usedPercent = typeof raw.usedPercent === 'number' && Number.isFinite(raw.usedPercent)
+ ? raw.usedPercent
+ : null;
+ const windowDurationMins = typeof raw.windowDurationMins === 'number' && Number.isFinite(raw.windowDurationMins)
+ ? raw.windowDurationMins
+ : null;
+ const resetsAt = trimmedString(raw.resetsAt);
+ const limitName = trimmedString(raw.limitName);
+ if (usedPercent === null && windowDurationMins === null && resetsAt === null) return null;
+ return { usedPercent, windowDurationMins, resetsAt, limitName };
+};
+
+/**
+ * The non-secret shape of `account/rateLimits/read`.
+ *
+ * Throws for a response that isn't an object, so a FAILED read stays `null` at
+ * the call site. A successful read with no active window returns an object
+ * whose windows are `null` — "fetched, and there is nothing to report" is a
+ * real answer and must not be re-labelled as a failed fetch (AGENTS.md).
+ */
+export const normalizeCodexRateLimits = (result) => {
+ if (result === null || result === undefined) throw new Error('rate limits read returned nothing');
+ if (typeof result !== 'object') throw new Error('rate limits read returned a non-object result');
+ const raw = result.rateLimits ?? result.codexRateLimits ?? result;
+ const source = (raw && typeof raw === 'object') ? raw : {};
+ const credits = (source.credits && typeof source.credits === 'object')
+ ? { hasCredits: source.credits.hasCredits === true, unlimited: source.credits.unlimited === true }
+ : null;
+ return {
+ primary: normalizeWindow(source.primary),
+ secondary: normalizeWindow(source.secondary),
+ credits,
+ };
+};
+
+/**
+ * Is the subscription's usage window spent?
+ *
+ * `null` (not fetched) is NOT exhausted — an unread quota may never take a
+ * working provider off the page. Only a window that reports itself at or past
+ * 100% counts.
+ */
+export const codexRateLimitsExhausted = (rateLimits) => {
+ if (!rateLimits || typeof rateLimits !== 'object') return false;
+ return [rateLimits.primary, rateLimits.secondary]
+ .some((window) => typeof window?.usedPercent === 'number' && window.usedPercent >= 100);
+};
+
+/**
+ * What `account/login/start` gives the browser, and nothing else.
+ *
+ * Both documented shapes are accepted: `authUrl` for the browser flow and
+ * `verificationUrl` (+ a short user code) for the device-code flow. Everything
+ * else in the response — including any token material a future Codex might add
+ * — is dropped here rather than filtered downstream.
+ *
+ * Throws when there is no `loginId`: without it the login cannot be cancelled
+ * or correlated with its completion notification, so returning a URL the user
+ * could open would strand them in a flow PortOS can no longer settle.
+ */
+export const normalizeCodexLoginStart = (result) => {
+ if (!result || typeof result !== 'object') throw new Error('login start returned a non-object result');
+ const loginId = trimmedString(result.loginId);
+ if (!loginId) throw new Error('login start returned no loginId');
+ const authUrl = trimmedString(result.authUrl);
+ const verificationUrl = trimmedString(result.verificationUrl);
+ if (!authUrl && !verificationUrl) throw new Error('login start returned no sign-in URL');
+ return {
+ loginId,
+ authUrl,
+ verificationUrl,
+ userCode: trimmedString(result.userCode),
+ };
+};
+
+/**
+ * Does this protocol error mean the stored ChatGPT sign-in is gone (revoked,
+ * expired, withdrawn from the workspace) rather than merely unreachable?
+ *
+ * Matched on the message because the app-server surfaces the upstream 401 as
+ * free text; a false negative degrades to `unknown`, which is the safe side.
+ */
+export const isCodexAuthError = (error) => {
+ const message = typeof error?.message === 'string' ? error.message : '';
+ return /\b(401|unauthorized|unauthenticated|invalid[_ -]?grant|token (?:expired|revoked)|re-?authenticate)\b/i
+ .test(message);
+};
+
+/**
+ * The whole state machine, in one pure function.
+ *
+ * @param {object} input
+ * @param {boolean|null} input.runtimeInstalled — `null` = NOT PROBED
+ * @param {boolean} input.accountFetched — did `account/read` actually answer?
+ * @param {object|null} input.account — normalized account; `null` only means
+ * signed out when `accountFetched` is true
+ * @param {object|null} input.rateLimits — `null` = NOT FETCHED
+ * @param {boolean} input.loginPending — a PortOS-initiated login is in flight
+ * @param {{code: string, message: string}|null} input.error
+ * @returns {string} one of {@link CODEX_ACCOUNT_STATUS}
+ */
+export const deriveCodexAccountStatus = ({
+ runtimeInstalled = null,
+ accountFetched = false,
+ account = null,
+ rateLimits = null,
+ loginPending = false,
+ error = null,
+} = {}) => {
+ if (runtimeInstalled === false) return CODEX_ACCOUNT_STATUS.runtimeMissing;
+ if (error?.code === CODEX_ERROR_CODES.authRevoked) return CODEX_ACCOUNT_STATUS.reauthRequired;
+ if (!accountFetched) {
+ return (!error && loginPending) ? CODEX_ACCOUNT_STATUS.loginPending : CODEX_ACCOUNT_STATUS.unknown;
+ }
+ if (!account) return loginPending ? CODEX_ACCOUNT_STATUS.loginPending : CODEX_ACCOUNT_STATUS.signedOut;
+ if (codexRateLimitsExhausted(rateLimits)) return CODEX_ACCOUNT_STATUS.quotaExhausted;
+ return CODEX_ACCOUNT_STATUS.ready;
+};
+
+/** One line for the card and the run log, per status. */
+export const describeCodexAccountStatus = (status, account = null) => {
+ switch (status) {
+ case CODEX_ACCOUNT_STATUS.runtimeMissing: return 'Codex CLI is not installed';
+ case CODEX_ACCOUNT_STATUS.signedOut: return 'No ChatGPT account is signed in';
+ case CODEX_ACCOUNT_STATUS.loginPending: return 'Waiting for the ChatGPT sign-in to finish';
+ case CODEX_ACCOUNT_STATUS.reauthRequired: return 'ChatGPT sign-in has expired — sign in again';
+ case CODEX_ACCOUNT_STATUS.quotaExhausted: return 'ChatGPT usage limit reached for this window';
+ case CODEX_ACCOUNT_STATUS.ready:
+ return account?.planType ? `Signed in on the ${account.planType} plan` : 'Signed in';
+ default: return 'Codex account state is unknown';
+ }
+};
diff --git a/server/lib/codexAccount.test.js b/server/lib/codexAccount.test.js
new file mode 100644
index 0000000000..87a114c703
--- /dev/null
+++ b/server/lib/codexAccount.test.js
@@ -0,0 +1,180 @@
+import { describe, it, expect } from 'vitest';
+import {
+ CODEX_ACCOUNT_STATUS,
+ CODEX_ERROR_CODES,
+ codexRateLimitsExhausted,
+ deriveCodexAccountStatus,
+ isCodexAuthError,
+ isCodexSubscriptionProvider,
+ normalizeCodexAccount,
+ normalizeCodexLoginStart,
+ normalizeCodexRateLimits,
+ redactCodexPayload,
+} from './codexAccount.js';
+
+describe('isCodexSubscriptionProvider', () => {
+ it('claims CLI and TUI providers whose command is the codex binary, whatever the id', () => {
+ expect(isCodexSubscriptionProvider({ id: 'codex', type: 'cli', command: 'codex' })).toBe(true);
+ expect(isCodexSubscriptionProvider({ id: 'codex-tui', type: 'tui', command: 'codex' })).toBe(true);
+ // A renamed clone still runs the same binary against the same sign-in.
+ expect(isCodexSubscriptionProvider({ id: 'codex-review', type: 'cli', command: '/opt/bin/codex' })).toBe(true);
+ });
+
+ it('does not claim an API provider or another vendor CLI', () => {
+ // An OpenAI API record authenticates with its own stored key — a
+ // subscription sign-in is not its question.
+ expect(isCodexSubscriptionProvider({ id: 'openai', type: 'api', endpoint: 'https://api.example.com/v1' })).toBe(false);
+ expect(isCodexSubscriptionProvider({ id: 'claude-code', type: 'cli', command: 'claude' })).toBe(false);
+ expect(isCodexSubscriptionProvider({ id: 'codex', type: 'cli' })).toBe(false);
+ });
+});
+
+describe('redactCodexPayload', () => {
+ it('replaces every credential-shaped key at any depth, keeping the rest readable', () => {
+ const redacted = redactCodexPayload({
+ account: { type: 'chatgpt', planType: 'pro' },
+ chatgptAuthTokens: { accessToken: 'secret-value', refresh_token: 'secret-value' },
+ nested: [{ apiKey: 'secret-value', label: 'kept' }],
+ });
+
+ expect(redacted.account).toEqual({ type: 'chatgpt', planType: 'pro' });
+ expect(redacted.chatgptAuthTokens).toBe('[redacted]');
+ expect(redacted.nested[0]).toEqual({ apiKey: '[redacted]', label: 'kept' });
+ expect(JSON.stringify(redacted)).not.toContain('secret-value');
+ });
+
+ it('bounds recursion and string length so one payload cannot flood a log line', () => {
+ let deep = { leaf: 'x' };
+ for (let i = 0; i < 10; i += 1) deep = { deep };
+
+ expect(JSON.stringify(redactCodexPayload(deep))).toContain('[redacted]');
+ expect(redactCodexPayload('y'.repeat(500))).toHaveLength(201);
+ });
+});
+
+describe('normalizeCodexAccount', () => {
+ it('returns null for a successful read that found no account — the only signed-out input', () => {
+ expect(normalizeCodexAccount({ account: null })).toBeNull();
+ expect(normalizeCodexAccount(null)).toBeNull();
+ });
+
+ it('keeps only the auth method, plan, and managed-credential flag', () => {
+ expect(normalizeCodexAccount({
+ account: { type: 'chatgpt', planType: 'pro', usesCodexManagedCredentials: true, accessToken: 'secret-value' },
+ })).toEqual({ authMethod: 'chatgpt', planType: 'pro', usesCodexManagedCredentials: true });
+ });
+
+ it('accepts a bare record, since an install may run a newer or older Codex', () => {
+ expect(normalizeCodexAccount({ type: 'apiKey' }))
+ .toEqual({ authMethod: 'apiKey', planType: null, usesCodexManagedCredentials: false });
+ });
+
+ it('throws rather than inventing a signed-out verdict from a shape it cannot read', () => {
+ expect(() => normalizeCodexAccount({ account: { planType: 'pro' } })).toThrow(/auth method/);
+ expect(() => normalizeCodexAccount('nope')).toThrow();
+ });
+});
+
+describe('normalizeCodexRateLimits', () => {
+ it('reports a fetched-but-empty window as an object, not as a failed fetch', () => {
+ // The sentinel that matters: `null` is reserved for "could not read".
+ expect(normalizeCodexRateLimits({ rateLimits: {} })).toEqual({ primary: null, secondary: null, credits: null });
+ });
+
+ it('normalizes the usage windows and drops anything not a number', () => {
+ expect(normalizeCodexRateLimits({
+ rateLimits: {
+ primary: { usedPercent: 42.5, windowDurationMins: 300, resetsAt: '2026-09-01T00:00:00Z', limitName: 'weekly' },
+ secondary: { usedPercent: 'lots' },
+ credits: { hasCredits: true, unlimited: false, balance: 12 },
+ },
+ })).toEqual({
+ primary: { usedPercent: 42.5, windowDurationMins: 300, resetsAt: '2026-09-01T00:00:00Z', limitName: 'weekly' },
+ secondary: null,
+ credits: { hasCredits: true, unlimited: false },
+ });
+ });
+
+ it('throws on a non-object response so the caller keeps the null sentinel', () => {
+ expect(() => normalizeCodexRateLimits(undefined)).toThrow();
+ expect(() => normalizeCodexRateLimits('nope')).toThrow();
+ });
+});
+
+describe('codexRateLimitsExhausted', () => {
+ it('is false for an unread quota and true only for a window at or past 100%', () => {
+ expect(codexRateLimitsExhausted(null)).toBe(false);
+ expect(codexRateLimitsExhausted({ primary: { usedPercent: 99.9 }, secondary: null })).toBe(false);
+ expect(codexRateLimitsExhausted({ primary: null, secondary: { usedPercent: 100 } })).toBe(true);
+ });
+});
+
+describe('normalizeCodexLoginStart', () => {
+ it('returns the browser URL and nothing else', () => {
+ expect(normalizeCodexLoginStart({
+ loginId: 'login-1',
+ authUrl: 'https://auth.example.com/x',
+ chatgptAuthTokens: { accessToken: 'secret-value' },
+ })).toEqual({ loginId: 'login-1', authUrl: 'https://auth.example.com/x', verificationUrl: null, userCode: null });
+ });
+
+ it('accepts the device-code shape', () => {
+ expect(normalizeCodexLoginStart({ loginId: 'login-2', verificationUrl: 'https://auth.example.com/device', userCode: 'ABCD-EFGH' }))
+ .toEqual({ loginId: 'login-2', authUrl: null, verificationUrl: 'https://auth.example.com/device', userCode: 'ABCD-EFGH' });
+ });
+
+ it('refuses a URL it could never cancel or correlate', () => {
+ expect(() => normalizeCodexLoginStart({ authUrl: 'https://auth.example.com/x' })).toThrow(/loginId/);
+ expect(() => normalizeCodexLoginStart({ loginId: 'login-3' })).toThrow(/sign-in URL/);
+ });
+});
+
+describe('deriveCodexAccountStatus', () => {
+ const ACCOUNT = { authMethod: 'chatgpt', planType: 'pro', usesCodexManagedCredentials: false };
+
+ it('never collapses an unprobed runtime or an unanswered read into signed-out', () => {
+ expect(deriveCodexAccountStatus({ runtimeInstalled: null, accountFetched: false }))
+ .toBe(CODEX_ACCOUNT_STATUS.unknown);
+ expect(deriveCodexAccountStatus({ runtimeInstalled: true, accountFetched: false }))
+ .toBe(CODEX_ACCOUNT_STATUS.unknown);
+ expect(deriveCodexAccountStatus({ runtimeInstalled: false }))
+ .toBe(CODEX_ACCOUNT_STATUS.runtimeMissing);
+ });
+
+ it('says signed-out only when a read actually reported no account', () => {
+ expect(deriveCodexAccountStatus({ runtimeInstalled: true, accountFetched: true, account: null }))
+ .toBe(CODEX_ACCOUNT_STATUS.signedOut);
+ });
+
+ it('prefers login-pending over signed-out and unknown while a flow is live', () => {
+ expect(deriveCodexAccountStatus({ runtimeInstalled: true, accountFetched: true, account: null, loginPending: true }))
+ .toBe(CODEX_ACCOUNT_STATUS.loginPending);
+ expect(deriveCodexAccountStatus({ runtimeInstalled: true, accountFetched: false, loginPending: true }))
+ .toBe(CODEX_ACCOUNT_STATUS.loginPending);
+ });
+
+ it('reports reauth-required for a revoked sign-in and unknown for any other failure', () => {
+ expect(deriveCodexAccountStatus({ runtimeInstalled: true, error: { code: CODEX_ERROR_CODES.authRevoked } }))
+ .toBe(CODEX_ACCOUNT_STATUS.reauthRequired);
+ expect(deriveCodexAccountStatus({ runtimeInstalled: true, error: { code: CODEX_ERROR_CODES.timeout }, loginPending: true }))
+ .toBe(CODEX_ACCOUNT_STATUS.unknown);
+ });
+
+ it('is ready on an unread quota, and quota-exhausted only on a read one', () => {
+ // An unread usage window must not take a working subscription off the page.
+ expect(deriveCodexAccountStatus({ runtimeInstalled: true, accountFetched: true, account: ACCOUNT, rateLimits: null }))
+ .toBe(CODEX_ACCOUNT_STATUS.ready);
+ expect(deriveCodexAccountStatus({
+ runtimeInstalled: true, accountFetched: true, account: ACCOUNT, rateLimits: { primary: { usedPercent: 100 } },
+ })).toBe(CODEX_ACCOUNT_STATUS.quotaExhausted);
+ });
+});
+
+describe('isCodexAuthError', () => {
+ it('recognizes the revoked/expired shapes and nothing else', () => {
+ expect(isCodexAuthError({ message: 'request failed with status 401' })).toBe(true);
+ expect(isCodexAuthError({ message: 'token expired' })).toBe(true);
+ expect(isCodexAuthError({ message: 'connection refused' })).toBe(false);
+ expect(isCodexAuthError(null)).toBe(false);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index a82feda881..8613df9f5d 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -128,6 +128,7 @@ export * from './cliChildEnv.js';
export * from './cliProviderArgs.js';
export * from './cliProviderRun.js';
export * from './codex.js';
+export * from './codexAccount.js';
export * from './codexAssistantExtract.js';
export * from './codexCliOutput.js';
export * from './contextBudget.js';
diff --git a/server/lib/providerPrerequisites.js b/server/lib/providerPrerequisites.js
index aa360283ee..6969843e51 100644
--- a/server/lib/providerPrerequisites.js
+++ b/server/lib/providerPrerequisites.js
@@ -36,6 +36,7 @@
*/
import { PROVIDER_TYPES } from './aiToolkit/constants.js';
+import { CODEX_ACCOUNT_STATUS, isCodexSubscriptionProvider } from './codexAccount.js';
import { isLocalInstanceHost } from './localProviderRuntime.js';
import { commandBasename } from './providerModels.js';
import { gatewayForProvider } from './providerGateways.js';
@@ -161,6 +162,33 @@ export const providerRuntimeKey = (provider) => {
const providerHasApiKey = (provider) =>
provider?.hasApiKey === true || Boolean(provider?.apiKey);
+/**
+ * The ChatGPT-subscription finding for a Codex provider, or `null`.
+ *
+ * PRESENTATION ONLY — deliberately absent from {@link ROUTING_BLOCKING_CODES}.
+ * Codex can authenticate several ways and PortOS's readiness snapshot may be
+ * seconds stale, so a card may say "sign in" while the router still tries the
+ * run: taking a working provider out of the fallback chain is the worse failure
+ * (see the module note above).
+ *
+ * `readiness: null` is NOT PROBED and produces nothing, and so does every
+ * status that isn't a definite negative — `unknown` must never be painted as
+ * signed out.
+ */
+const codexAccountFinding = (provider, readiness) => {
+ if (!readiness || !isCodexSubscriptionProvider(provider)) return null;
+ switch (readiness.status) {
+ case CODEX_ACCOUNT_STATUS.signedOut:
+ return { code: 'codexAccount', label: 'No ChatGPT account is signed in' };
+ case CODEX_ACCOUNT_STATUS.reauthRequired:
+ return { code: 'codexAccount', label: 'ChatGPT sign-in has expired' };
+ case CODEX_ACCOUNT_STATUS.quotaExhausted:
+ return { code: 'codexQuota', label: 'ChatGPT usage limit reached' };
+ default:
+ return null;
+ }
+};
+
/**
* Which prerequisites `provider` is missing, and whether it is runnable at all.
*
@@ -168,13 +196,16 @@ const providerHasApiKey = (provider) =>
* @param {object} [options]
* @param {object|null} [options.runtime] — the provider's entry of the runtimes
* map. `null` = NOT PROBED (see the sentinel note at the top of this file).
+ * @param {object|null} [options.codexAccount] — the Codex ChatGPT readiness
+ * snapshot, or `null` for NOT PROBED (presentation-only; see
+ * {@link codexAccountFinding}).
* @param {Record<string, boolean|null>|null} [options.gatewayKeySet] — per gateway
* id, does the sibling API provider of that id hold the key an OpenCode
* wrapper inherits at spawn time? `false` covers both "no key" and "sibling
* deleted"; `null`/absent is "cannot tell".
* @returns {{met: boolean, missing: {code: string, label: string}[]}}
*/
-export const providerPrerequisites = (provider, { runtime = null, gatewayKeySet = null } = {}) => {
+export const providerPrerequisites = (provider, { runtime = null, gatewayKeySet = null, codexAccount = null } = {}) => {
const missing = [];
if (runtime && runtime.installed === false) {
@@ -195,6 +226,9 @@ export const providerPrerequisites = (provider, { runtime = null, gatewayKeySet
missing.push({ code: 'inheritedApiKey', label: `${gateway.label} API provider has no API key` });
}
+ const codexFinding = codexAccountFinding(provider, codexAccount);
+ if (codexFinding) missing.push(codexFinding);
+
return { met: missing.length === 0, missing };
};
diff --git a/server/lib/validation.js b/server/lib/validation.js
index f042345ac3..1b42c1be35 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -554,6 +554,19 @@ export const providerVisionTestSchema = z.object({
model: z.preprocess(emptyToUndefined, z.string().trim().min(1).max(256).optional()),
});
+// POST /api/providers/codex/account/login/cancel. The id is minted by the Codex
+// app-server and only ever echoed back, so this bounds the shape and nothing
+// more — the service still refuses an id that isn't the pending login's.
+export const codexLoginCancelSchema = z.object({
+ loginId: z.string().trim().min(1).max(200),
+});
+
+// POST /api/providers/codex/account/login. `deviceCode` picks the device-code
+// flow (a URL plus a short code) over opening a browser URL directly.
+export const codexLoginStartSchema = z.object({
+ deviceCode: z.boolean().optional().default(false),
+});
+
// POST /api/providers/:id/vision-suite.
export const providerVisionSuiteSchema = z.object({
model: z.preprocess(emptyToUndefined, z.string().trim().min(1).max(256).optional()),
diff --git a/server/routes/providers.codexAccount.test.js b/server/routes/providers.codexAccount.test.js
new file mode 100644
index 0000000000..5a09ba9d5d
--- /dev/null
+++ b/server/routes/providers.codexAccount.test.js
@@ -0,0 +1,187 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express, { Router } from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { CODEX_ACCOUNT_STATUS } from '../lib/codexAccount.js';
+
+// The lifecycle service owns the process; this suite asserts the ROUTE
+// CONTRACT — which service call each endpoint makes, what it validates, and
+// what shape reaches the browser.
+vi.mock('../services/codexAppServer.js', () => ({
+ getCodexAccountReadiness: vi.fn(),
+ startCodexChatGptLogin: vi.fn(),
+ cancelCodexChatGptLogin: vi.fn(),
+ codexLogout: vi.fn(),
+ peekCodexAccountReadiness: vi.fn(() => null),
+}));
+vi.mock('../services/providerRuntimeInstaller.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ peekProviderRuntimeStatuses: vi.fn(() => ({ codex: { id: 'codex', label: 'Codex CLI', installed: true } })),
+}));
+
+const codexAppServer = await import('../services/codexAppServer.js');
+const { createPortOSProviderRoutes } = await import('./providers.js');
+
+const CODEX = { id: 'codex', name: 'Codex CLI', type: 'cli', command: 'codex', envVars: {} };
+const CLAUDE = { id: 'claude-code', name: 'Claude Code', type: 'cli', command: 'claude', envVars: {} };
+
+const READY = {
+ status: CODEX_ACCOUNT_STATUS.ready,
+ detail: 'Signed in on the pro plan',
+ runtimeInstalled: true,
+ accountFetched: true,
+ account: { authMethod: 'chatgpt', planType: 'pro', usesCodexManagedCredentials: false },
+ rateLimits: { primary: { usedPercent: 12, windowDurationMins: 300, resetsAt: null, limitName: null }, secondary: null, credits: null },
+ login: null,
+ error: null,
+ checkedAt: 1_700_000_000_000,
+};
+
+const appWith = (providers = [CODEX, CLAUDE]) => {
+ const providerService = { getAllProviders: vi.fn().mockResolvedValue({ activeProvider: 'codex', providers }) };
+ const app = express();
+ app.use(express.json());
+ app.use('/api/providers', createPortOSProviderRoutes({
+ services: { providers: providerService }, routes: { providers: Router() },
+ }));
+ app.use(errorMiddleware);
+ return app;
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ codexAppServer.peekCodexAccountReadiness.mockReturnValue(null);
+});
+
+describe('GET /api/providers/codex/account', () => {
+ it('returns the readiness verdict and honours ?fresh=1', async () => {
+ codexAppServer.getCodexAccountReadiness.mockResolvedValue(READY);
+
+ const res = await request(appWith()).get('/api/providers/codex/account');
+ expect(res.status).toBe(200);
+ expect(res.body.readiness.status).toBe(CODEX_ACCOUNT_STATUS.ready);
+ expect(codexAppServer.getCodexAccountReadiness).toHaveBeenCalledWith({ fresh: false });
+
+ await request(appWith()).get('/api/providers/codex/account?fresh=1');
+ expect(codexAppServer.getCodexAccountReadiness).toHaveBeenLastCalledWith({ fresh: true });
+ });
+
+ it('is not shadowed by the GET /:id provider lookup', async () => {
+ codexAppServer.getCodexAccountReadiness.mockResolvedValue(READY);
+
+ const res = await request(appWith()).get('/api/providers/codex/account');
+
+ expect(res.body.readiness).toBeTruthy();
+ expect(res.body.id).toBeUndefined();
+ });
+});
+
+describe('POST /api/providers/codex/account/login', () => {
+ it('starts the browser flow and returns only the URL and login id', async () => {
+ codexAppServer.startCodexChatGptLogin.mockResolvedValue({
+ loginId: 'login-1', authUrl: 'https://auth.example.com/x', verificationUrl: null, userCode: null,
+ startedAt: 1, expiresAt: 2,
+ });
+
+ const res = await request(appWith()).post('/api/providers/codex/account/login').send({});
+
+ expect(res.status).toBe(200);
+ expect(codexAppServer.startCodexChatGptLogin).toHaveBeenCalledWith({ deviceCode: false });
+ expect(res.body.login.authUrl).toBe('https://auth.example.com/x');
+ });
+
+ it('passes the device-code opt-in through', async () => {
+ codexAppServer.startCodexChatGptLogin.mockResolvedValue({ loginId: 'login-2', verificationUrl: 'https://auth.example.com/d', userCode: 'ABCD' });
+
+ await request(appWith()).post('/api/providers/codex/account/login').send({ deviceCode: true });
+
+ expect(codexAppServer.startCodexChatGptLogin).toHaveBeenCalledWith({ deviceCode: true });
+ });
+
+ it('rejects a non-boolean deviceCode instead of coercing it', async () => {
+ const res = await request(appWith()).post('/api/providers/codex/account/login').send({ deviceCode: 'yes' });
+
+ expect(res.status).toBe(400);
+ expect(codexAppServer.startCodexChatGptLogin).not.toHaveBeenCalled();
+ });
+});
+
+describe('POST /api/providers/codex/account/login/cancel', () => {
+ it('cancels the named login and answers with the settled readiness', async () => {
+ codexAppServer.cancelCodexChatGptLogin.mockResolvedValue({ ...READY, status: CODEX_ACCOUNT_STATUS.signedOut });
+
+ const res = await request(appWith()).post('/api/providers/codex/account/login/cancel').send({ loginId: 'login-1' });
+
+ expect(res.status).toBe(200);
+ expect(codexAppServer.cancelCodexChatGptLogin).toHaveBeenCalledWith('login-1');
+ expect(res.body.readiness.status).toBe(CODEX_ACCOUNT_STATUS.signedOut);
+ });
+
+ it('requires a login id', async () => {
+ const res = await request(appWith()).post('/api/providers/codex/account/login/cancel').send({});
+
+ expect(res.status).toBe(400);
+ expect(codexAppServer.cancelCodexChatGptLogin).not.toHaveBeenCalled();
+ });
+
+ it('surfaces the service\'s 409 for a login that is no longer pending', async () => {
+ const err = Object.assign(new Error('That ChatGPT sign-in is no longer in progress.'), { status: 409, code: 'CODEX_UNKNOWN_LOGIN' });
+ codexAppServer.cancelCodexChatGptLogin.mockRejectedValue(err);
+
+ const res = await request(appWith()).post('/api/providers/codex/account/login/cancel').send({ loginId: 'stale' });
+
+ expect(res.status).toBe(409);
+ });
+});
+
+describe('POST /api/providers/codex/account/logout', () => {
+ it('signs out and returns the re-read readiness', async () => {
+ codexAppServer.codexLogout.mockResolvedValue({ ...READY, status: CODEX_ACCOUNT_STATUS.signedOut, account: null });
+
+ const res = await request(appWith()).post('/api/providers/codex/account/logout').send({});
+
+ expect(res.status).toBe(200);
+ expect(res.body.readiness.status).toBe(CODEX_ACCOUNT_STATUS.signedOut);
+ });
+});
+
+describe('GET /api/providers decorates the Codex cards', () => {
+ const byId = (res) => Object.fromEntries(res.body.providers.map((p) => [p.id, p]));
+
+ it('publishes nothing but an unprobed null on a cold cache, and never accuses a card', async () => {
+ const cards = byId(await request(appWith()).get('/api/providers'));
+
+ expect(cards.codex.codexAccount).toBeNull();
+ expect(cards.codex.prerequisitesMet).toBe(true);
+ expect(cards.codex.missingPrerequisites).toEqual([]);
+ // Reading the list must never be the thing that spawns an app-server.
+ expect(codexAppServer.getCodexAccountReadiness).not.toHaveBeenCalled();
+ });
+
+ it('attaches the cached snapshot to Codex providers only', async () => {
+ codexAppServer.peekCodexAccountReadiness.mockReturnValue(READY);
+
+ const cards = byId(await request(appWith()).get('/api/providers'));
+
+ expect(cards.codex.codexAccount.status).toBe(CODEX_ACCOUNT_STATUS.ready);
+ expect(cards['claude-code']).not.toHaveProperty('codexAccount');
+ });
+
+ it('adds a presentation-only finding for a signed-out account', async () => {
+ codexAppServer.peekCodexAccountReadiness.mockReturnValue({ ...READY, status: CODEX_ACCOUNT_STATUS.signedOut, account: null });
+
+ const cards = byId(await request(appWith()).get('/api/providers'));
+
+ expect(cards.codex.missingPrerequisites).toEqual([{ code: 'codexAccount', label: 'No ChatGPT account is signed in' }]);
+ expect(cards['claude-code'].missingPrerequisites).toEqual([]);
+ });
+
+ it('does not turn an unknown verdict into a finding', async () => {
+ codexAppServer.peekCodexAccountReadiness.mockReturnValue({ ...READY, status: CODEX_ACCOUNT_STATUS.unknown, accountFetched: false, account: null });
+
+ const cards = byId(await request(appWith()).get('/api/providers'));
+
+ expect(cards.codex.missingPrerequisites).toEqual([]);
+ expect(cards.codex.prerequisitesMet).toBe(true);
+ });
+});
diff --git a/server/routes/providers.js b/server/routes/providers.js
index 81f8baa73a..23983e2703 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -9,6 +9,8 @@ import { onClientDisconnect, openSseStream } from '../lib/sseDownload.js';
import { createInstallLogger } from '../lib/installLogger.js';
import {
validateRequest,
+ codexLoginCancelSchema,
+ codexLoginStartSchema,
providerVisionTestSchema,
providerVisionSuiteSchema,
} from '../lib/validation.js';
@@ -24,6 +26,14 @@ import { getProviderReadinessMap, resetProviderReadinessCache, servedModelId } f
import { getLlamaServerEndpoint, relaunchLlamaServerWithAlias } from '../services/llamaServerManager.js';
import { claimHeavyLocalJob } from '../lib/heavyJobClaim.js';
import { getProviderPrerequisiteMap } from '../services/providerPrerequisites.js';
+import { isCodexSubscriptionProvider } from '../lib/codexAccount.js';
+import {
+ cancelCodexChatGptLogin,
+ peekCodexAccountReadiness,
+ codexLogout,
+ getCodexAccountReadiness,
+ startCodexChatGptLogin,
+} from '../services/codexAppServer.js';
import { runLocalRuntimeSetup, SETUP_ACTIONS } from '../services/localRuntimeSetup.js';
import { localEndpointPort, localRuntimeForProvider } from '../lib/localProviderRuntime.js';
import { buildTuiShellLaunch } from '../lib/tuiShellLaunch.js';
@@ -160,12 +170,17 @@ export function createPortOSProviderRoutes(aiToolkit) {
const data = await providerService.getAllProviders();
const prerequisites = getProviderPrerequisiteMap(data.providers);
const capabilities = await detectSystemCapabilities();
+ // Cache-only: this list must stay a synchronous read that spawns nothing.
+ // `null` here means NOT PROBED, and the dedicated `/codex/account` fetch is
+ // what fills it — a card renders "unknown", never "signed out", until then.
+ const codexAccount = peekCodexAccountReadiness();
res.json({
activeProvider: data.activeProvider,
providers: data.providers.map((provider) => ({
...presentProvider(provider, capabilities),
prerequisitesMet: prerequisites[provider.id]?.met ?? true,
missingPrerequisites: prerequisites[provider.id]?.missing ?? [],
+ ...(isCodexSubscriptionProvider(provider) ? { codexAccount } : {}),
})),
runnerAllowedCommands: RUNNER_ALLOWED_COMMANDS
});
@@ -227,6 +242,55 @@ export function createPortOSProviderRoutes(aiToolkit) {
res.json({ readiness: await getProviderReadinessMap(data.providers) });
}));
+ /**
+ * Is a ChatGPT subscription signed in, and is it usable right now?
+ *
+ * The Codex CLI/TUI cards could already say whether the `codex` binary
+ * exists; they could not say whether the account behind it is signed in, on
+ * which plan, expired, or out of quota — the user learned that from a failed
+ * agent transcript. The answer comes from the Codex app-server's own
+ * `account/read`: PortOS never reads Codex's credential file and never holds
+ * a token.
+ *
+ * LAZY BY CONTRACT. This is the call that may spawn `codex app-server`, and
+ * it runs only from an explicit page fetch — nothing on the boot path calls
+ * it, and `GET /api/providers` decorates its cards from the cache-only peek.
+ * `?fresh=1` skips the TTL for the poll that follows a sign-in.
+ *
+ * The payload carries a status, a plan name, and quota percentages. No token,
+ * no account id, no email, no credential path.
+ */
+ router.get('/codex/account', asyncHandler(async (req, res) => {
+ res.json({ readiness: await getCodexAccountReadiness({ fresh: req.query.fresh === '1' }) });
+ }));
+
+ /**
+ * Begin an explicit ChatGPT sign-in and return only the URL (browser flow) or
+ * the verification URL plus short code (device-code flow) the user needs.
+ *
+ * A POST because it starts an OAuth flow — never a side effect of a read.
+ * The response deliberately contains no token material, and `loginId` is the
+ * bounded handle the cancel endpoint takes.
+ */
+ router.post('/codex/account/login', asyncHandler(async (req, res) => {
+ const { deviceCode } = validateRequest(codexLoginStartSchema, req.body ?? {});
+ res.json({ login: await startCodexChatGptLogin({ deviceCode }) });
+ }));
+
+ /**
+ * Abandon the sign-in this PortOS started. The id must match the pending
+ * login, so a stale tab cannot cancel a flow the user began afterwards.
+ */
+ router.post('/codex/account/login/cancel', asyncHandler(async (req, res) => {
+ const { loginId } = validateRequest(codexLoginCancelSchema, req.body ?? {});
+ res.json({ readiness: await cancelCodexChatGptLogin(loginId) });
+ }));
+
+ /** Sign out. Codex drops its own credentials; PortOS has none to clear. */
+ router.post('/codex/account/logout', asyncHandler(async (_req, res) => {
+ res.json({ readiness: await codexLogout() });
+ }));
+
/**
* Install one provider runtime, streaming the installer's output as SSE.
*
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index e3f3173146..50b5061b23 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -146,6 +146,7 @@ import { outcomesStore as liOutcomesStore } from './layeredIntelligenceOutcomes.
import * as gameStore from './games/store.js';
import * as fableLoomStore from './fableLoom/store.js';
import { prerequisitesMetForRouting } from './providerPrerequisites.js';
+import { stopCodexAppServer } from './codexAppServer.js';
/**
* Pre-route boot. Everything a route handler may depend on being ready the
@@ -898,6 +899,16 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>
writeHostShutdownMarker({ agentIds: [...activeAgents.keys()], signal })
.then(() => finish(), (err) => finish(`⚠️ Host-shutdown marker failed: ${err.message}`, true)));
+ // Terminate the Codex app-server child before the socket teardown below.
+ // pm2's TreeKill would reap it anyway, but a direct SIGTERM keeps a manual
+ // `kill` of the server from orphaning a Codex process holding the user's
+ // sign-in, and it is a no-op when nothing was ever spawned.
+ await withGrace('Codex app-server', 2000, (finish) =>
+ stopCodexAppServer().then(
+ () => finish(),
+ (err) => finish(`⚠️ Codex app-server stop failed: ${err.message}`, true),
+ ));
+
// Drop existing long-lived sockets (SSE + keep-alive) up front so the closes
// below don't wait on connections that never end on their own.
try { httpServer.closeAllConnections?.(); } catch (e) { console.error(`⚠️ closeAllConnections(http): ${e.message}`); }
diff --git a/server/services/codexAppServer.js b/server/services/codexAppServer.js
new file mode 100644
index 0000000000..6584cc63f0
--- /dev/null
+++ b/server/services/codexAppServer.js
@@ -0,0 +1,464 @@
+/**
+ * PortOS's client for the Codex **app-server** — the JSON-RPC-over-stdio
+ * endpoint OpenAI documents for embedding Codex in a product.
+ *
+ * This is the process half of `lib/codexAccount.js`: it spawns
+ * `codex app-server`, speaks the handshake, and exposes exactly the bounded
+ * account actions the Providers page needs — read the account, start a ChatGPT
+ * sign-in, cancel it, sign out. Nothing else in this phase: no threads, no
+ * turns, no inference (that is #5590).
+ *
+ * Rules this module exists to keep in one place:
+ *
+ * - **Codex owns the credentials.** PortOS never reads `~/.codex/auth.json`,
+ * never asks for a token, and never persists one. `account/read` is the
+ * source of truth; every payload crossing this boundary goes through
+ * `redactCodexPayload` before it can reach a log or an error context.
+ * - **Nothing starts at boot.** The child is spawned lazily, on an explicit
+ * request only, so a cold install makes no Codex process and no network
+ * call (AGENTS.md, "No cold-bootstrap LLM calls" — and this is stricter,
+ * since an OAuth flow is not something a boot sequence may begin).
+ * - **Every wait is bounded and settles once.** A request, the handshake, and
+ * a login each carry their own deadline; a child exit fails every pending
+ * request with a typed error rather than hanging the page forever.
+ * - **Writes are serialized.** JSON-RPC framing is newline-delimited, so two
+ * concurrent writers could interleave a frame. Every write is chained onto
+ * one tail promise.
+ *
+ * The readiness snapshot is CACHED and separately PEEKABLE: `GET /api/providers`
+ * decorates cards from `peekCodexAccountReadiness()`, which never spawns
+ * anything, while the Providers page's own explicit fetch is what fills that
+ * cache.
+ */
+
+import { spawn } from '../lib/childProcess.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { createLineReader } from '../lib/streamLines.js';
+import { findCommandOnPath } from '../lib/processEnv.js';
+import {
+ CODEX_APP_SERVER_ARGS,
+ CODEX_APP_SERVER_COMMAND,
+ CODEX_ERROR_CODES,
+ CODEX_NOTIFICATIONS,
+ CODEX_RPC,
+ deriveCodexAccountStatus,
+ describeCodexAccountStatus,
+ isCodexAuthError,
+ normalizeCodexAccount,
+ normalizeCodexLoginStart,
+ normalizeCodexRateLimits,
+ redactCodexPayload,
+} from '../lib/codexAccount.js';
+
+/** The app-server answers a local read in milliseconds; a stall is a fault. */
+const REQUEST_TIMEOUT_MS = 15_000;
+/** Cold start pays for process launch and config load, so it gets more room. */
+const HANDSHAKE_TIMEOUT_MS = 20_000;
+/**
+ * How long a browser sign-in may stay pending before PortOS stops waiting. Long
+ * enough for a real OAuth round trip in another tab, short enough that an
+ * abandoned flow does not pin the card in `login-pending` until a restart.
+ */
+const LOGIN_TIMEOUT_MS = 5 * 60_000;
+/**
+ * Matches the Providers page's poll cadence: a user who just signed in must see
+ * `ready` on the next tick, while a page reload landing on top of a poll reuses
+ * the answer instead of spawning a second read.
+ */
+const READINESS_TTL_MS = 15_000;
+
+const CLIENT_INFO = Object.freeze({ name: 'PortOS', title: 'PortOS', version: '1' });
+
+/** The live connection, or `null` when nothing is running. */
+let connection = null;
+/** Coalesces concurrent connects so one page load cannot spawn two children. */
+let connecting = null;
+/** `{ at, readiness }` — the last successful read. `null` = never probed. */
+let readinessCache = null;
+/** `{ loginId, startedAt, expiresAt, timer }` for a PortOS-initiated login. */
+let pendingLogin = null;
+
+const codexError = (code, message, options = {}) => new ServerError(message, {
+ status: options.status ?? 502,
+ code,
+ context: options.context ?? {},
+});
+
+/**
+ * Where the `codex` binary is, or `null` when it is not on PortOS's PATH.
+ *
+ * A synchronous PATH walk, not a spawn — this is the gate that keeps a
+ * runtime-missing host from launching a child that can only fail with ENOENT.
+ */
+const resolveCodexBinary = () => findCommandOnPath(CODEX_APP_SERVER_COMMAND);
+
+/**
+ * Fail every in-flight request and drop the connection.
+ *
+ * Called from the child's `exit`/`error` handlers and from `stop()`. Each
+ * pending entry is removed from the map BEFORE it is settled, so a rejection
+ * handler that immediately retries cannot see the same id twice.
+ */
+const teardown = (target, error) => {
+ if (!target) return;
+ const pendingEntries = [...target.pending.values()];
+ target.pending.clear();
+ target.closed = true;
+ for (const entry of pendingEntries) entry.reject(error);
+ if (connection === target) connection = null;
+};
+
+/** Settle a pending login once, clearing its deadline. */
+const settleLogin = (reason) => {
+ if (!pendingLogin) return;
+ clearTimeout(pendingLogin.timer);
+ pendingLogin = null;
+ if (reason) console.log(`🔑 Codex sign-in ${reason}`);
+};
+
+/**
+ * Notifications PortOS acts on. Everything else the app-server streams is for
+ * a thread/turn client and is ignored here.
+ *
+ * The account cache is dropped rather than patched: the notification says the
+ * state CHANGED, and re-reading `account/read` is one cheap local call, whereas
+ * merging a partial payload would invent state PortOS was not told.
+ */
+const handleNotification = (method, params) => {
+ if (method === CODEX_NOTIFICATIONS.accountUpdated || method === CODEX_NOTIFICATIONS.rateLimitsUpdated) {
+ readinessCache = null;
+ return;
+ }
+ if (method !== CODEX_NOTIFICATIONS.loginCompleted) return;
+ readinessCache = null;
+ const loginId = typeof params?.loginId === 'string' ? params.loginId : null;
+ // A completion for a login PortOS did not start (another Codex client on this
+ // host) still invalidates the cache above, but must not settle ours.
+ if (!pendingLogin || (loginId && loginId !== pendingLogin.loginId)) return;
+ settleLogin(params?.success === false ? 'failed' : 'completed');
+};
+
+/** One decoded stdout line. Malformed input is logged and dropped, never thrown. */
+const handleFrame = (target, line) => {
+ const text = line.trim();
+ if (text === '') return;
+ let frame = null;
+ try {
+ frame = JSON.parse(text);
+ } catch {
+ console.error(`❌ Codex app-server sent a frame PortOS could not parse (${text.length} chars)`);
+ return;
+ }
+ if (!frame || typeof frame !== 'object') return;
+ if (frame.id === undefined || frame.id === null) {
+ if (typeof frame.method === 'string') handleNotification(frame.method, frame.params);
+ return;
+ }
+ const entry = target.pending.get(frame.id);
+ if (!entry) return; // A late answer to a request that already timed out.
+ target.pending.delete(frame.id);
+ clearTimeout(entry.timer);
+ if (frame.error) {
+ const message = typeof frame.error?.message === 'string' ? frame.error.message : 'Codex app-server returned an error';
+ const rpcError = codexError(
+ isCodexAuthError(frame.error) ? CODEX_ERROR_CODES.authRevoked : CODEX_ERROR_CODES.protocol,
+ message,
+ { context: { method: entry.method, error: redactCodexPayload(frame.error) } },
+ );
+ entry.reject(rpcError);
+ return;
+ }
+ entry.resolve(frame.result ?? null);
+};
+
+/**
+ * Write one JSON-RPC frame, chained onto the connection's write tail.
+ *
+ * The tail is what makes concurrent callers safe: `stdin.write` can return
+ * false mid-frame, and two unchained writers would interleave halves of two
+ * JSON lines into one unparseable stream.
+ */
+const writeFrame = (target, frame) => {
+ target.writeTail = target.writeTail.then(() => new Promise((resolve, reject) => {
+ if (target.closed || target.child.stdin.destroyed) {
+ reject(codexError(CODEX_ERROR_CODES.exited, 'The Codex app-server is no longer running.'));
+ return;
+ }
+ target.child.stdin.write(`${JSON.stringify(frame)}\n`, (err) => (err ? reject(err) : resolve()));
+ }));
+ return target.writeTail;
+};
+
+/** A JSON-RPC request with its own deadline. Settles exactly once. */
+const sendRequest = (target, method, params = {}, timeoutMs = REQUEST_TIMEOUT_MS) => new Promise((resolve, reject) => {
+ const id = target.nextId++;
+ const timer = setTimeout(() => {
+ if (!target.pending.delete(id)) return;
+ reject(codexError(CODEX_ERROR_CODES.timeout, `Codex app-server did not answer ${method} within ${Math.round(timeoutMs / 1000)}s.`));
+ }, timeoutMs);
+ timer.unref?.();
+ target.pending.set(id, { method, resolve, reject, timer });
+ writeFrame(target, { jsonrpc: '2.0', id, method, params }).catch((err) => {
+ if (!target.pending.delete(id)) return;
+ clearTimeout(timer);
+ reject(err);
+ });
+});
+
+/** A JSON-RPC notification — fire and forget, but still serialized. */
+const sendNotification = (target, method, params = {}) =>
+ writeFrame(target, { jsonrpc: '2.0', method, params });
+
+/**
+ * Spawn the app-server and complete the handshake, or throw a typed error.
+ *
+ * `spawn` can throw synchronously and the child can die before the handshake
+ * answers; both are caught here because this runs outside the Express request
+ * lifecycle, where an unhandled rejection from a process event kills the node.
+ */
+const openConnection = async () => {
+ const binary = resolveCodexBinary();
+ if (!binary) {
+ throw codexError(
+ CODEX_ERROR_CODES.runtimeMissing,
+ 'The Codex CLI is not installed, so PortOS cannot check the ChatGPT account.',
+ { status: 409 },
+ );
+ }
+
+ let child = null;
+ try {
+ // Fixed argv, inherited env, no shell — nothing from a request or a stored
+ // provider record reaches this command line.
+ child = spawn(binary, [...CODEX_APP_SERVER_ARGS], { stdio: ['pipe', 'pipe', 'pipe'] });
+ } catch (err) {
+ throw codexError(CODEX_ERROR_CODES.startFailed, `Codex app-server failed to start: ${err.message}`);
+ }
+
+ const target = { child, pending: new Map(), nextId: 1, writeTail: Promise.resolve(), closed: false };
+ const reader = createLineReader((line) => handleFrame(target, line));
+ child.stdout?.on('data', reader.push);
+ // stderr is Codex's own diagnostics. Never forwarded to a client and never
+ // parsed — the protocol answer is the only thing PortOS acts on.
+ child.stderr?.on('data', () => {});
+ child.stdin?.on('error', (err) => console.error(`❌ Codex app-server stdin: ${err.message}`));
+ child.on('error', (err) => {
+ teardown(target, codexError(CODEX_ERROR_CODES.startFailed, `Codex app-server failed to start: ${err.message}`));
+ settleLogin('ended because the Codex app-server stopped');
+ });
+ child.on('exit', (code, signal) => {
+ reader.flush();
+ teardown(target, codexError(
+ CODEX_ERROR_CODES.exited,
+ `The Codex app-server exited (${signal ? `signal ${signal}` : `code ${code}`}).`,
+ ));
+ settleLogin('ended because the Codex app-server stopped');
+ });
+
+ await sendRequest(target, CODEX_RPC.initialize, { clientInfo: CLIENT_INFO }, HANDSHAKE_TIMEOUT_MS);
+ await sendNotification(target, CODEX_RPC.initialized, {});
+ console.log('🔌 Codex app-server connected');
+ return target;
+};
+
+/** The live connection, opening one if needed. One connect in flight at a time. */
+const connect = async () => {
+ if (connection && !connection.closed) return connection;
+ if (!connecting) {
+ connecting = openConnection()
+ .then((target) => { connection = target; return target; })
+ .finally(() => { connecting = null; });
+ }
+ return connecting;
+};
+
+/** A request against a fresh-or-existing connection. */
+const call = async (method, params = {}, timeoutMs = REQUEST_TIMEOUT_MS) =>
+ sendRequest(await connect(), method, params, timeoutMs);
+
+const loginSnapshot = () => (pendingLogin
+ ? { loginId: pendingLogin.loginId, startedAt: pendingLogin.startedAt, expiresAt: pendingLogin.expiresAt }
+ : null);
+
+const buildReadiness = ({ runtimeInstalled, accountFetched, account, rateLimits, error }) => {
+ const status = deriveCodexAccountStatus({
+ runtimeInstalled,
+ accountFetched,
+ account,
+ rateLimits,
+ loginPending: pendingLogin !== null,
+ error,
+ });
+ return {
+ status,
+ detail: describeCodexAccountStatus(status, account),
+ runtimeInstalled,
+ // Published, not derived downstream: `account: null` alone cannot tell a
+ // successful read that found no account (SIGNED OUT) from a read that never
+ // answered (UNKNOWN), and every consumer would have to re-derive it.
+ accountFetched,
+ account,
+ rateLimits,
+ login: loginSnapshot(),
+ error,
+ checkedAt: Date.now(),
+ };
+};
+
+/**
+ * Read the account and the quota window, and fold both into one readiness
+ * verdict.
+ *
+ * The two reads are independent on purpose. A quota read that fails leaves
+ * `rateLimits: null` — NOT FETCHED — and a signed-in account still reports
+ * `ready`, because "PortOS could not read the usage window" is not "you are out
+ * of quota". Only the account read can move the verdict off `unknown`.
+ */
+const readReadiness = async () => {
+ const runtimeInstalled = resolveCodexBinary() !== null;
+ if (!runtimeInstalled) {
+ return buildReadiness({ runtimeInstalled: false, accountFetched: false, account: null, rateLimits: null, error: null });
+ }
+
+ let account = null;
+ let accountFetched = false;
+ let error = null;
+ try {
+ account = normalizeCodexAccount(await call(CODEX_RPC.accountRead));
+ accountFetched = true;
+ } catch (err) {
+ error = { code: err.code || CODEX_ERROR_CODES.protocol, message: err.message };
+ console.error(`❌ Codex account/read failed: ${err.message}`);
+ }
+
+ let rateLimits = null;
+ if (accountFetched && account) {
+ try {
+ rateLimits = normalizeCodexRateLimits(await call(CODEX_RPC.rateLimitsRead));
+ } catch (err) {
+ // Sentinel, not a verdict: an unread quota stays `null` and the account
+ // keeps whatever status it earned.
+ console.error(`❌ Codex rate-limit read failed: ${err.message}`);
+ }
+ }
+
+ return buildReadiness({ runtimeInstalled: true, accountFetched, account, rateLimits, error });
+};
+
+/**
+ * The current Codex account readiness, from cache unless `fresh` is set or the
+ * cache has aged out.
+ *
+ * LAZY: the only callers are the Providers page's explicit fetch and an
+ * explicitly requested run. Nothing on the boot path may call this.
+ */
+export async function getCodexAccountReadiness({ fresh = false } = {}) {
+ if (!fresh && readinessCache && Date.now() - readinessCache.at < READINESS_TTL_MS) {
+ // Recompute the envelope so a login that started or expired since the read
+ // is reflected without paying for another round trip — but keep the ORIGINAL
+ // `checkedAt`, or a cache hit would claim a freshness it does not have.
+ return { ...buildReadiness(readinessCache.readiness), checkedAt: readinessCache.readiness.checkedAt };
+ }
+ const readiness = await readReadiness();
+ readinessCache = { at: Date.now(), readiness };
+ return readiness;
+}
+
+/**
+ * The cached readiness, or `null` when nothing has probed it yet.
+ *
+ * Spawns nothing and awaits nothing, so `GET /api/providers` can decorate cards
+ * with it on a hot cache while a cold one publishes an honest "unprobed"
+ * instead of an accusation.
+ */
+export function peekCodexAccountReadiness() {
+ if (!readinessCache) return null;
+ if (Date.now() - readinessCache.at >= READINESS_TTL_MS) return null;
+ return readinessCache.readiness;
+}
+
+/**
+ * Start an explicit ChatGPT sign-in and hand back only what the browser needs.
+ *
+ * Never called implicitly: an OAuth flow is a user action, so this runs from a
+ * POST and from nowhere else. A second call while one is pending is refused
+ * rather than silently replacing it — two live `loginId`s would leave the
+ * completion notification unable to say which flow finished.
+ *
+ * @param {object} [options]
+ * @param {boolean} [options.deviceCode] — use the device-code flow (a URL plus
+ * a short code) instead of opening a browser URL directly.
+ */
+export async function startCodexChatGptLogin({ deviceCode = false } = {}) {
+ if (pendingLogin) {
+ throw codexError(CODEX_ERROR_CODES.loginFailed, 'A ChatGPT sign-in is already in progress. Finish or cancel it first.', { status: 409 });
+ }
+ const result = await call(CODEX_RPC.loginStart, { type: deviceCode ? 'chatgptDeviceCode' : 'chatgpt' });
+ const login = normalizeCodexLoginStart(result);
+ const startedAt = Date.now();
+ const timer = setTimeout(() => {
+ readinessCache = null;
+ settleLogin('timed out');
+ }, LOGIN_TIMEOUT_MS);
+ timer.unref?.();
+ pendingLogin = { loginId: login.loginId, startedAt, expiresAt: startedAt + LOGIN_TIMEOUT_MS, timer };
+ readinessCache = null;
+ console.log('🔑 Codex ChatGPT sign-in started');
+ return { ...login, startedAt, expiresAt: startedAt + LOGIN_TIMEOUT_MS };
+}
+
+/**
+ * Cancel the sign-in this PortOS started.
+ *
+ * The id is checked against the pending login before anything is sent, so a
+ * stale page cannot cancel a flow the user started afterwards.
+ */
+export async function cancelCodexChatGptLogin(loginId) {
+ if (!pendingLogin || pendingLogin.loginId !== loginId) {
+ throw codexError(CODEX_ERROR_CODES.unknownLogin, 'That ChatGPT sign-in is no longer in progress.', { status: 409 });
+ }
+ try {
+ await call(CODEX_RPC.loginCancel, { loginId });
+ } finally {
+ // The flow is over for PortOS either way: a cancel the app-server refused
+ // must not strand the card in `login-pending` forever.
+ settleLogin('cancelled');
+ readinessCache = null;
+ }
+ return getCodexAccountReadiness({ fresh: true });
+}
+
+/** Sign out of ChatGPT. Codex drops its own credentials; PortOS holds none. */
+export async function codexLogout() {
+ await call(CODEX_RPC.logout);
+ settleLogin('ended by sign-out');
+ readinessCache = null;
+ console.log('🔒 Codex ChatGPT account signed out');
+ return getCodexAccountReadiness({ fresh: true });
+}
+
+/**
+ * Terminate the app-server child, if one is running.
+ *
+ * Registered with the graceful-shutdown sequence so PortOS never leaves an
+ * orphaned Codex process behind. Safe to call when nothing is running.
+ */
+export async function stopCodexAppServer() {
+ settleLogin(null);
+ readinessCache = null;
+ const target = connection;
+ connection = null;
+ if (!target || target.closed) return;
+ teardown(target, codexError(CODEX_ERROR_CODES.exited, 'PortOS is shutting down the Codex app-server.'));
+ target.child.kill('SIGTERM');
+ console.log('🔌 Codex app-server stopped');
+}
+
+/** Test-only: drop every module-level handle so a suite starts clean. */
+export function __resetCodexAppServer() {
+ if (pendingLogin) clearTimeout(pendingLogin.timer);
+ pendingLogin = null;
+ readinessCache = null;
+ connection = null;
+ connecting = null;
+}
diff --git a/server/services/codexAppServer.test.js b/server/services/codexAppServer.test.js
new file mode 100644
index 0000000000..74ecce88ac
--- /dev/null
+++ b/server/services/codexAppServer.test.js
@@ -0,0 +1,393 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { EventEmitter } from 'events';
+
+// No real process and no real OAuth: a fake child speaks the protocol back, so
+// this suite asserts the LIFECYCLE (handshake, settle-once, cancellation,
+// timeouts, process exit) rather than whether codex happens to be installed.
+vi.mock('../lib/childProcess.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ spawn: vi.fn(),
+}));
+vi.mock('../lib/processEnv.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ findCommandOnPath: vi.fn(() => '/usr/local/bin/codex'),
+}));
+
+const { spawn } = await import('../lib/childProcess.js');
+const { findCommandOnPath } = await import('../lib/processEnv.js');
+const { CODEX_ACCOUNT_STATUS, CODEX_ERROR_CODES } = await import('../lib/codexAccount.js');
+const {
+ __resetCodexAppServer,
+ cancelCodexChatGptLogin,
+ codexLogout,
+ getCodexAccountReadiness,
+ peekCodexAccountReadiness,
+ startCodexChatGptLogin,
+ stopCodexAppServer,
+} = await import('./codexAppServer.js');
+
+const READY_ACCOUNT = { account: { type: 'chatgpt', planType: 'pro' } };
+
+/**
+ * A stand-in for the app-server child. `written` is every frame PortOS sent,
+ * already parsed, so a test can assert the exact method and params that reached
+ * the wire — including that nothing but the fixed argv was ever spawned.
+ */
+const makeChild = () => {
+ const child = new EventEmitter();
+ child.written = [];
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.stdin = Object.assign(new EventEmitter(), {
+ destroyed: false,
+ write: (line, cb) => { child.written.push(JSON.parse(line)); cb?.(); return true; },
+ });
+ child.kill = vi.fn(() => { child.emit('exit', null, 'SIGTERM'); });
+ child.emitFrame = (frame) => child.stdout.emit('data', `${JSON.stringify(frame)}\n`);
+ // A cursor, not a search: the same method is requested several times in one
+ // test, and answering the FIRST `account/read` again would settle nothing and
+ // hang the second call.
+ child.cursor = 0;
+ child.take = (method) => {
+ const index = child.written.findIndex((f, i) => i >= child.cursor && f.method === method);
+ if (index === -1) return null;
+ child.cursor = index + 1;
+ return child.written[index];
+ };
+ child.lastRequest = (method) => [...child.written].reverse().find((f) => f.method === method);
+ child.reply = (frame, result) => child.emitFrame({ jsonrpc: '2.0', id: frame.id, result });
+ child.replyError = (frame, error) => child.emitFrame({ jsonrpc: '2.0', id: frame.id, error });
+ return child;
+};
+
+/**
+ * Drive one call to completion: PortOS's request is written asynchronously
+ * (behind the serialized write tail), so each scripted answer waits a macrotask
+ * for its frame to appear before replying.
+ */
+const scripted = async (child, promise, script) => {
+ for (const [method, answer] of script) {
+ let frame = null;
+ await vi.waitFor(() => { frame = child.take(method); expect(frame).toBeTruthy(); });
+ if (typeof answer === 'function') answer(frame);
+ else child.reply(frame, answer);
+ }
+ return promise;
+};
+
+let child = null;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ __resetCodexAppServer();
+ child = makeChild();
+ spawn.mockReturnValue(child);
+ findCommandOnPath.mockReturnValue('/usr/local/bin/codex');
+});
+
+afterEach(() => { __resetCodexAppServer(); });
+
+describe('spawning the app-server', () => {
+ it('spawns the fixed `codex app-server` argv and completes the handshake before any account read', async () => {
+ const promise = getCodexAccountReadiness();
+ await scripted(child, promise, [['initialize', {}], ['account/read', READY_ACCOUNT], ['account/rateLimits/read', { rateLimits: {} }]]);
+ const readiness = await promise;
+
+ expect(spawn).toHaveBeenCalledTimes(1);
+ expect(spawn.mock.calls[0][0]).toBe('/usr/local/bin/codex');
+ expect(spawn.mock.calls[0][1]).toEqual(['app-server']);
+ // The `initialized` notification must follow the handshake and precede the read.
+ expect(child.written.map((f) => f.method))
+ .toEqual(['initialize', 'initialized', 'account/read', 'account/rateLimits/read']);
+ expect(readiness.status).toBe(CODEX_ACCOUNT_STATUS.ready);
+ expect(readiness.account).toEqual({ authMethod: 'chatgpt', planType: 'pro', usesCodexManagedCredentials: false });
+ });
+
+ it('reports runtime-missing WITHOUT spawning when the codex binary is absent', async () => {
+ findCommandOnPath.mockReturnValue(null);
+
+ const readiness = await getCodexAccountReadiness();
+
+ expect(spawn).not.toHaveBeenCalled();
+ expect(readiness.status).toBe(CODEX_ACCOUNT_STATUS.runtimeMissing);
+ expect(readiness.runtimeInstalled).toBe(false);
+ });
+
+ it('reuses one child across calls, so a page poll cannot fan out processes', async () => {
+ const first = getCodexAccountReadiness();
+ await scripted(child, first, [['initialize', {}], ['account/read', { account: null }]]);
+ await first;
+
+ const second = getCodexAccountReadiness({ fresh: true });
+ await scripted(child, second, [['account/read', { account: null }]]);
+ await second;
+
+ expect(spawn).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('readiness verdicts', () => {
+ const readOnce = async (script) => {
+ const promise = getCodexAccountReadiness({ fresh: true });
+ await scripted(child, promise, [['initialize', {}], ...script]);
+ return promise;
+ };
+
+ it('says signed-out for a read that reported no account', async () => {
+ expect((await readOnce([['account/read', { account: null }]])).status).toBe(CODEX_ACCOUNT_STATUS.signedOut);
+ });
+
+ it('says reauth-required when the app-server answers with a revoked-auth error', async () => {
+ const readiness = await readOnce([['account/read', (frame) => child.replyError(frame, { code: -32000, message: 'request failed with status 401' })]]);
+
+ expect(readiness.status).toBe(CODEX_ACCOUNT_STATUS.reauthRequired);
+ expect(readiness.error.code).toBe(CODEX_ERROR_CODES.authRevoked);
+ });
+
+ it('says unknown — not signed-out — when the read fails for any other reason', async () => {
+ const readiness = await readOnce([['account/read', (frame) => child.replyError(frame, { code: -32000, message: 'connection refused' })]]);
+
+ expect(readiness.status).toBe(CODEX_ACCOUNT_STATUS.unknown);
+ expect(readiness.accountFetched).toBe(false);
+ });
+
+ it('stays ready when the quota read fails, and keeps rateLimits at the null sentinel', async () => {
+ const readiness = await readOnce([
+ ['account/read', READY_ACCOUNT],
+ ['account/rateLimits/read', (frame) => child.replyError(frame, { message: 'boom' })],
+ ]);
+
+ expect(readiness.status).toBe(CODEX_ACCOUNT_STATUS.ready);
+ expect(readiness.rateLimits).toBeNull();
+ });
+
+ it('says quota-exhausted for a spent window', async () => {
+ const readiness = await readOnce([
+ ['account/read', READY_ACCOUNT],
+ ['account/rateLimits/read', { rateLimits: { primary: { usedPercent: 100, resetsAt: '2026-09-02T00:00:00Z' } } }],
+ ]);
+
+ expect(readiness.status).toBe(CODEX_ACCOUNT_STATUS.quotaExhausted);
+ });
+
+ it('publishes no token, account id, or credential path even when the app-server sends them', async () => {
+ const readiness = await readOnce([
+ ['account/read', { account: { type: 'chatgpt', planType: 'pro', accountId: 'acct-1', accessToken: 'secret-value', authFile: '/home/example/.codex/auth.json' } }],
+ ['account/rateLimits/read', { rateLimits: {} }],
+ ]);
+
+ expect(JSON.stringify(readiness)).not.toContain('secret-value');
+ expect(JSON.stringify(readiness)).not.toContain('acct-1');
+ expect(JSON.stringify(readiness)).not.toContain('auth.json');
+ });
+});
+
+describe('the cached snapshot the provider list reads', () => {
+ it('peeks null until an explicit read has filled it, so a cold boot accuses nobody', async () => {
+ expect(peekCodexAccountReadiness()).toBeNull();
+
+ const promise = getCodexAccountReadiness();
+ await scripted(child, promise, [['initialize', {}], ['account/read', { account: null }]]);
+ await promise;
+
+ expect(peekCodexAccountReadiness().status).toBe(CODEX_ACCOUNT_STATUS.signedOut);
+ expect(spawn).toHaveBeenCalledTimes(1);
+ });
+
+ it('is dropped by an account/updated notification so the next read is real', async () => {
+ const promise = getCodexAccountReadiness();
+ await scripted(child, promise, [['initialize', {}], ['account/read', { account: null }]]);
+ await promise;
+
+ child.emitFrame({ jsonrpc: '2.0', method: 'account/updated', params: {} });
+
+ expect(peekCodexAccountReadiness()).toBeNull();
+ });
+});
+
+describe('the ChatGPT sign-in flow', () => {
+ const connect = async () => {
+ const promise = getCodexAccountReadiness();
+ await scripted(child, promise, [['initialize', {}], ['account/read', { account: null }]]);
+ await promise;
+ };
+
+ it('returns only the sign-in URL and a bounded login id', async () => {
+ await connect();
+
+ const promise = startCodexChatGptLogin();
+ await scripted(child, promise, [['account/login/start', { loginId: 'login-1', authUrl: 'https://auth.example.com/x', accessToken: 'secret-value' }]]);
+ const login = await promise;
+
+ expect(child.lastRequest('account/login/start').params).toEqual({ type: 'chatgpt' });
+ expect(login.loginId).toBe('login-1');
+ expect(login.authUrl).toBe('https://auth.example.com/x');
+ expect(login.expiresAt).toBeGreaterThan(login.startedAt);
+ expect(JSON.stringify(login)).not.toContain('secret-value');
+ });
+
+ it('asks for the device-code flow when the caller does', async () => {
+ await connect();
+
+ const promise = startCodexChatGptLogin({ deviceCode: true });
+ await scripted(child, promise, [['account/login/start', { loginId: 'login-2', verificationUrl: 'https://auth.example.com/device', userCode: 'ABCD-EFGH' }]]);
+ const login = await promise;
+
+ expect(child.lastRequest('account/login/start').params).toEqual({ type: 'chatgptDeviceCode' });
+ expect(login.userCode).toBe('ABCD-EFGH');
+ });
+
+ it('reports login-pending while the flow is live, then ready once it completes', async () => {
+ await connect();
+ const started = startCodexChatGptLogin();
+ await scripted(child, started, [['account/login/start', { loginId: 'login-3', authUrl: 'https://auth.example.com/x' }]]);
+ await started;
+
+ const pending = getCodexAccountReadiness({ fresh: true });
+ await scripted(child, pending, [['account/read', { account: null }]]);
+ expect((await pending).status).toBe(CODEX_ACCOUNT_STATUS.loginPending);
+
+ child.emitFrame({ jsonrpc: '2.0', method: 'account/login/completed', params: { loginId: 'login-3', success: true } });
+
+ const settled = getCodexAccountReadiness({ fresh: true });
+ await scripted(child, settled, [['account/read', READY_ACCOUNT], ['account/rateLimits/read', { rateLimits: {} }]]);
+ expect((await settled).status).toBe(CODEX_ACCOUNT_STATUS.ready);
+ });
+
+ it('ignores a completion for a login PortOS did not start', async () => {
+ await connect();
+ const started = startCodexChatGptLogin();
+ await scripted(child, started, [['account/login/start', { loginId: 'login-4', authUrl: 'https://auth.example.com/x' }]]);
+ await started;
+
+ child.emitFrame({ jsonrpc: '2.0', method: 'account/login/completed', params: { loginId: 'someone-elses', success: true } });
+
+ const readiness = getCodexAccountReadiness({ fresh: true });
+ await scripted(child, readiness, [['account/read', { account: null }]]);
+ expect((await readiness).status).toBe(CODEX_ACCOUNT_STATUS.loginPending);
+ });
+
+ it('refuses a second concurrent sign-in rather than orphaning the first', async () => {
+ await connect();
+ const started = startCodexChatGptLogin();
+ await scripted(child, started, [['account/login/start', { loginId: 'login-5', authUrl: 'https://auth.example.com/x' }]]);
+ await started;
+
+ await expect(startCodexChatGptLogin()).rejects.toMatchObject({ status: 409, code: CODEX_ERROR_CODES.loginFailed });
+ });
+
+ it('cancels the pending login and settles back to signed-out', async () => {
+ await connect();
+ const started = startCodexChatGptLogin();
+ await scripted(child, started, [['account/login/start', { loginId: 'login-6', authUrl: 'https://auth.example.com/x' }]]);
+ await started;
+
+ const cancelled = cancelCodexChatGptLogin('login-6');
+ await scripted(child, cancelled, [['account/login/cancel', {}], ['account/read', { account: null }]]);
+
+ expect(child.lastRequest('account/login/cancel').params).toEqual({ loginId: 'login-6' });
+ expect((await cancelled).status).toBe(CODEX_ACCOUNT_STATUS.signedOut);
+ });
+
+ it('refuses a cancel for an id that is not the pending login, so a stale tab cannot kill a new flow', async () => {
+ await connect();
+ const started = startCodexChatGptLogin();
+ await scripted(child, started, [['account/login/start', { loginId: 'login-7', authUrl: 'https://auth.example.com/x' }]]);
+ await started;
+
+ await expect(cancelCodexChatGptLogin('login-6')).rejects.toMatchObject({ status: 409, code: CODEX_ERROR_CODES.unknownLogin });
+ expect(child.lastRequest('account/login/cancel')).toBeUndefined();
+ });
+
+ it('times out an abandoned sign-in instead of pinning the card in login-pending', async () => {
+ vi.useFakeTimers();
+ try {
+ await connect();
+ const started = startCodexChatGptLogin();
+ await scripted(child, started, [['account/login/start', { loginId: 'login-8', authUrl: 'https://auth.example.com/x' }]]);
+ await started;
+
+ await vi.advanceTimersByTimeAsync(5 * 60_000 + 1);
+ } finally {
+ vi.useRealTimers();
+ }
+
+ const readiness = getCodexAccountReadiness({ fresh: true });
+ await scripted(child, readiness, [['account/read', { account: null }]]);
+ expect((await readiness).status).toBe(CODEX_ACCOUNT_STATUS.signedOut);
+ });
+
+ it('signs out and re-reads, holding no credential of its own to clear', async () => {
+ await connect();
+
+ const promise = codexLogout();
+ await scripted(child, promise, [['account/logout', {}], ['account/read', { account: null }]]);
+
+ expect((await promise).status).toBe(CODEX_ACCOUNT_STATUS.signedOut);
+ });
+});
+
+describe('failure paths settle exactly once', () => {
+ it('fails every pending request when the child exits mid-flight', async () => {
+ const promise = getCodexAccountReadiness();
+ await vi.waitFor(() => expect(child.lastRequest('initialize')).toBeTruthy());
+ child.emit('exit', 1, null);
+
+ const readiness = await promise;
+ expect(readiness.status).toBe(CODEX_ACCOUNT_STATUS.unknown);
+ expect(readiness.error.code).toBe(CODEX_ERROR_CODES.exited);
+ });
+
+ it('reports a spawn failure as a typed start error rather than crashing the process', async () => {
+ spawn.mockImplementation(() => { throw new Error('EACCES'); });
+
+ const readiness = await getCodexAccountReadiness();
+
+ expect(readiness.status).toBe(CODEX_ACCOUNT_STATUS.unknown);
+ expect(readiness.error.code).toBe(CODEX_ERROR_CODES.startFailed);
+ });
+
+ it('bounds the handshake, so a child that never answers cannot hang the page', async () => {
+ vi.useFakeTimers();
+ try {
+ const promise = getCodexAccountReadiness();
+ await vi.advanceTimersByTimeAsync(20_001);
+ const readiness = await promise;
+
+ expect(readiness.status).toBe(CODEX_ACCOUNT_STATUS.unknown);
+ expect(readiness.error.code).toBe(CODEX_ERROR_CODES.timeout);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('drops a malformed frame and a late duplicate answer without settling twice', async () => {
+ const promise = getCodexAccountReadiness();
+ await vi.waitFor(() => expect(child.lastRequest('initialize')).toBeTruthy());
+ child.stdout.emit('data', 'not json at all\n');
+ child.reply(child.take('initialize'), {});
+ let readFrame = null;
+ await vi.waitFor(() => { readFrame = child.take('account/read'); expect(readFrame).toBeTruthy(); });
+ child.reply(readFrame, { account: null });
+ // A second answer for an id already settled must be ignored, not thrown.
+ child.emitFrame({ jsonrpc: '2.0', id: readFrame.id, result: READY_ACCOUNT });
+
+ expect((await promise).status).toBe(CODEX_ACCOUNT_STATUS.signedOut);
+ });
+
+ it('terminates the child on shutdown and clears the cache', async () => {
+ const promise = getCodexAccountReadiness();
+ await scripted(child, promise, [['initialize', {}], ['account/read', { account: null }]]);
+ await promise;
+
+ await stopCodexAppServer();
+
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(peekCodexAccountReadiness()).toBeNull();
+ });
+
+ it('is a no-op on shutdown when nothing was ever spawned', async () => {
+ await expect(stopCodexAppServer()).resolves.toBeUndefined();
+ expect(spawn).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/providerPrerequisites.js b/server/services/providerPrerequisites.js
index 675954f8b5..a38016eb22 100644
--- a/server/services/providerPrerequisites.js
+++ b/server/services/providerPrerequisites.js
@@ -37,6 +37,7 @@ import { blocksRouting, describeMissingPrerequisites, providerPrerequisites, pro
import { PROVIDER_GATEWAYS } from '../lib/providerGateways.js';
import { inferTuiCommand } from '../lib/providerVendors.js';
import { findCommandOnPath } from '../lib/processEnv.js';
+import { peekCodexAccountReadiness } from './codexAppServer.js';
import { delimiter, isAbsolute } from 'path';
import {
getProviderRuntime,
@@ -96,11 +97,17 @@ const runtimeSnapshotFor = (keys) => {
return runtimes;
};
+// CACHE-ONLY (`peek`, never `get`): the Codex ChatGPT readiness a card shows
+// must never be the thing that spawns `codex app-server`. A cold cache answers
+// `null` — NOT PROBED — so `GET /api/providers` stays a synchronous read and a
+// fresh boot starts no auth check (AGENTS.md, no cold-bootstrap provider calls).
+// The Providers page's own explicit fetch is what fills it.
const forProvider = (provider, runtimes, gatewayKeySet) => providerPrerequisites(provider, {
// `undefined` (no entry in the map) is NOT PROBED — normalize it to the
// module's `null` sentinel rather than letting it fall through as a value.
runtime: runtimes?.[providerRuntimeKey(provider) ?? ''] ?? null,
gatewayKeySet,
+ codexAccount: peekCodexAccountReadiness(),
});
const effectiveProcessCommand = (provider) => {