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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: stop Codex nudges after terminal model-access rejection (#9319)
[._.]/ Adam Eivye08be39cddd7
diff --git a/server/services/agentTuiSpawning/codexModelRejection.js b/server/services/agentTuiSpawning/codexModelRejection.jsnew file mode 100644index 0000000000..efe79535c4--- /dev/null+++ b/server/services/agentTuiSpawning/codexModelRejection.js@@ -0,0 +1,72 @@+// A Codex screen is arbitrary agent output until terminal chrome corroborates+// it. Keep this separate from the one-shot immediate-fallback detector: a tool+// can legitimately print an error fixture while its agent is still working.+const BUFFER_CAP = 4096;+const SETTLE_MS = 5000;+const ERROR_PREFIX = /(?:^|[\r\n])[ \t]*■\s*Unexpected\s*status\s*400\s*Bad\s*Request\s*:\s*/i;+const TURN_ENDED = /(?:^|[\r\n])[ \t]*[─━]+\s*Worked\s*for\s+[^\r\n]+[\r\n]/i;+const IDLE_COMPOSER = /(?:^|[\r\n])[ \t]*›[ \t]*Ask\s*Codex[^\r\n]*[\r\n]/i;+const WORKING = /esc\s*to\s*interrupt|(?:^|[\r\n])[ \t]*[•●]\s*(?:Working|Thinking|Running|Reconnecting)\b/i;++export function createCodexModelRejectionGate() {+ let buffer = '';+ let pending = null;++ return {+ observe(chunk) {+ if (!chunk) return;+ const next = buffer + chunk;+ // Do not manufacture a line start at a rolling-window slice boundary.+ buffer = next.length > BUFFER_CAP+ ? next.slice(-BUFFER_CAP).replace(/^[^\r\n]*/, '')+ : next;+ pending = null;+ const prefix = ERROR_PREFIX.exec(buffer);+ if (!prefix) return;+ const afterPrefix = buffer.slice(prefix.index + prefix[0].length);+ // The known envelope has an error object inside the response object.+ // Parse it instead of treating keywords in prose as a structured error.+ const envelope = /^(\{[\s\S]*?\}\s*\})/.exec(afterPrefix);+ if (!envelope) return;+ let response;+ try {+ // Codex hard-wraps JSON even inside strings when rendering the screen.+ response = JSON.parse(envelope[1].replace(/[\r\n]/g, ''));+ } catch {+ return;+ }+ if (response?.error?.type !== 'invalid_request_error'+ || typeof response.error.message !== 'string'+ || !/model\s*is\s*not\s*supported\s*when\s*using\s*Codex\s*with\s*a\s*ChatGPT\s*account/i.test(response.error.message)) return;++ const afterError = afterPrefix.slice(envelope[0].length);+ const ended = TURN_ENDED.exec(afterError);+ if (!ended) return;+ const afterTurn = afterError.slice(ended.index + ended[0].length);+ const composer = IDLE_COMPOSER.exec(afterTurn);+ // A fresh empty composer alone also renders DURING a live turn. Require+ // the turn-end separator before it and invalidate on any later work.+ if (!composer || WORKING.test(afterError)) return;+ const afterComposer = afterTurn.slice(composer.index + composer[0].length);+ // Only footer chrome may follow: subsequent tool/assistant output makes+ // this a quoted fixture or a recovered session, never a terminal verdict.+ if (afterComposer.split(/[\r\n]/).some(line => line.trim()+ && !/^[ \t]*(?:\?\s*for\s*shortcuts|\d+%\s*context\s*left|[─━]+)[^\r\n]*$/i.test(line))) return;+ pending = {+ category: 'model-not-supported',+ actionable: true,+ origin: 'provider',+ message: 'Codex rejected the selected model for the signed-in ChatGPT account.',+ suggestedFix: 'Choose a model supported by the signed-in Codex account, or clear the model override to use the CLI default. API-key authentication uses separate API billing.',+ escalation: 'Pick a model the provider account supports (or clear the override to use the CLI default), then approve the retry.',+ };+ },+ takeRejected(now, lastOutputAt) {+ if (!pending || now - lastOutputAt < SETTLE_MS) return null;+ const result = pending;+ pending = null;+ buffer = '';+ return result;+ },+ };+}diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.jsindex 5a8db606af..618485573f 100644--- a/server/services/agentTuiSpawning/sessionController.js+++ b/server/services/agentTuiSpawning/sessionController.js@@ -41,6 +41,7 @@ import { createClaudeSessionLimitBannerDetector, createImmediateFallbackSignalDeimport { isAntigravityCommand } from '../../lib/antigravity.js';import { isCodexCommand } from '../../lib/codex.js';import { isClaudeCommand } from '../../lib/providerModels.js';+import { createCodexModelRejectionGate } from './codexModelRejection.js';import {READY_POLL_INTERVAL_MS,READY_IDLE_THRESHOLD_MS,@@ -632,6 +633,7 @@ export function createTuiSessionController({// not `spawnCommand` — a credential-bootstrap wrap makes the latter the// bootstrap CLI.const isCodexSession = isCodexCommand(tuiConfig.command);+ const codexModelRejectionGate = isCodexSession ? createCodexModelRejectionGate() : null;// Latches once codex's composer placeholder paints — the positive "the input// box exists" signal the idle heuristic lacks. See// CODEX_COMPOSER_READY_PATTERN; consumed by the idle paste branch below.@@ -1252,6 +1254,7 @@ export function createTuiSessionController({if (isCodexSession && !codexComposerReady && !promptSentAt && commandInjected && stripped&& CODEX_COMPOSER_READY_PATTERN.test(stripped)) codexComposerReady = true;const now = Date.now();+ if (promptSubmittedAt) codexModelRejectionGate?.observe(stripped);// Startup-idle detection (the promptTimer's non-inputReady branch below)// reads lastOutputAt/firstOutputAt to decide the TUI has gone quiet and is// ready for the prompt paste. Gate them on commandInjected for the same@@ -1721,6 +1724,19 @@ export function createTuiSessionController({// One clock for every gate on this tick. They all measure the same silence,// so reading the wall four times only invites them to disagree about it.const now = Date.now();+ // A completed Codex turn that rejected account model access cannot be+ // repaired by any continuation nudge. Preserve its actionable outcome+ // without changing the pinned model or authentication/billing mode.+ const modelRejection = sessionPhase === 'running' && promptSubmittedAt+ ? codexModelRejectionGate?.takeRejected(now, lastOutputAt)+ : null;+ if (modelRejection && !sentinelPresent()) {+ immediateFallbackAnalysis = { ...modelRejection, affectedModel: model, configuredModel: model };+ appendLine(`❌ ${modelRejection.message}`);+ finish({ success: false, exitCode: 1, error: modelRejection.message, reason: 'model-access-rejected' })+ .catch(err => emitLog('error', `TUI agent ${agentId} model-access finish failed: ${err?.message || err}`, { agentId }));+ return;+ }const expired = selfClearingGate.takeExpired(now);if (expired) {// setInterval can't await, and an unhandled rejection here would crash thediff --git a/server/services/agentTuiSpawning/sessionController.test.js b/server/services/agentTuiSpawning/sessionController.test.jsindex 565b1c7562..87b75a6696 100644--- a/server/services/agentTuiSpawning/sessionController.test.js+++ b/server/services/agentTuiSpawning/sessionController.test.js@@ -18,6 +18,7 @@*/import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { STALL_NUDGE_IDLE_MS, STALL_NUDGE_TEXT } from '../../lib/tuiHandshake.js';vi.mock('../cosEvents.js', () => ({ emitLog: vi.fn() }));@@ -65,6 +66,7 @@ function makeController({write: vi.fn(),paste: vi.fn(() => ({ /* a live submit-Enter interval handle */ })),kill: vi.fn(),+ resolveErrorAnalysis: vi.fn(async ({ immediateFallbackAnalysis }) => immediateFallbackAnalysis),};const controller = createTuiSessionController({agentId: 'agent-8021',@@ -112,9 +114,9 @@ function makeController({},finalization: {finalizeAgent: seams.finalizeAgent,- finalizeRunCommon: () => ({ outcome: 'completed', finalSuccess: true, finalError: null, terminatedByUser: false }),+ finalizeRunCommon: ({ success, error }) => ({ outcome: success ? 'completed' : 'failed', finalSuccess: success, finalError: error, terminatedByUser: false }),shouldAbandonRun: () => false,- resolveErrorAnalysis: vi.fn().mockResolvedValue(null),+ resolveErrorAnalysis: seams.resolveErrorAnalysis,runCompletionCleanup: seams.runCompletionCleanup,},probeMergeGatePr: async () => prProbe,@@ -255,3 +257,82 @@ describe('TUI session controller — teardown owns its own machinery (#8021)', (expect(finalizeAgent).toHaveBeenCalledTimes(1);});});++describe('Codex terminal model-access rejection (#9319)', () => {+ const rejection = '\n■ Unexpected status 400 Bad Request: ' + JSON.stringify({+ error: {+ message: "The 'example-model' model is not supported when using Codex with a ChatGPT account.",+ type: 'invalid_request_error', param: null, code: null,+ },+ }) + '\n';+ const ended = '─ Worked for 1s ─────────────────\n';+ const composer = '› Ask Codex to do anything\n ? for shortcuts\n';++ beforeEach(() => { vi.useFakeTimers(); });+ afterEach(() => { vi.useRealTimers(); });++ const submitted = async (options) => {+ const subject = makeController(options);+ subject.controller.attachSession({ sessionId: 'session-abcdef12', pid: 4242 });+ subject.controller.markCommandInjected();+ await subject.controller.handleData(composer);+ await vi.advanceTimersByTimeAsync(3000);+ await subject.controller.handleData('do the work\n');+ await vi.advanceTimersByTimeAsync(4000);+ subject.write.mockClear();+ return subject;+ };++ it('settles a chunked structured rejection, finalizes once, and tears down without continuing', async () => {+ const { controller, paste, write, finalizeAgent, resolveErrorAnalysis, kill, closers } = await submitted();+ for (const chunk of [rejection.slice(0, 90), rejection.slice(90), ended, composer]) {+ await controller.handleData(chunk);+ }+ await vi.advanceTimersByTimeAsync(4000);+ expect(finalizeAgent).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(6000);+ expect(resolveErrorAnalysis).toHaveBeenCalledWith(expect.objectContaining({+ immediateFallbackAnalysis: expect.objectContaining({ category: 'model-not-supported', actionable: true, origin: 'provider' }),+ }));+ expect(finalizeAgent).toHaveBeenCalledWith(expect.objectContaining({+ success: false, exitCode: 1, completionReason: 'model-access-rejected',+ errorAnalysis: expect.objectContaining({ category: 'model-not-supported' }),+ }));+ expect(paste).not.toHaveBeenCalled();+ expect(write).not.toHaveBeenCalled();+ expect(controller.isTerminal()).toBe(true);+ expect(vi.getTimerCount()).toBe(0);+ expect(closers[0]).toHaveBeenCalledTimes(1);+ expect(kill).toHaveBeenCalledTimes(1);+ await controller.handleExit({ exitCode: 1 });+ await controller.handleData(rejection + ended + composer);+ await vi.advanceTimersByTimeAsync(STALL_NUDGE_IDLE_MS * 2);+ expect(finalizeAgent).toHaveBeenCalledTimes(1);+ });++ it.each([+ ['no fresh completed turn', rejection + composer],+ ['no fresh empty composer', rejection + ended],+ ['transient HTTP failure', rejection.replace('400 Bad Request', '500 Internal Server Error') + ended + composer],+ ['quoted prose', '> ' + rejection.trimStart() + ended + composer],+ ['productive tool output after a fixture', rejection + ended + composer + '• Running tests (1s • esc to interrupt)\n'],+ ['recovered assistant output', rejection + ended + composer + 'The tests passed; committing the fix.\n'],+ ])('preserves ordinary continuation for %s', async (_name, output) => {+ const { controller, paste, finalizeAgent } = await submitted();+ await controller.handleData(output);+ await vi.advanceTimersByTimeAsync(STALL_NUDGE_IDLE_MS + 10000);+ expect(finalizeAgent).not.toHaveBeenCalled();+ expect(paste).toHaveBeenCalledWith(STALL_NUDGE_TEXT, expect.any(Object));+ await controller.handleExit({ exitCode: 0 });+ });++ it('discards a corroborated fixture when productive output resumes in a later chunk', async () => {+ const { controller, finalizeAgent } = await submitted();+ await controller.handleData(rejection + ended + composer);+ await vi.advanceTimersByTimeAsync(2000);+ await controller.handleData('• Working (2s • esc to interrupt)\n');+ await vi.advanceTimersByTimeAsync(10000);+ expect(finalizeAgent).not.toHaveBeenCalled();+ await controller.handleExit({ exitCode: 0 });+ });+});