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(cos): give codex agents time to boot MCP servers before paste-verify fails

Adam Eivy4b344d56bd27
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d770e3ad3f..1d143bb9e0 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -47,6 +47,9 @@
- **CoS agents (notably codex) now open their PR as the gh account that matches the repo owner, not gh's mutable active user.** PortOS's own `createPR` pins `GH_TOKEN` to the logged-in gh account whose login matches the repo owner (avoiding the multi-account "must be a collaborator" failure), but a spawned agent running its *own* `gh pr create` — a codex/Claude/CLI CoS agent finishing `/do:pr` — never received that pinning. TUI agents fared worst: `shell.js`'s `buildSafeEnv` strips `GH_TOKEN` from the inherited env entirely, so their `gh` fell back to whatever `hosts.yml` active user happened to be set. A new best-effort `resolveForgeTokenEnv(dir)` (in `server/services/git.js`) resolves just the owner-matched `GH_TOKEN` overlay and is injected into all three agent-spawn env paths — direct CLI (`spawnDirectly`), TUI shell session (`spawnTuiAgent`), and the CoS runner (`spawnViaRunner`). It's provider-agnostic (no codex special-case), returns `{}` when no owner-matched account exists (so single-account installs and GitLab repos are untouched), and is spread before `provider.envVars` so an explicit provider `GH_TOKEN` override still wins.
+- **Codex CoS agents no longer die `paste-not-rendered` while codex boots its MCP servers.** Codex boots any MCP servers configured in the user's global `~/.codex/config.toml` on every headless spawn — including heavyweight interactive ones like `playwright` (fetched via `npx`) or a `node_repl` with `startup_timeout_sec = 120`. That boot can run for tens of seconds up to ~2 minutes, during which codex swallows pastes, renders no `[Pasted Content N chars]` commit marker, and shows only the *tail* of a long paste in its input viewport (never the verified prefix) — so PortOS's paste-verify retry could not confirm delivery and killed the agent after only 3 short attempts (~19s), long before the boot finished (real incident 2026-07-10: `agent-c5a26b40` / `agent-3f4ae3b1`, both on gpt-5.6-sol; the same prompt succeeded days earlier when no MCP servers were configured and codex was ready in <10s). The spawner now detects codex's MCP-boot banner (`Booting MCP server` / `Starting MCP servers`) and extends the paste-retry budget from the fixed 3 attempts to a time budget (150s, covering `node_repl`'s 120s startup plus an `npx` cold download while staying under the idle-reap window), so a slow boot completes and the paste finally lands. If the boot genuinely never finishes, the failure now names the MCP-boot cause and points at the codex config instead of a misleading "still initializing" message. Non-codex TUIs and codex installs without MCP servers are unchanged.
+>>>>>>> a2c2ced23 (fix(cos): give codex agents time to boot MCP servers before paste-verify fails)
+
- **Read-only CoS agents (e.g. reference-watch) on a TUI provider now signal completion via the `.agent-done` sentinel.** The prompt builder's completion decision tree gave every other task shape (reasoning-only, TUI push+PR, CLI) an explicit sentinel instruction, but the `isReadOnly` branch emitted only the bare "Read-Only Task" notice with no sentinel — so a read-only TUI run (reference-watch records its proposals directly in the tracker, then just needs to signal done) never wrote `.agent-done`. The 2s sentinel poll in `spawnTuiAgent` — the primary finalize path and the channel that ingests the run summary — therefore never fired, and the run only completed via the idle-reaper / shell-exit fallback with no clean resolution summary captured. `agentPromptBuilder.js` now routes the read-only branch through a new `buildReadOnlyCompletionSection({ isTui, sentinelPath })` that keeps the do-not-modify guidance and, for TUI agents, appends the write-`.agent-done`-then-stop instruction. CLI/API read-only agents complete on process exit and never poll a sentinel, so they still get the bare notice.
- **Digital Twin Taste questionnaire no longer shows "Question 5 of 3" after follow-ups.** The progress header used total response count (core + follow-ups) as the current question number against a core-only total, so once branching follow-ups fired the counter overran the "of N". It now reports the 1-based index among core questions for that section, so the label stays "Question 2 of 3" even when follow-ups sit between cores.
diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.js
index e3673968e0..0b347a79e4 100644
--- a/server/lib/tuiHandshake.js
+++ b/server/lib/tuiHandshake.js
@@ -642,6 +642,99 @@ export function createReviewLoopTracker() {
};
}
+// ─── Codex MCP-server boot detection ──────────────────────────────────────
+//
+// Codex (unlike Claude Code) boots any MCP servers configured in the user's
+// GLOBAL `~/.codex/config.toml` on every startup — INCLUDING for our headless
+// CoS agents, which never asked for them. A user with heavyweight interactive
+// servers (e.g. `playwright` via `npx @playwright/mcp@latest`, or a `node_repl`
+// with `startup_timeout_sec = 120`) makes codex spend tens of seconds — up to
+// two minutes — booting that stack before its input box will accept a paste.
+//
+// During that boot codex renders its input box EARLY but SWALLOWS pastes, and
+// while it waits on a silent boot subprocess (an `npx` download, a stalled
+// server) its PTY output goes IDLE — indistinguishable from "ready" to the
+// idle-detect readiness heuristic. So the spawner pastes mid-boot, codex
+// swallows it (no `[Pasted Content N chars]` marker, and its single-line input
+// viewport shows only the TAIL of the long paste, never the verifiable prefix),
+// and the paste-verify retry (issue #2192) exhausts its 3 short attempts and
+// fails `paste-not-rendered` — killing codex BEFORE its MCP boot ever finished
+// (real incident 2026-07-10: agent-c5a26b40 / agent-3f4ae3b1, both gpt-5.6-sol;
+// the same prompt succeeded on 2026-07-03..09 back when no MCP servers were
+// configured and codex was ready in <10s).
+//
+// The fix is NOT a new readiness signal (codex gives no reliable boot-complete
+// one — a slow boot looks identical to a ready box) but a boot-aware RETRY
+// BUDGET: once boot chrome is seen, keep re-pasting until codex finishes booting
+// and a paste finally lands its marker, up to MCP_BOOT_PASTE_DEADLINE_MS. The
+// spawner (agentTuiSpawning.js) consumes `createMcpBootTracker` for exactly that.
+//
+// Matched against ANSI-stripped output. Detection is deliberately conservative,
+// same rationale as MERGE_QUEUE_MARKERS: a false POSITIVE only extends the
+// (bounded) retry window, and a false NEGATIVE just preserves the pre-fix 3-retry
+// behavior. The two phrases are anchored to codex's literal boot banners rather
+// than a bare "mcp server" substring so an agent whose prompt/output merely
+// mentions MCP servers can't latch the extended window.
+const MCP_BOOT_MARKERS = ['booting mcp server', 'starting mcp servers'];
+
+// Covers a `node_repl` with the documented `startup_timeout_sec = 120` plus an
+// `npx`-fetched server's cold download and margin, while still bounding a
+// genuinely-hung boot's failure. Kept under the 180s default idle-reap window so
+// the boot-retry loop resolves (succeeds or fails cleanly) before the idle
+// reaper can race it.
+export const MCP_BOOT_PASTE_DEADLINE_MS = 150000;
+// Spacing between paste retries while codex is booting MCP servers. A swallowed
+// mid-boot paste renders nothing, so a re-paste every few seconds is a cheap
+// no-op until the box is finally live; this is additive to each attempt's own
+// marker-wait + verify window (~5.5s), so the effective cadence is ~10s.
+export const MCP_BOOT_PASTE_RETRY_DELAY_MS = 5000;
+
+// Rolling tail cap for createMcpBootTracker's cross-chunk buffer, same rationale
+// as REVIEW_LOOP_TAIL_CAP: a boot banner can split across two onData chunks
+// during streaming, so concatenate onto a short tail before testing.
+const MCP_BOOT_TAIL_CAP = 256;
+
+/**
+ * True when a chunk of ANSI-stripped TUI output shows codex booting its MCP
+ * servers. Callers MUST pass stripped output. Non-string / empty input → false.
+ *
+ * @param {string} strippedText — ANSI-stripped output (a chunk or accumulator).
+ * @returns {boolean}
+ */
+export function isMcpBootSignal(strippedText) {
+ if (typeof strippedText !== 'string' || !strippedText) return false;
+ const lower = strippedText.toLowerCase();
+ return MCP_BOOT_MARKERS.some((marker) => lower.includes(marker));
+}
+
+/**
+ * Latching tracker for "this TUI is booting its MCP servers" — the codex slow-
+ * boot failure mode above. Feed it each ANSI-stripped STARTUP chunk (before the
+ * prompt is submitted) via `observe(text)`; it latches `active` the first time a
+ * boot banner appears and STAYS active thereafter. Latching (not a sliding
+ * window) is deliberate: the boot banner prints once and then codex updates the
+ * line via cursor-positioned partial redraws that don't reprint the full phrase,
+ * and the whole point is to keep the extended paste-retry budget in force across
+ * the (often silent) boot. Keeps a small rolling tail so a marker split across a
+ * chunk boundary still matches. Lives here so the detection is unit-testable.
+ *
+ * @returns {{ observe: (strippedText: string) => boolean, readonly active: boolean }}
+ */
+export function createMcpBootTracker() {
+ let active = false;
+ let tail = '';
+ return {
+ observe(strippedText) {
+ if (active) return true;
+ if (typeof strippedText !== 'string' || !strippedText) return active;
+ tail = (tail + strippedText).slice(-MCP_BOOT_TAIL_CAP);
+ if (isMcpBootSignal(tail)) active = true;
+ return active;
+ },
+ get active() { return active; },
+ };
+}
+
// ─── Buffer caps (defensive RAM bounds) ───────────────────────────────────
//
// RAW caps stay small — the raw PTY stream is only used for paste-marker
diff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.js
index 98cdb6e6d7..dd39937847 100644
--- a/server/lib/tuiHandshake.test.js
+++ b/server/lib/tuiHandshake.test.js
@@ -18,6 +18,10 @@ import {
REVIEW_LOOP_IDLE_TIMEOUT_MS,
isReviewLoopSignal,
createReviewLoopTracker,
+ MCP_BOOT_PASTE_DEADLINE_MS,
+ MCP_BOOT_PASTE_RETRY_DELAY_MS,
+ isMcpBootSignal,
+ createMcpBootTracker,
rendersWorkCounter,
PASTE_TO_ENTER_MIN_DELAY_MS,
PASTE_TO_ENTER_FALLBACK_MS,
@@ -380,6 +384,59 @@ describe('tuiHandshake — review-loop idle suppression', () => {
});
});
+describe('tuiHandshake — codex MCP-boot paste patience (agent-c5a26b40)', () => {
+ it('deadline covers a node_repl startup_timeout_sec=120 plus margin, under the idle-reap window', () => {
+ // Long enough for the documented 120s node_repl startup + an npx cold
+ // download, short enough to resolve before the 180s default idle reaper.
+ expect(MCP_BOOT_PASTE_DEADLINE_MS).toBe(150000);
+ expect(MCP_BOOT_PASTE_DEADLINE_MS).toBeGreaterThan(120000);
+ expect(MCP_BOOT_PASTE_DEADLINE_MS).toBeLessThan(DEFAULT_TUI_IDLE_TIMEOUT_MS);
+ expect(MCP_BOOT_PASTE_RETRY_DELAY_MS).toBe(5000);
+ });
+
+ it('isMcpBootSignal matches codex MCP boot banners (case-insensitive)', () => {
+ expect(isMcpBootSignal('Booting MCP server: codex_apps(0s • esc to interrupt)')).toBe(true);
+ expect(isMcpBootSignal('Starting MCP servers (0/3): codex_apps, node_repl, playwright')).toBe(true);
+ expect(isMcpBootSignal('STARTING MCP SERVERS (3/3)')).toBe(true);
+ });
+
+ it('isMcpBootSignal ignores ordinary output that merely mentions MCP', () => {
+ // Conservative anchoring: a prompt/output that talks ABOUT mcp servers must
+ // not latch the extended budget (a false positive only slows a failure, but
+ // keep it tight anyway — mirrors the merge-queue/review-loop discipline).
+ expect(isMcpBootSignal('Configure the mcp server in server/services/voice/tools.js')).toBe(false);
+ expect(isMcpBootSignal('the playwright MCP server is slow')).toBe(false);
+ expect(isMcpBootSignal('')).toBe(false);
+ expect(isMcpBootSignal(null)).toBe(false);
+ expect(isMcpBootSignal(undefined)).toBe(false);
+ });
+
+ it('createMcpBootTracker latches on first banner and stays active through the silent boot', () => {
+ const tracker = createMcpBootTracker();
+ expect(tracker.active).toBe(false);
+ // Ordinary startup banner chrome — not a boot signal.
+ tracker.observe('>_ OpenAI Codex (v0.144.1) permissions: YOLO mode');
+ expect(tracker.active).toBe(false);
+ // MCP boot begins — latches.
+ expect(tracker.observe('Starting MCP servers (0/3): codex_apps, node_repl, playwright')).toBe(true);
+ expect(tracker.active).toBe(true);
+ // Codex updates the line via cursor-positioned partial redraws that do NOT
+ // reprint the full phrase, and the boot subprocess can go silent (npx
+ // download) — neither must un-latch the extended patience.
+ tracker.observe('servers (3/4');
+ tracker.observe('');
+ expect(tracker.active).toBe(true);
+ });
+
+ it('createMcpBootTracker latches on a banner split across two chunks', () => {
+ const tracker = createMcpBootTracker();
+ tracker.observe('• You have 3 usage limit resets available. Booting MCP');
+ expect(tracker.active).toBe(false);
+ expect(tracker.observe(' server: codex_apps(0s • esc to interrupt)')).toBe(true);
+ expect(tracker.active).toBe(true);
+ });
+});
+
describe('tuiHandshake.inferTuiCommand', () => {
// Catch-all default also returns claude; the claude rows just confirm
// an explicit match isn't accidentally tagged codex/antigravity/gemini.
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 98c4295db0..6ea045ec09 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -37,6 +37,9 @@ import {
createWorkActivityTracker,
createMergeQueueTracker,
createReviewLoopTracker,
+ createMcpBootTracker,
+ MCP_BOOT_PASTE_DEADLINE_MS,
+ MCP_BOOT_PASTE_RETRY_DELAY_MS,
createInputReadyTracker,
rendersWorkCounter,
PASTE_TO_ENTER_MIN_DELAY_MS,
@@ -365,6 +368,15 @@ export async function spawnTuiAgent({
// isn't reaped as a false `idle-complete` success before it reaches the
// merge gate (issue observed on agent-61508f36, PR #2084).
const reviewLoop = createReviewLoopTracker();
+ // Latches once codex prints its MCP-server boot banner during startup. A user
+ // with heavyweight interactive MCP servers in ~/.codex/config.toml (playwright
+ // via npx, a node_repl with startup_timeout_sec=120) makes codex spend tens of
+ // seconds — up to ~2min — booting them before its input box accepts a paste,
+ // far longer than the default 3-attempt paste-retry window. While latched, the
+ // paste-retry loop below extends its budget to MCP_BOOT_PASTE_DEADLINE_MS so a
+ // slow boot completes and the paste finally lands, instead of being killed
+ // `paste-not-rendered` mid-boot (incident 2026-07-10, agent-c5a26b40).
+ const mcpBoot = createMcpBootTracker();
// Tracks claude's interactive input-readiness (footer chrome) and its first-run
// folder-trust gate. Gates the prompt paste for the claude TUI so we never
// paste into a startup banner, a trust menu, or a returned shell prompt.
@@ -720,6 +732,10 @@ export async function spawnTuiAgent({
// injected — earlier toggles belong to shell startup and the readiness
// probe, not to claude.
if (!promptSentAt && commandInjected) inputReady.observe(text, stripped);
+ // Latch codex's MCP-server boot banner during startup (before the prompt is
+ // submitted, so codex's own boot chrome — not the echoed prompt — is what
+ // trips it). Gates the extended, boot-aware paste-retry budget below.
+ if (!promptSubmittedAt && stripped && !mcpBoot.active) mcpBoot.observe(stripped);
const now = Date.now();
// Once the prompt is SUBMITTED (Enter sent — not merely pasted), watch for
// proof the model is actually working. Keying on promptSubmittedAt (not
@@ -879,6 +895,10 @@ export async function spawnTuiAgent({
// Computed once up front so retry attempts use the same verification target.
const verifiablePrefix = extractVerifiablePromptPrefix(prompt);
let pasteAttempt = 0;
+ // Wall-clock of the FIRST paste attempt — the anchor for the MCP-boot-aware
+ // retry deadline (retries are time-bounded, not attempt-count-bounded, while
+ // codex is still booting its MCP servers).
+ let firstPasteStartedAt = null;
const sendPrompt = async (reason) => {
if (finalized || promptSentAt) return;
@@ -907,6 +927,7 @@ export async function spawnTuiAgent({
const attemptPaste = (reason) => {
pasteAttempt += 1;
const attemptNum = pasteAttempt;
+ if (firstPasteStartedAt === null) firstPasteStartedAt = Date.now();
if (pasteEnterTimer) { clearInterval(pasteEnterTimer); pasteEnterTimer = null; }
if (pasteVerifyTimer) { clearInterval(pasteVerifyTimer); pasteVerifyTimer = null; }
// Start capturing post-paste output. Set BEFORE writing the paste so
@@ -978,24 +999,49 @@ export async function spawnTuiAgent({
isPasteConfirmed(buffer, { verifiablePrefix, promptMarkerCount });
// Markerless AND the prompt text never rendered → the paste was swallowed by
- // a still-initializing TUI (issue #2192). Retry with backoff, then fail.
+ // a still-initializing TUI (issue #2192). Retry, then fail.
+ //
+ // Budget is boot-aware: once codex's MCP-boot banner has been seen (mcpBoot
+ // active), the boot can legitimately run for tens of seconds — up to ~2min
+ // for a node_repl/npx server — during which EVERY paste is swallowed. Switch
+ // from the fixed 3-attempt/exponential-backoff budget to a TIME budget
+ // (MCP_BOOT_PASTE_DEADLINE_MS from the first paste) with a fixed cadence, so
+ // retries outlast the boot and the paste finally lands once the input box is
+ // live (incident 2026-07-10, agent-c5a26b40). No MCP boot → unchanged.
const retryOrFailPaste = () => {
if (finalized) return;
- if (attemptNum < PASTE_RETRY_MAX_ATTEMPTS) {
- const retryDelayMs = PASTE_RETRY_BASE_DELAY_MS * Math.pow(2, attemptNum - 1);
- appendLine(`⚠️ Paste verification failed — prompt text not found in buffer, retrying in ${retryDelayMs}ms`);
+ const bootActive = mcpBoot.active;
+ const withinBudget = bootActive
+ ? (Date.now() - firstPasteStartedAt) < MCP_BOOT_PASTE_DEADLINE_MS
+ : attemptNum < PASTE_RETRY_MAX_ATTEMPTS;
+ if (withinBudget) {
+ const retryDelayMs = bootActive
+ ? MCP_BOOT_PASTE_RETRY_DELAY_MS
+ : PASTE_RETRY_BASE_DELAY_MS * Math.pow(2, attemptNum - 1);
+ const bootNote = bootActive
+ ? ` (waiting for ${tuiConfig.command} MCP servers to finish booting)`
+ : '';
+ appendLine(`⚠️ Paste verification failed — prompt text not found in buffer, retrying in ${retryDelayMs}ms${bootNote}`);
setTimeout(() => {
if (finalized) return;
attemptPaste(reason);
}, retryDelayMs);
return;
}
- // Max retries exhausted — fail the agent
- appendLine(`❌ Paste verification failed after ${PASTE_RETRY_MAX_ATTEMPTS} attempts — prompt never rendered`);
- finishStartupFailure(
- 'paste-not-rendered',
- `${tuiConfig.command} was still initializing and the paste was silently swallowed. The prompt never appeared in the TUI buffer after ${PASTE_RETRY_MAX_ATTEMPTS} attempts.`,
- ).catch(err => emitLog('error', `TUI agent ${agentId} finishStartupFailure(paste-not-rendered) failed: ${err?.message || err}`, { agentId }));
+ // Budget exhausted — fail the agent, naming the MCP-boot cause when that's
+ // what kept the paste from landing so the operator knows to check their
+ // codex config rather than chasing a phantom paste-timing bug.
+ const bootSecs = Math.round(MCP_BOOT_PASTE_DEADLINE_MS / 1000);
+ const summary = bootActive
+ ? `${tuiConfig.command} did not finish booting its MCP servers within ${bootSecs}s, so the prompt was never delivered. A slow or hung MCP server in your ~/.codex config (e.g. playwright via npx, or a node_repl) blocks codex from accepting input — disable or fix it, or remove it for headless runs.`
+ : `${tuiConfig.command} was still initializing and the paste was silently swallowed. The prompt never appeared in the TUI buffer after ${PASTE_RETRY_MAX_ATTEMPTS} attempts.`;
+ appendLine(
+ bootActive
+ ? `❌ Paste never landed after ${bootSecs}s of waiting for MCP servers to boot — prompt never rendered`
+ : `❌ Paste verification failed after ${PASTE_RETRY_MAX_ATTEMPTS} attempts — prompt never rendered`,
+ );
+ finishStartupFailure('paste-not-rendered', summary)
+ .catch(err => emitLog('error', `TUI agent ${agentId} finishStartupFailure(paste-not-rendered) failed: ${err?.message || err}`, { agentId }));
};
const pasteSentAt = Date.now();
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 8567e6472e..dae0532f95 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -972,6 +972,91 @@ describe('spawnTuiAgent runtime', () => {
expect(pasteWrites()).toHaveLength(1);
});
+ // ── 1d. Codex MCP-server boot patience (incident 2026-07-10, agent-c5a26b40) ──
+ // Codex boots the user's globally-configured MCP servers (playwright via npx,
+ // a node_repl with startup_timeout_sec=120) on every headless spawn. During
+ // that boot codex swallows pastes and renders no `[Pasted Content N chars]`
+ // marker, and its input viewport shows only the paste TAIL (never the verified
+ // prefix), so the paste-verify retry can't confirm. With the fixed 3-attempt
+ // budget the agent was killed `paste-not-rendered` at ~19s — long before a
+ // legitimately-slow boot finishes. Once the MCP-boot banner is seen, the retry
+ // budget must extend to MCP_BOOT_PASTE_DEADLINE_MS so a slow boot completes and
+ // the paste finally lands.
+ it('codex MCP boot: extends the paste-retry budget past the fixed 3-attempt cap while booting', async () => {
+ const pasteFailSpy = vi.fn();
+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async (args) => {
+ if (args?.completionReason === 'paste-not-rendered') pasteFailSpy(args);
+ });
+
+ runSpawn({ prompt: 'evaluate our animation prompts and generate drafts' });
+ await flushMicrotasks();
+
+ // Codex prints its MCP-boot banner during startup → latches the boot tracker.
+ await capturedOnData(Buffer.from('>_ OpenAI Codex (v0.144.1)\nStarting MCP servers (0/3): codex_apps, node_repl, playwright\n'));
+ await flushMicrotasks();
+ // Fire the paste (past prompt-delay floor + readiness idle threshold).
+ await vi.advanceTimersByTimeAsync(2000);
+ await flushMicrotasks();
+
+ // No marker and no echo ever arrive — every attempt is swallowed. Advance
+ // well past the ~19s that would exhaust the fixed 3-attempt budget, but under
+ // the 150s MCP-boot deadline.
+ await vi.advanceTimersByTimeAsync(45000);
+ await flushMicrotasks();
+
+ // Boot-aware budget kept retrying instead of failing paste-not-rendered…
+ expect(pasteFailSpy).not.toHaveBeenCalled();
+ // …and re-pasted more times than the 3-attempt cap would ever allow.
+ expect(pasteCount()).toBeGreaterThan(3);
+ });
+
+ it('codex MCP boot: fails paste-not-rendered only after the extended deadline if boot never completes', async () => {
+ let resolveComplete;
+ const completeDone = new Promise((r) => { resolveComplete = r; });
+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });
+
+ runSpawn();
+ await flushMicrotasks();
+ await capturedOnData(Buffer.from('Booting MCP server: node_repl(0s • esc to interrupt)\n'));
+ await flushMicrotasks();
+ await vi.advanceTimersByTimeAsync(2000);
+ await flushMicrotasks();
+
+ // Never becomes ready. Advance past MCP_BOOT_PASTE_DEADLINE_MS (150s).
+ await vi.advanceTimersByTimeAsync(155000);
+ vi.useRealTimers();
+ await completeDone;
+
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agent-1', success: false, completionReason: 'paste-not-rendered' })
+ );
+ });
+
+ it('paste-not-rendered: without an MCP-boot banner, still fails after the fixed 3 attempts (~19s)', async () => {
+ let resolveComplete;
+ const completeDone = new Promise((r) => { resolveComplete = r; });
+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });
+
+ runSpawn();
+ await flushMicrotasks();
+ // Ordinary banner chrome — NOT an MCP-boot signal, so the budget stays fixed.
+ await capturedOnData(Buffer.from('Codex booting...\n'));
+ await flushMicrotasks();
+ await vi.advanceTimersByTimeAsync(2000);
+ await flushMicrotasks();
+
+ // No marker/echo. Advance past the 3-attempt budget (~19s) but well under the
+ // 150s MCP-boot deadline — proves the non-boot path is unchanged.
+ await vi.advanceTimersByTimeAsync(25000);
+ vi.useRealTimers();
+ await completeDone;
+
+ expect(pasteCount()).toBe(3);
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agent-1', success: false, completionReason: 'paste-not-rendered' })
+ );
+ });
+
// ── 2. Command-not-found path ────────────────────────────────────────────────
it('command-not-found: finalizeAgent called with success:false, exitCode 127, completionReason=command-not-found', async () => {
const spawnPromise = runSpawn();