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

fix: address local review of the Codex subscription transport

[._.]/ Adam Eivy9f4af7395b59
diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.js
index ca2ff87677..d4f494d10d 100644
--- a/client/src/services/apiProviders.js
+++ b/client/src/services/apiProviders.js
@@ -74,6 +74,8 @@ export const cancelCodexLogin = (loginId, options) => request('/providers/codex/
});
export const codexLogout = (options) => request('/providers/codex/account/logout', { method: 'POST', ...options });
// The models this subscription may run, from the app-server catalog (#5590).
+// Not yet called from a component: the Providers-page picker that consumes it is
+// #5591 (phase 3), which also ships the toggle that sets `textTransportEnabled`.
// Resolves to { models, fetchedAt, error }. `models: null` means NEVER FETCHED
// and `[]` means fetched-and-empty; when `error` is set the list is the
// last-known-good one, so render that rather than emptying the picker.
diff --git a/data.reference/providers.json b/data.reference/providers.json
index a34ed1f2ac..a41a8b7f75 100644
--- a/data.reference/providers.json
+++ b/data.reference/providers.json
@@ -100,6 +100,7 @@
"heavyModel": "gpt-5.6-sol",
"timeout": 600000,
"enabled": false,
+ "textTransport": "codex-app-server",
"envVars": {},
"tuiPromptDelayMs": 2500
},
diff --git a/scripts/migrations/331-codex-text-transport.js b/scripts/migrations/331-codex-text-transport.js
index e90008886a..a4b33dc225 100644
--- a/scripts/migrations/331-codex-text-transport.js
+++ b/scripts/migrations/331-codex-text-transport.js
@@ -1,6 +1,6 @@
/**
- * Advertise the ChatGPT-subscription text transport on the installed `codex`
- * provider (#5590).
+ * Advertise the ChatGPT-subscription text transport on every installed Codex
+ * harness record (#5590).
*
* Phase 1 (#5589) taught PortOS to read the Codex account; this is the record
* flag that lets the same `codex` record ALSO serve plain text through the
@@ -66,12 +66,15 @@ export default {
return { ok: false, reason: doc.reason, updated: 0 };
}
- const provider = doc.providers.codex;
- if (!isCodexHarness(provider)) return { ok: true, reason: 'already-current-or-custom', updated: 0 };
+ // Every Codex harness record, not just the `codex` id — that is what "keyed on
+ // the COMMAND" above actually means, and an install that cloned `codex` into
+ // `codex-review` runs the same binary against the same ChatGPT sign-in.
+ const targets = Object.values(doc.providers).filter(isCodexHarness);
+ if (targets.length === 0) return { ok: true, reason: 'already-current-or-custom', updated: 0 };
- provider.textTransport = TRANSPORT;
+ for (const provider of targets) provider.textTransport = TRANSPORT;
await writeJsonAtomic(doc.path, doc.config);
- console.log(`📝 ${PROVIDERS_REL_PATH}: the codex provider now advertises the ChatGPT subscription text transport (off until enabled)`);
- return { ok: true, reason: 'updated', updated: 1 };
+ console.log(`📝 ${PROVIDERS_REL_PATH}: ${targets.length} Codex provider record${targets.length === 1 ? '' : 's'} now advertising the ChatGPT subscription text transport (off until enabled)`);
+ return { ok: true, reason: 'updated', updated: targets.length };
},
};
diff --git a/scripts/migrations/331-codex-text-transport.test.js b/scripts/migrations/331-codex-text-transport.test.js
index 2d6d44ba7a..bea4c0211d 100644
--- a/scripts/migrations/331-codex-text-transport.test.js
+++ b/scripts/migrations/331-codex-text-transport.test.js
@@ -43,16 +43,22 @@ describe('migration 331 — codex text transport', () => {
expect(codex).toMatchObject(CODEX);
});
- it('matches a renamed clone by its command, and leaves other providers alone', async () => {
+ it('stamps every Codex harness record, clones included, and leaves others alone', async () => {
writeProviders({
codex: { ...CODEX, command: '/opt/bin/codex', name: 'My Codex' },
+ 'codex-review': { id: 'codex-review', type: 'cli', command: 'codex', enabled: true },
+ 'codex-tui': { id: 'codex-tui', type: 'tui', command: 'codex', enabled: false },
openrouter: { id: 'openrouter', type: 'api', endpoint: 'https://example.com/v1', apiKey: 'secret' },
});
- await migration.up({ rootDir });
+ await expect(migration.up({ rootDir })).resolves.toEqual({ ok: true, reason: 'updated', updated: 3 });
const providers = readProviders();
- expect(providers.codex.textTransport).toBe('codex-app-server');
+ // Keyed on the COMMAND, so a renamed clone and the disabled TUI record are
+ // covered too — an upgraded install then matches what data.reference seeds.
+ for (const id of ['codex', 'codex-review', 'codex-tui']) {
+ expect(providers[id].textTransport).toBe('codex-app-server');
+ }
expect(providers.openrouter).toEqual({
id: 'openrouter', type: 'api', endpoint: 'https://example.com/v1', apiKey: 'secret',
});
diff --git a/server/lib/README.md b/server/lib/README.md
index 7d5c9cdccf..73bf015b73 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -193,7 +193,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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`. |
-| `codexTurn.js` | The INFERENCE half of the Codex ChatGPT-subscription provider (#5590), pure. The `thread/start` / `turn/start` / `turn/interrupt` / `model/list` method names and the turn notifications, `CODEX_TEXT_TRANSPORT` plus `providerDeclaresCodexTextTransport` (advertises, reusing `codexAccount.isCodexSubscriptionProvider` so the two halves cannot drift) vs `isCodexTextTransportEnabled` (the explicit opt-in that actually permits routing), the `CODEX_TEXT_THREAD_CONFIG` safety envelope a generic text call runs under (empty throwaway cwd, read-only no-network sandbox, fail-closed approvals, no MCP servers, no web search), `normalizeCodexModels` / `normalizeCodexTokenUsage` / `resolveCodexEffort`, the `createTurnAccumulator` → `applyCodexTurnEvent` → `finalizeCodexTurn` projection (a non-`completed` turn yields an error, NEVER the partial text), and `classifyCodexTurnError` / `classifyCodexTransportError`, which fold both failure shapes onto the shared `ERROR_CATEGORIES` the cooldown policy reads. `models: null` = never fetched, `[]` = fetched-and-empty. The process half is `services/codexAppServer.js`. |
+| `codexTurn.js` | The INFERENCE half of the Codex ChatGPT-subscription provider (#5590), pure. The `thread/start` / `turn/start` / `turn/interrupt` / `model/list` method names and the turn notifications, `CODEX_TEXT_TRANSPORT` plus `providerDeclaresCodexTextTransport` (advertises, reusing `codexAccount.isCodexSubscriptionProvider` so the two halves cannot drift) vs `isCodexTextTransportEnabled` (the explicit opt-in that actually permits routing), the `CODEX_TEXT_THREAD_CONFIG` safety envelope a generic text call runs under (empty throwaway cwd, no writes, no network, fail-closed approvals, no MCP servers, no web search — it does NOT confine reads; see the module docstring), `normalizeCodexModels` / `normalizeCodexTokenUsage` / `resolveCodexEffort`, the `createTurnAccumulator` → `applyCodexTurnEvent` → `finalizeCodexTurn` projection (a non-`completed` turn yields an error, NEVER the partial text), and `classifyCodexTurnError` / `classifyCodexTransportError`, which fold both failure shapes onto the shared `ERROR_CATEGORIES` the cooldown policy reads. `models: null` = never fetched, `[]` = fetched-and-empty. 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/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.json
index 894fdca8da..2492b00bdf 100644
--- a/server/lib/aiToolkit/defaults/providers.sample.json
+++ b/server/lib/aiToolkit/defaults/providers.sample.json
@@ -440,6 +440,7 @@
"contextWindow": 1000000,
"timeout": 600000,
"enabled": false,
+ "textTransport": "codex-app-server",
"envVars": {},
"secretEnvVars": [],
"tuiPromptDelayMs": 2500
diff --git a/server/lib/codexAccount.js b/server/lib/codexAccount.js
index cc53e2aaf3..ec67cd76cd 100644
--- a/server/lib/codexAccount.js
+++ b/server/lib/codexAccount.js
@@ -139,6 +139,27 @@ export const redactCodexPayload = (value, depth = 0) => {
]));
};
+/**
+ * A free-text protocol message with any credential-shaped substring masked, or
+ * `null` when there is nothing to say.
+ *
+ * The payload redactor keys on FIELD NAMES; an upstream failure quoted into a
+ * `message` string has no field names to key on ("access_token=… expired",
+ * "Authorization: Bearer …"). These messages are both logged AND returned to the
+ * browser by the `/codex/*` routes, so they need their own scrub.
+ */
+export const redactCodexMessage = (value) => {
+ if (typeof value !== 'string' || value.trim() === '') return null;
+ const masked = value
+ // key=value / key: value, where the key is credential-shaped
+ .replace(/\b([A-Za-z0-9_-]*(?:token|secret|password|credential|api[_-]?key|access[_-]?key|cookie)[A-Za-z0-9_-]*)\s*[=:]\s*\S+/gi, '$1=' + REDACTED)
+ // an inline bearer/basic credential
+ .replace(/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]+/gi, '$1 ' + REDACTED)
+ // a bare OpenAI-style key, which carries no label at all
+ .replace(/\bsk-[A-Za-z0-9._-]{8,}/g, REDACTED);
+ return masked.length > 400 ? `${masked.slice(0, 400)}…` : masked;
+};
+
const trimmedString = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : null);
/**
diff --git a/server/lib/codexTurn.js b/server/lib/codexTurn.js
index df75af7745..e1f481a020 100644
--- a/server/lib/codexTurn.js
+++ b/server/lib/codexTurn.js
@@ -60,14 +60,23 @@ export const CODEX_TURN_NOTIFICATIONS = Object.freeze({
/**
* The safety envelope every generic text turn runs under.
*
- * `approvalPolicy: 'never'` is FAIL-CLOSED here, not permissive: paired with a
- * read-only sandbox it means an escalation request is refused outright rather
- * than queued for a human who is not watching a Brain summary. `ephemeral`
- * keeps the thread out of the user's Codex history, and the empty `mcp_servers`
- * / disabled web search strip every tool the model could otherwise reach for.
+ * What this GUARANTEES: the turn cannot write anywhere, cannot reach the
+ * network, has no MCP servers and no web search, starts in a fresh empty
+ * directory outside the PortOS checkout, and leaves no thread behind.
+ * `approvalPolicy: 'never'` is FAIL-CLOSED here rather than permissive — paired
+ * with a read-only sandbox it means an escalation request is refused outright
+ * instead of queued for a human who is not watching a Brain summary, and
+ * `sandbox_permissions: []` withholds every opt-in widening (notably Codex's
+ * `disk-full-read-access`).
*
- * The `cwd` is supplied per call (a fresh empty directory outside the PortOS
- * checkout) because it is a runtime path, not a constant.
+ * What it does NOT guarantee: Codex's read-only sandbox still lets the model's
+ * own shell tool READ files by absolute path. So a prompt carrying injected
+ * instructions could, in principle, quote local file contents back into its
+ * answer. Narrowing that needs a Codex permission profile verified against a
+ * live signed-in account, which is #5628 — do not describe this envelope as
+ * read-confinement until that lands.
+ *
+ * The `cwd` is supplied per call because it is a runtime path, not a constant.
*/
export const CODEX_TEXT_THREAD_CONFIG = Object.freeze({
approvalPolicy: 'never',
@@ -77,6 +86,9 @@ export const CODEX_TEXT_THREAD_CONFIG = Object.freeze({
mcp_servers: {},
tools: { web_search: false },
web_search: false,
+ // An explicit empty list, not an omission: Codex's opt-in widenings (e.g.
+ // `disk-full-read-access`) are additive, so declaring none can only narrow.
+ sandbox_permissions: [],
}),
});
@@ -303,7 +315,8 @@ export const classifyCodexTransportError = (err) => {
};
/** A fresh accumulator for one turn. */
-export const createTurnAccumulator = (turnId = null) => ({
+export const createTurnAccumulator = ({ threadId = null, turnId = null } = {}) => ({
+ threadId,
turnId,
deltas: [],
finalText: null,
@@ -331,18 +344,30 @@ export const applyCodexTurnEvent = (acc, method, params) => {
// a second time, and never fold it into the answer.
if (!acc || acc.status !== 'inProgress') return true;
if (!params || typeof params !== 'object') return false;
+ // Enforced HERE, not only in the caller that routes by thread: this function's
+ // contract says another thread's frames are ignored, and its own tests drive
+ // it directly.
+ if (acc.threadId && typeof params.threadId === 'string' && params.threadId !== acc.threadId) return false;
if (acc.turnId && typeof params.turnId === 'string' && params.turnId !== acc.turnId) return false;
+ // Latch the id from the first frame that carries one. `turn/start`'s own
+ // response also sets it, but a delta can arrive first (or that response can be
+ // delayed) — and without an id the caller cannot `turn/interrupt` a cancelled
+ // turn, which would leave it consuming subscription quota until it ends.
+ if (!acc.turnId && typeof params.turnId === 'string' && params.turnId) acc.turnId = params.turnId;
switch (method) {
case CODEX_TURN_NOTIFICATIONS.agentMessageDelta:
appendText(acc, params.delta);
return false;
case CODEX_TURN_NOTIFICATIONS.itemCompleted:
- // The completed item is AUTHORITATIVE for its own text; the deltas were a
- // progress signal. Replacing rather than appending is what keeps a
- // retried/repaired stream from producing doubled prose.
+ // A turn can emit several agent messages, so completed items CONCATENATE.
+ // Within one message the completed item is authoritative and the deltas
+ // that previewed it are dropped — appending both would double the prose —
+ // while deltas that arrive AFTER it belong to the next message and are
+ // still carried by `finalizeCodexTurn`.
if (params.item?.type === 'agentMessage' && typeof params.item.text === 'string') {
acc.finalText = acc.finalText === null ? params.item.text : `${acc.finalText}${params.item.text}`;
+ acc.deltas.length = 0;
}
return false;
case CODEX_TURN_NOTIFICATIONS.tokenUsage:
@@ -358,7 +383,11 @@ export const applyCodexTurnEvent = (acc, method, params) => {
case CODEX_TURN_NOTIFICATIONS.turnCompleted: {
const turn = params.turn;
if (acc.turnId && turn?.id && turn.id !== acc.turnId) return false;
- acc.status = typeof turn?.status === 'string' ? turn.status : 'completed';
+ // A frame with no status is MALFORMED, and defaulting it to 'completed'
+ // would hand the caller whatever text had streamed so far as a finished
+ // answer. `finalizeCodexTurn` errors on anything that is not 'completed',
+ // so an unrecognizable status fails the turn instead.
+ acc.status = typeof turn?.status === 'string' && turn.status ? turn.status : 'malformed';
if (acc.status === 'failed') acc.error = classifyCodexTurnError(turn?.error);
return true;
}
@@ -387,7 +416,9 @@ export const finalizeCodexTurn = (acc) => {
if (acc.status !== 'completed') {
return { error: 'The Codex turn ended without completing', category: ERROR_CATEGORIES.UNKNOWN };
}
- const text = acc.finalText !== null ? acc.finalText : acc.deltas.join('');
+ // Completed items plus any deltas streamed after the last one — a trailing
+ // message with no closing `item/completed` must not be silently dropped.
+ const text = `${acc.finalText ?? ''}${acc.deltas.join('')}`;
if (!text.trim()) {
return { error: 'Codex returned an empty completion', category: ERROR_CATEGORIES.UNKNOWN };
}
diff --git a/server/lib/codexTurn.test.js b/server/lib/codexTurn.test.js
index 2e2a86e0f6..6c62461cd3 100644
--- a/server/lib/codexTurn.test.js
+++ b/server/lib/codexTurn.test.js
@@ -140,7 +140,7 @@ describe('turn projection', () => {
applyCodexTurnEvent(acc, CODEX_TURN_NOTIFICATIONS.turnCompleted, { threadId: 't', turn });
it('joins deltas when no completed item supersedes them', () => {
- const acc = createTurnAccumulator('turn-1');
+ const acc = createTurnAccumulator({ threadId: 't', turnId: 'turn-1' });
delta(acc, 'Hello, ');
delta(acc, 'world');
expect(complete(acc, { id: 'turn-1', status: 'completed' })).toBe(true);
@@ -149,7 +149,7 @@ describe('turn projection', () => {
});
it('prefers the completed item text over the deltas that previewed it', () => {
- const acc = createTurnAccumulator('turn-1');
+ const acc = createTurnAccumulator({ threadId: 't', turnId: 'turn-1' });
delta(acc, '{"partial"');
applyCodexTurnEvent(acc, CODEX_TURN_NOTIFICATIONS.itemCompleted, {
threadId: 't', turnId: 'turn-1', item: { type: 'agentMessage', text: '{"whole":true}' },
@@ -160,7 +160,7 @@ describe('turn projection', () => {
});
it('ignores frames belonging to another turn on the same connection', () => {
- const acc = createTurnAccumulator('turn-1');
+ const acc = createTurnAccumulator({ threadId: 't', turnId: 'turn-1' });
delta(acc, 'mine');
delta(acc, 'SOMEBODY ELSE', { turnId: 'turn-2' });
complete(acc, { id: 'turn-1', status: 'completed' });
@@ -169,7 +169,7 @@ describe('turn projection', () => {
});
it('keeps running through a retryable error', () => {
- const acc = createTurnAccumulator('turn-1');
+ const acc = createTurnAccumulator({ threadId: 't', turnId: 'turn-1' });
const terminal = applyCodexTurnEvent(acc, CODEX_TURN_NOTIFICATIONS.error, {
threadId: 't', turnId: 'turn-1', willRetry: true, error: { message: 'transient' },
});
@@ -183,7 +183,7 @@ describe('turn projection', () => {
it('NEVER hands back the partial text of an interrupted turn', () => {
// A half-streamed JSON object that happened to parse would be silently wrong
// data — worse than a failed call, which the caller can fall back from.
- const acc = createTurnAccumulator('turn-1');
+ const acc = createTurnAccumulator({ threadId: 't', turnId: 'turn-1' });
delta(acc, '{"answer": "half');
complete(acc, { id: 'turn-1', status: 'interrupted' });
@@ -194,7 +194,7 @@ describe('turn projection', () => {
});
it('NEVER hands back the partial text of a failed turn, and carries its category', () => {
- const acc = createTurnAccumulator('turn-1');
+ const acc = createTurnAccumulator({ threadId: 't', turnId: 'turn-1' });
delta(acc, 'as much as I got');
complete(acc, {
id: 'turn-1',
@@ -208,15 +208,66 @@ describe('turn projection', () => {
});
it('treats a completed-but-empty turn as a failure, not a successful blank answer', () => {
- const acc = createTurnAccumulator('turn-1');
+ const acc = createTurnAccumulator({ threadId: 't', turnId: 'turn-1' });
delta(acc, ' \n ');
complete(acc, { id: 'turn-1', status: 'completed' });
expect(finalizeCodexTurn(acc)).toMatchObject({ error: expect.stringMatching(/empty completion/i) });
});
+ it('treats a turn/completed with no status as malformed, not as success', () => {
+ // Defaulting an unrecognizable frame to 'completed' would hand the caller
+ // whatever had streamed so far as a finished answer — and a caller parsing
+ // JSON would get a plausible, wrong object out of half a document.
+ const acc = createTurnAccumulator({ threadId: 't', turnId: 'turn-1' });
+ delta(acc, '{"answer":"hal');
+ expect(complete(acc, { id: 'turn-1' })).toBe(true);
+
+ const result = finalizeCodexTurn(acc);
+ expect(result.text).toBeUndefined();
+ expect(result.error).toMatch(/without completing/i);
+ });
+
+ it('ignores frames belonging to another thread on the same connection', () => {
+ // The routing layer filters by thread too, but this function's contract says
+ // it does — and its own callers drive it directly.
+ const acc = createTurnAccumulator({ threadId: 't', turnId: 'turn-1' });
+ delta(acc, 'mine');
+ applyCodexTurnEvent(acc, CODEX_TURN_NOTIFICATIONS.agentMessageDelta, {
+ threadId: 'another-thread', turnId: 'turn-1', delta: 'NOT MINE',
+ });
+ complete(acc, { id: 'turn-1', status: 'completed' });
+
+ expect(finalizeCodexTurn(acc).text).toBe('mine');
+ });
+
+ it('latches the turn id from the first frame that carries one', () => {
+ // Without this the caller has no id to `turn/interrupt` with when the
+ // `turn/start` response is delayed or lost — and a cancelled turn keeps
+ // consuming subscription quota until it ends on its own.
+ const acc = createTurnAccumulator({ threadId: 't' });
+ delta(acc, 'streaming', { turnId: 'turn-9' });
+
+ expect(acc.turnId).toBe('turn-9');
+ });
+
+ it('keeps deltas that arrive after the last completed item', () => {
+ // A second agent message with no closing `item/completed` used to vanish:
+ // once finalText was set, the delta buffer was ignored entirely.
+ const acc = createTurnAccumulator({ threadId: 't', turnId: 'turn-1' });
+ delta(acc, 'preview of one');
+ applyCodexTurnEvent(acc, CODEX_TURN_NOTIFICATIONS.itemCompleted, {
+ threadId: 't', turnId: 'turn-1', item: { type: 'agentMessage', text: 'message one. ' },
+ });
+ delta(acc, 'message two.');
+ complete(acc, { id: 'turn-1', status: 'completed' });
+
+ // The completed item supersedes its own preview deltas, and does not double.
+ expect(finalizeCodexTurn(acc).text).toBe('message one. message two.');
+ });
+
it('records token usage under the subscription, with no invented dollar cost', () => {
- const acc = createTurnAccumulator('turn-1');
+ const acc = createTurnAccumulator({ threadId: 't', turnId: 'turn-1' });
applyCodexTurnEvent(acc, CODEX_TURN_NOTIFICATIONS.tokenUsage, {
threadId: 't',
turnId: 'turn-1',
@@ -269,7 +320,7 @@ describe('classifyCodexTransportError', () => {
// 'context-length' is a SCHEMA_TYPE category — `isRequestSpecificCategory`
// returns true for it, so the caller shrinks and retries instead of taking
// the subscription offline for every other call.
- const acc = createTurnAccumulator('turn-1');
+ const acc = createTurnAccumulator({ threadId: 't', turnId: 'turn-1' });
applyCodexTurnEvent(acc, CODEX_TURN_NOTIFICATIONS.turnCompleted, {
threadId: 't',
turn: { id: 'turn-1', status: 'failed', error: { message: 'too long', codexErrorInfo: 'contextWindowExceeded' } },
diff --git a/server/lib/providerCooldown.js b/server/lib/providerCooldown.js
index c712d748b6..2f5e2fc3bc 100644
--- a/server/lib/providerCooldown.js
+++ b/server/lib/providerCooldown.js
@@ -46,6 +46,11 @@ export const DEFAULT_COOLDOWN_MS = 60 * 1000;
// A usage limit with no parsed reset window. Matches QUOTA_EXCEEDED's hour:
// both mean "the plan is spent", and retrying inside the hour is futile.
export const DEFAULT_USAGE_LIMIT_COOLDOWN_MS = 60 * 60 * 1000;
+// The longest a bench may ever last. A provider-reported reset is trusted over
+// the category table, but not unconditionally: a weekly window, or a value in a
+// unit that merely happens to parse (bare epoch seconds read as a year), would
+// otherwise take a provider offline for days with no path back.
+export const MAX_BENCH_MS = 24 * 60 * 60 * 1000;
// Categories the tiered cascade classifies as schema/type (mirrors
// autoFixer.CATEGORY_TO_TIER's SCHEMA_TYPE entries; kept out of the CoS stack so
@@ -120,7 +125,8 @@ export function resolveProviderBench(analysis) {
* reports it on the rate-limit window). It wins over the category table because
* it is the truth rather than an estimate, but only when it is a real future
* timestamp: a past or unparseable value would otherwise resolve to "unbench
- * immediately", which is exactly the failure a bench exists to prevent.
+ * immediately", which is exactly the failure a bench exists to prevent. It is
+ * also clamped to {@link MAX_BENCH_MS} at the other end.
*
* @param {ReturnType<typeof resolveProviderBench>} bench
* @param {{ resetsAt?: string|number|Date|null, now?: number }} [options]
@@ -129,7 +135,7 @@ export function resolveProviderBench(analysis) {
export function resolveBenchWaitMs(bench, { resetsAt = null, now = Date.now() } = {}) {
if (!bench) return 0;
const resetMs = resetsAt == null ? NaN : new Date(resetsAt).getTime();
- if (Number.isFinite(resetMs) && resetMs > now) return resetMs - now;
+ if (Number.isFinite(resetMs) && resetMs > now) return Math.min(resetMs - now, MAX_BENCH_MS);
if (bench.marker === 'usage-limit') return DEFAULT_USAGE_LIMIT_COOLDOWN_MS;
return bench.waitTimeMs ?? DEFAULT_COOLDOWN_MS;
}
diff --git a/server/lib/providerCooldown.test.js b/server/lib/providerCooldown.test.js
index 07066c9945..4a48ed6ad1 100644
--- a/server/lib/providerCooldown.test.js
+++ b/server/lib/providerCooldown.test.js
@@ -5,6 +5,7 @@ import {
COOLDOWN_MS_BY_CATEGORY,
DEFAULT_COOLDOWN_MS,
DEFAULT_USAGE_LIMIT_COOLDOWN_MS,
+ MAX_BENCH_MS,
isRequestSpecificCategory,
isSchemaTypeCategory,
resolveBenchWaitMs,
@@ -106,6 +107,13 @@ describe('resolveBenchWaitMs', () => {
expect(resolveBenchWaitMs(auth, { now: NOW })).toBe(COOLDOWN_MS_BY_CATEGORY[ERROR_CATEGORIES.AUTH_ERROR]);
});
+ it('clamps an implausibly distant reset so a bad unit cannot bench for days', () => {
+ const bench = resolveProviderBench({ category: ERROR_CATEGORIES.USAGE_LIMIT });
+ const aWeekOut = new Date(NOW + 7 * 24 * 60 * 60_000).toISOString();
+
+ expect(resolveBenchWaitMs(bench, { resetsAt: aWeekOut, now: NOW })).toBe(MAX_BENCH_MS);
+ });
+
it('is zero for a failure that must not bench anything', () => {
expect(resolveBenchWaitMs(resolveProviderBench({ category: ERROR_CATEGORIES.CONTENT_REFUSAL }))).toBe(0);
});
diff --git a/server/services/aiProvider.js b/server/services/aiProvider.js
index 47f7238a6b..cc7d9a610d 100644
--- a/server/services/aiProvider.js
+++ b/server/services/aiProvider.js
@@ -41,26 +41,16 @@ const LM_STUDIO_LOAD_TIMEOUT_MS = 120000;
const DEFAULT_PROVIDER_TIMEOUT_MS = 300000;
/**
- * Resolve a provider for features that need a bounded text call rather than a
- * coding agent.
+ * The shared body of the two resolvers below. `accept` decides which records
+ * count for steps 1 and 2.
*
- * Resolution order:
- * 1. The requested provider (if it can serve text)
- * 2. The user's active provider (if it can serve text)
- * 3. The first enabled API provider configured
- *
- * Steps 1 and 2 accept the Codex ChatGPT-subscription transport, because both
- * name a provider the user chose. Step 3 stays **API-ONLY on purpose**: it is a
+ * Step 3 is deliberately NOT parameterized — it is always `isAPI`. It is a
* blind sweep of whatever happens to be configured, and letting it land on a
* subscription would silently move a background feature's billing from an API
- * key the user is already paying for onto their ChatGPT plan (and, in the other
- * direction, an unavailable subscription must not silently start spending an
- * API key). Switching billing source is a decision, not a fallback.
- *
- * Returns null when nothing is configured — callers should surface a
- * "configure an API provider" hint rather than re-throwing.
+ * key the user already pays for onto their ChatGPT plan. Switching billing
+ * source is a decision, not a fallback.
*/
-export async function resolveTextProvider(requestedProviderId) {
+async function resolveProviderFor(requestedProviderId, accept) {
// One read of providers.json — getAllProviders returns both the active id
// and the full list, so we don't need separate getProviderById/getActiveProvider
// round-trips for each step of the fallback chain.
@@ -71,19 +61,55 @@ export async function resolveTextProvider(requestedProviderId) {
if (requestedProviderId) {
const requested = providers.find(p => p.id === requestedProviderId);
- if (isTextCapable(requested)) return requested;
+ if (accept(requested)) return requested;
}
if (all?.activeProvider) {
const active = providers.find(p => p.id === all.activeProvider);
- if (isTextCapable(active)) return active;
+ if (accept(active)) return active;
}
return providers.find(isAPI) || null;
}
-// The name every existing caller imports. Kept as a permanent alias rather than
-// a codemod: other installs and forks call it, and renaming a public export in
-// place would break them on their own upgrade schedule.
-export { resolveTextProvider as resolveAPIProvider };
+/**
+ * Resolve an API-type provider for features that can only run against an API
+ * endpoint (CLI providers don't support the simple chat-completions call path).
+ *
+ * Resolution order:
+ * 1. The requested provider (if API-type)
+ * 2. The user's active provider (if API-type)
+ * 3. The first enabled API provider configured
+ *
+ * **This must stay API-ONLY.** Most of its callers hand the result to
+ * `promptRunner.runPromptThroughProvider`, which dispatches on `provider.type`
+ * and would run a returned `codex` record through `executeCliRun` — the
+ * file-writing coding harness, in the PortOS checkout, with the network and the
+ * user's MCP servers. Widening this function to accept the subscription text
+ * transport therefore does NOT give those callers a bounded text call; it gives
+ * them a coding agent pointed at the repo. New callers that want the transport
+ * ask for it by name via {@link resolveTextProvider}, which is only safe
+ * because they feed `callProviderAISimple`.
+ *
+ * Returns null when no API provider is configured — callers should surface a
+ * "configure an API provider" hint rather than re-throwing.
+ */
+export async function resolveAPIProvider(requestedProviderId) {
+ return resolveProviderFor(requestedProviderId, isAPI);
+}
+
+/**
+ * Resolve a provider for a bounded text call made through
+ * {@link callProviderAISimple} — the one path that knows how to run the
+ * subscription transport safely.
+ *
+ * Same order as {@link resolveAPIProvider}, except that steps 1 and 2 also
+ * accept the Codex ChatGPT subscription, because both name a provider the user
+ * chose. **Only call this when the result goes to `callProviderAISimple`** — a
+ * `type: 'cli'` record reaching the prompt runner is a coding agent, not a
+ * text call.
+ */
+export async function resolveTextProvider(requestedProviderId) {
+ return resolveProviderFor(requestedProviderId, isTextCapable);
+}
// LM Studio's chat-completions endpoint returns this when no model is in
// memory. The error is identical regardless of which model name the request
diff --git a/server/services/aiProvider.test.js b/server/services/aiProvider.test.js
index afafe81b5f..1efc404033 100644
--- a/server/services/aiProvider.test.js
+++ b/server/services/aiProvider.test.js
@@ -174,6 +174,29 @@ const OPENAI_API = {
id: 'openai', name: 'OpenAI', type: 'api', endpoint: 'https://api.example.com/v1',
};
+describe('resolveAPIProvider stays API-only', () => {
+ const withProviders = (providers, activeProvider = null) =>
+ getAllProviders.mockResolvedValue({ activeProvider, providers });
+
+ it('never returns a CLI record, even one whose text transport is enabled', async () => {
+ // Most of its callers hand the result to promptRunner, which dispatches on
+ // `provider.type` — a `codex` record reaching it runs `executeCliRun`: the
+ // file-writing coding harness, in the PortOS checkout, with the network and
+ // the user's MCP servers. Widening this resolver would silently turn a
+ // universe-refine or mood-board call into exactly that.
+ withProviders([CODEX_ENABLED, OPENAI_API], 'codex');
+
+ await expect(resolveAPIProvider('codex')).resolves.toMatchObject({ id: 'openai' });
+ await expect(resolveAPIProvider(null)).resolves.toMatchObject({ id: 'openai' });
+ });
+
+ it('returns null when only the subscription is configured', async () => {
+ withProviders([CODEX_ENABLED], 'codex');
+
+ await expect(resolveAPIProvider('codex')).resolves.toBeNull();
+ });
+});
+
describe('resolveTextProvider', () => {
const withProviders = (providers, activeProvider = null) =>
getAllProviders.mockResolvedValue({ activeProvider, providers });
@@ -200,9 +223,6 @@ describe('resolveTextProvider', () => {
await expect(resolveTextProvider('codex')).resolves.toMatchObject({ id: 'openai' });
});
- it('is still reachable under its original name', () => {
- expect(resolveAPIProvider).toBe(resolveTextProvider);
- });
});
describe('callProviderAISimple through the ChatGPT subscription', () => {
diff --git a/server/services/codexAppServer.js b/server/services/codexAppServer.js
index 6f9a378421..0630893d09 100644
--- a/server/services/codexAppServer.js
+++ b/server/services/codexAppServer.js
@@ -45,13 +45,13 @@ import {
CODEX_ERROR_CODES,
CODEX_NOTIFICATIONS,
CODEX_RPC,
- CODEX_ACCOUNT_STATUS,
deriveCodexAccountStatus,
describeCodexAccountStatus,
isCodexAuthError,
normalizeCodexAccount,
normalizeCodexLoginStart,
normalizeCodexRateLimits,
+ redactCodexMessage,
redactCodexPayload,
} from '../lib/codexAccount.js';
import {
@@ -142,12 +142,22 @@ const teardown = (target, error) => {
const pendingEntries = [...target.pending.values()];
target.pending.clear();
target.closed = true;
- for (const entry of pendingEntries) entry.reject(error);
- // A turn whose `turn/start` already answered has no pending request to
- // reject, so losing the child would otherwise leave it waiting on a
- // notification that can never arrive.
- failActiveTurns(error);
- if (connection === target) connection = null;
+ for (const entry of pendingEntries) {
+ // Clearing matters more now that turns exist: a request deadline can be the
+ // full 5-minute turn timeout, and an unfired timer for an already-rejected
+ // request keeps a callback armed for the rest of that window.
+ clearTimeout(entry.timer);
+ entry.reject(error);
+ }
+ // A turn whose `turn/start` already answered has no pending request to reject,
+ // so losing the child would otherwise leave it waiting on a notification that
+ // can never arrive. Scoped to the LIVE connection: a stale target's late
+ // `exit` event must not kill turns running on the replacement that took over.
+ const wasLive = connection === target;
+ if (wasLive) {
+ connection = null;
+ failActiveTurns(error);
+ }
};
/**
@@ -202,6 +212,9 @@ const handleNotification = (method, params) => {
// 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;
+ // A completed sign-in is a user action that really did change the account, so
+ // unlike a background readiness poll it may clear an auth/quota bench.
+ if (params?.success !== false) clearCodexTextTransportBench();
settleLogin(params?.success === false ? 'failed' : 'completed');
};
@@ -221,16 +234,14 @@ const routeTurnNotification = (method, params) => {
// The accumulator is pure; a malformed frame can still throw inside a
// normalizer, and this runs on a stdout event handler where an uncaught
// throw would take down the node process.
- // The caller's progress hook runs in its OWN guard: a throwing `onDelta` must
- // not skip the accumulator below, or the finished answer would silently lose
- // that chunk of text.
- if (turn.onDelta && method === CODEX_TURN_NOTIFICATIONS.agentMessageDelta && typeof params.delta === 'string') {
- try {
- turn.onDelta(params.delta);
- } catch (err) {
- console.error(`❌ Codex turn progress hook failed: ${err.message}`);
- }
- }
+ // Whether the accumulator will accept this frame, computed BEFORE applying it
+ // (which may latch the turn id). The progress hook honours the same filters:
+ // streaming another turn's delta, or one that lands after this turn already
+ // failed, would show a consumer partial text from an answer PortOS is going to
+ // refuse.
+ const accepted = turn.acc.status === 'inProgress'
+ && (!turn.acc.turnId || typeof params.turnId !== 'string' || params.turnId === turn.acc.turnId);
+
let terminal = false;
try {
terminal = applyCodexTurnEvent(turn.acc, method, params);
@@ -238,6 +249,19 @@ const routeTurnNotification = (method, params) => {
console.error(`❌ Codex turn event ${method} could not be applied: ${err.message}`);
return;
}
+ // Fired AFTER the accumulator, and in its own guard: a throwing hook must not
+ // skip the frame (the finished answer would silently lose that text), and an
+ // async hook's rejection is invisible to try/catch — unhandled here would be a
+ // process-level crash, since this runs on a stdout event outside any request.
+ if (accepted && turn.onDelta && method === CODEX_TURN_NOTIFICATIONS.agentMessageDelta
+ && typeof params.delta === 'string') {
+ try {
+ Promise.resolve(turn.onDelta(params.delta))
+ .catch((err) => console.error(`❌ Codex turn progress hook rejected: ${err.message}`));
+ } catch (err) {
+ console.error(`❌ Codex turn progress hook failed: ${err.message}`);
+ }
+ }
if (terminal) turn.settle();
};
@@ -262,7 +286,10 @@ const handleFrame = (target, line) => {
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';
+ // Scrubbed, not raw: this message is logged AND returned to the browser by
+ // the `/codex/*` routes, and an upstream failure can quote the credential
+ // that failed ("access_token=… expired").
+ const message = redactCodexMessage(frame.error?.message) ?? 'Codex app-server returned an error';
const rpcError = codexError(
isCodexAuthError(frame.error) ? CODEX_ERROR_CODES.authRevoked : CODEX_ERROR_CODES.protocol,
message,
@@ -454,14 +481,14 @@ const readReadiness = async () => {
}
}
- const readiness = buildReadiness({ runtimeInstalled: true, accountFetched, account, rateLimits, error });
- // A fresh read that says the subscription is ready is the evidence a bench was
- // waiting for — the window reset, or the user signed back in — so the text
- // transport comes back without waiting out the rest of a cooldown. Any other
- // verdict leaves the bench alone: it must expire on its own, not on a probe
- // that merely failed to contradict it.
- if (readiness.status === CODEX_ACCOUNT_STATUS.ready) clearCodexTextTransportBench();
- return readiness;
+ // Deliberately does NOT clear a bench. `ready` is far weaker evidence than it
+ // looks: a per-session budget can be spent while the account's 5h/weekly
+ // windows sit at 60%, and a quota read that merely FAILED also lands on
+ // `ready` (an unread window is not an exhausted one). Clearing on either would
+ // unbench a still-spent subscription on the Providers page's next 15s poll,
+ // and loop that way for the whole window. The bench expires on the reset time
+ // Codex itself reported; only an explicit sign-in or sign-out clears it early.
+ return buildReadiness({ runtimeInstalled: true, accountFetched, account, rateLimits, error });
};
/**
@@ -552,6 +579,10 @@ export async function codexLogout() {
await call(CODEX_RPC.logout);
settleLogin('ended by sign-out');
readinessCache = null;
+ modelsCache = null;
+ // Signing out invalidates whatever the bench was waiting on, and signing back
+ // in must not inherit the previous account's cooldown.
+ clearCodexTextTransportBench();
console.log('🔒 Codex ChatGPT account signed out');
return getCodexAccountReadiness({ fresh: true });
}
@@ -571,6 +602,8 @@ export async function codexLogout() {
const TURN_TIMEOUT_MS = 300_000;
/** The catalog changes when a plan does. Long enough to not re-list per call. */
const MODELS_TTL_MS = 10 * 60_000;
+/** A real catalog is tens of models; this only bounds a misbehaving server. */
+const MODEL_LIST_MAX_PAGES = 20;
/**
* The empty directory every generic text turn runs in.
@@ -646,7 +679,19 @@ export async function listCodexModels({ fresh = false } = {}) {
return { models: modelsCache.models, fetchedAt: modelsCache.at, error: null };
}
try {
- const { models } = normalizeCodexModels(await call(CODEX_TURN_RPC.modelList, {}));
+ // Follow `nextCursor`. A truncated catalog is not just a short picker: a
+ // model on a later page is absent from `cachedModelEntry`, so its effort is
+ // sent unclamped — the exact failure the clamp exists to prevent. The page
+ // cap bounds a server that never stops handing back a cursor.
+ const models = [];
+ let cursor = null;
+ for (let page = 0; page < MODEL_LIST_MAX_PAGES; page += 1) {
+ const result = normalizeCodexModels(await call(CODEX_TURN_RPC.modelList, cursor ? { cursor } : {}));
+ models.push(...result.models);
+ cursor = result.nextCursor;
+ if (!cursor) break;
+ }
+ if (cursor) console.error(`❌ Codex model/list stopped after ${MODEL_LIST_MAX_PAGES} pages with a cursor still pending`);
modelsCache = { at: Date.now(), models };
return { models, fetchedAt: modelsCache.at, error: null };
} catch (err) {
@@ -728,7 +773,7 @@ export async function runCodexTextTurn({
throw codexError(CODEX_ERROR_CODES.protocol, 'Codex started a thread with no id.');
}
- const acc = createTurnAccumulator();
+ const acc = createTurnAccumulator({ threadId });
let settle = null;
let fail = null;
const finished = new Promise((resolve, reject) => { settle = resolve; fail = reject; });
diff --git a/server/services/codexAppServer.turn.test.js b/server/services/codexAppServer.turn.test.js
index 4b1f1bd57f..2ff59d2504 100644
--- a/server/services/codexAppServer.turn.test.js
+++ b/server/services/codexAppServer.turn.test.js
@@ -23,8 +23,10 @@ const { CODEX_TURN_ERROR_CODES } = await import('../lib/codexTurn.js');
const {
__resetCodexAppServer,
benchCodexTextTransport,
+ getCodexAccountReadiness,
getCodexTextTransportBench,
listCodexModels,
+ codexLogout,
peekCodexModels,
runCodexTextTurn,
stopCodexAppServer,
@@ -106,7 +108,9 @@ describe('running a text turn', () => {
expect(start.sandbox).toBe('read-only');
expect(start.approvalPolicy).toBe('never');
expect(start.ephemeral).toBe(true);
- expect(start.config).toEqual({ mcp_servers: {}, tools: { web_search: false }, web_search: false });
+ expect(start.config).toEqual({
+ mcp_servers: {}, tools: { web_search: false }, web_search: false, sandbox_permissions: [],
+ });
expect(start.cwd).toEqual(expect.stringContaining('portos-codex-text-'));
expect(start.cwd.includes('PortOS')).toBe(false);
@@ -250,6 +254,23 @@ describe('model discovery', () => {
expect(child.written.filter((f) => f.method === 'model/list')).toHaveLength(1);
});
+ it('follows the catalog cursor so a later page still reaches the picker', async () => {
+ // A truncated catalog is not just a short picker: a model on a later page is
+ // absent from the effort-clamp lookup, so its effort is sent unvalidated.
+ const promise = listCodexModels();
+ await handshake();
+ await awaitRequest(child, 'model/list', {
+ data: [{ id: 'model-alpha', supportedReasoningEfforts: [] }], nextCursor: 'page-2',
+ });
+ await awaitRequest(child, 'model/list', {
+ data: [{ id: 'model-beta', supportedReasoningEfforts: [] }], nextCursor: null,
+ });
+
+ const result = await promise;
+ expect(result.models.map((m) => m.id)).toEqual(['model-alpha', 'model-beta']);
+ expect(child.written.filter((f) => f.method === 'model/list')[1].params).toEqual({ cursor: 'page-2' });
+ });
+
it('keeps the last-known-good list when a refresh fails', async () => {
const first = listCodexModels();
await handshake();
@@ -270,3 +291,62 @@ describe('model discovery', () => {
expect(peekCodexModels()).toBeNull();
});
});
+
+describe('bench and readiness are independent', () => {
+ it('does not clear a quota bench just because the account reads ready', async () => {
+ // `ready` is weak evidence: a spent per-session budget, or a quota read that
+ // merely FAILED, both land there. Clearing on it would unbench a still-spent
+ // subscription on the Providers page's next 15s poll, forever.
+ benchCodexTextTransport({ waitMs: 60_000, category: 'usage-limit', message: 'session budget spent' });
+
+ const promise = getCodexAccountReadiness({ fresh: true });
+ await handshake();
+ await awaitRequest(child, 'account/read', { account: { type: 'chatgpt', planType: 'pro' } });
+ await awaitRequest(child, 'account/rateLimits/read', { primary: { usedPercent: 60 } });
+
+ await expect(promise).resolves.toMatchObject({ status: 'ready' });
+ expect(getCodexTextTransportBench()).not.toBeNull();
+ });
+
+ it('clears the bench when the user signs out', async () => {
+ benchCodexTextTransport({ waitMs: 60_000, category: 'auth-error', message: 'signed out' });
+
+ const promise = codexLogout();
+ await handshake();
+ await awaitRequest(child, 'account/logout', {});
+ await awaitRequest(child, 'account/read', null);
+ await promise;
+
+ expect(getCodexTextTransportBench()).toBeNull();
+ });
+});
+
+describe('protocol errors that quote a credential', () => {
+ it('scrubs the RPC message before it reaches a log or the HTTP response', async () => {
+ const promise = listCodexModels();
+ await handshake();
+ await awaitRequest(child, 'model/list', (frame) =>
+ child.replyError(frame, { code: -32000, message: 'refresh failed: access_token=sk-live-ABCDEFGH1234 expired' }));
+
+ const result = await promise;
+ expect(result.error.message).not.toMatch(/sk-live-ABCDEFGH1234/);
+ expect(result.error.message).toContain('[redacted]');
+ });
+});
+
+describe('progress hooks', () => {
+ it('never streams a delta belonging to a different turn', async () => {
+ const seen = [];
+ const promise = runCodexTextTurn({ prompt: 'hi', onDelta: (d) => seen.push(d) });
+ await handshake();
+ await awaitRequest(child, 'thread/start', { thread: { id: 'thread-1' } });
+ await awaitRequest(child, 'turn/start', { turn: { id: 'turn-1', items: [], status: 'inProgress' } });
+
+ child.notify('item/agentMessage/delta', { threadId: 'thread-1', turnId: 'turn-1', delta: 'mine' });
+ child.notify('item/agentMessage/delta', { threadId: 'thread-1', turnId: 'turn-2', delta: 'SOMEBODY ELSE' });
+ child.notify('turn/completed', { threadId: 'thread-1', turn: { id: 'turn-1', items: [], status: 'completed' } });
+
+ await expect(promise).resolves.toMatchObject({ text: 'mine' });
+ expect(seen).toEqual(['mine']);
+ });
+});
diff --git a/server/services/taste-questionnaire.js b/server/services/taste-questionnaire.js
index 1cd0fc0513..1931d909bb 100644
--- a/server/services/taste-questionnaire.js
+++ b/server/services/taste-questionnaire.js
@@ -11,7 +11,11 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { atomicWrite, ensureDir, safeJSONParse, PATHS } from '../lib/fileUtils.js';
-import { resolveAPIProvider, callProviderAISimple } from './aiProvider.js';
+// `resolveTextProvider`, not `resolveAPIProvider`: every provider resolved here
+// goes straight to `callProviderAISimple`, which is the one path that can run a
+// ChatGPT-subscription record as a bounded text call. Callers that hand their
+// provider to the prompt runner must keep using the API-only resolver (#5590).
+import { resolveTextProvider, callProviderAISimple } from './aiProvider.js';
import { ServerError } from '../lib/errorHandler.js';
import { buildPrompt } from './promptService.js';
import { digitalTwinEvents } from './digital-twin.js';
@@ -646,7 +650,7 @@ export async function generateSectionSummary(sectionId, providerId, model) {
throw new Error(`No responses to summarize for section: ${sectionId}`);
}
- const provider = await resolveAPIProvider(providerId);
+ const provider = await resolveTextProvider(providerId);
if (!provider) throw new Error(NO_API_PROVIDER_HINT);
const modelId = model || provider.defaultModel;
@@ -720,7 +724,7 @@ export async function generateOverallSummary(providerId, model) {
throw new Error('No taste responses to summarize. Complete at least one section first.');
}
- const provider = await resolveAPIProvider(providerId);
+ const provider = await resolveTextProvider(providerId);
if (!provider) throw new Error(NO_API_PROVIDER_HINT);
const modelId = model || provider.defaultModel;
@@ -915,7 +919,7 @@ export async function generatePersonalizedTasteQuestion(sectionId, providerId, m
const { context, sourcesUsed } = await aggregateIdentityContext(sectionId);
if (!context) return { question: null, reason: 'no-context' };
- const provider = await resolveAPIProvider(providerId);
+ const provider = await resolveTextProvider(providerId);
if (!provider) return { question: null, reason: 'no-provider' };
const modelId = model || provider.defaultModel;
diff --git a/server/services/taste-questionnaire.test.js b/server/services/taste-questionnaire.test.js
index dc8a4e829a..48ee0b0d9a 100644
--- a/server/services/taste-questionnaire.test.js
+++ b/server/services/taste-questionnaire.test.js
@@ -20,7 +20,7 @@ vi.mock('./digital-twin.js', () => ({
// without a live LLM. Re-imported per test because beforeEach resets the module
// registry, which mints fresh spies for each generation.
vi.mock('./aiProvider.js', () => ({
- resolveAPIProvider: vi.fn(),
+ resolveTextProvider: vi.fn(),
callProviderAISimple: vi.fn(),
}));
@@ -140,8 +140,8 @@ describe('generatePersonalizedTasteQuestion outcomes', () => {
});
it('reports no-provider rather than blaming the user documents that do exist', async () => {
- const { resolveAPIProvider } = await import('./aiProvider.js');
- resolveAPIProvider.mockResolvedValue(null);
+ const { resolveTextProvider } = await import('./aiProvider.js');
+ resolveTextProvider.mockResolvedValue(null);
const taste = await import('./taste-questionnaire.js');
await seedIdentityContext(taste);
@@ -152,8 +152,8 @@ describe('generatePersonalizedTasteQuestion outcomes', () => {
});
it('throws AI_PROVIDER_ERROR instead of collapsing a provider failure into "nothing to ask"', async () => {
- const { resolveAPIProvider, callProviderAISimple } = await import('./aiProvider.js');
- resolveAPIProvider.mockResolvedValue(PROVIDER);
+ const { resolveTextProvider, callProviderAISimple } = await import('./aiProvider.js');
+ resolveTextProvider.mockResolvedValue(PROVIDER);
callProviderAISimple.mockResolvedValue({ error: 'Provider returned 401: invalid key' });
const taste = await import('./taste-questionnaire.js');
await seedIdentityContext(taste);
@@ -173,8 +173,8 @@ describe('generatePersonalizedTasteQuestion outcomes', () => {
});
it('returns the question with reason null on success', async () => {
- const { resolveAPIProvider, callProviderAISimple } = await import('./aiProvider.js');
- resolveAPIProvider.mockResolvedValue(PROVIDER);
+ const { resolveTextProvider, callProviderAISimple } = await import('./aiProvider.js');
+ resolveTextProvider.mockResolvedValue(PROVIDER);
callProviderAISimple.mockResolvedValue({ text: ' Which film would you rewatch forever? ' });
const taste = await import('./taste-questionnaire.js');
await seedIdentityContext(taste);