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: wait for a codex TUI paste to commit instead of re-pasting over it

[._.]/ Adam Eivy12575a5c02af
diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.js
index f91f073061..861971c492 100644
--- a/server/lib/tuiHandshake.js
+++ b/server/lib/tuiHandshake.js
@@ -78,6 +78,39 @@ export const PASTE_MARKER_PATTERN = /\[Pasted?\s*(?:text\s*#\d+[^\]]*|content\s*
export const PASTE_TO_ENTER_MIN_DELAY_MS = 200;
export const PASTE_TO_ENTER_FALLBACK_MS = 3500;
+// Codex QUEUES a bracketed paste that arrives before its composer has finished
+// initializing and commits it once the composer is live — it is not lost. On a
+// cold Windows start (`cmd.exe /c codex.cmd` -> node -> the native binary) that
+// commit was measured at ~11s for a paste written at 3.7s, far past the 3.5s
+// marker wait + 2s verify window above. The first attempt was therefore
+// declared swallowed and the retry ladder wrote a SECOND 29KB bracketed paste
+// on top of the queued one; codex then committed NEITHER, all three attempts
+// "failed", and the agent was killed `paste-not-rendered` with a healthy TUI
+// sitting at its composer (2026-09-20: six codex-tui agents each dead in ~24s
+// with an empty "Ask Codex to do anything" box in the transcript). Re-pasting
+// is the destructive half — a single early paste, left alone, lands on its own.
+//
+// So codex's FIRST attempt waits this long for the commit instead of retrying.
+// It costs nothing in the healthy case: the wait exits the instant the paste is
+// confirmed (the `[Pasted Content N chars]` chip, or the prompt text rendering
+// for a paste too small to chip), which on a ready codex is ~200ms. Only
+// attempt 1 is patient: 45s is the WHOLE queued-commit window (4x the measured
+// 11s), so a paste still uncommitted after it is genuinely gone and attempts 2
+// and 3 revert to the short #2192 swallow-recovery ladder — a run with no live
+// TUI at all still fails in ~60s.
+//
+// It does NOT apply while codex is booting MCP servers. There it renders its
+// input box early and SWALLOWS pastes outright (see createMcpBootTracker
+// below), so nothing is queued to wait for and patience would only delay the
+// re-paste cadence that IS the recovery. The spawner reads the boot tracker
+// live for that reason — the banner can latch after the paste went out.
+//
+// The one-shot runner (tuiPromptRunner.js) keeps the flat fallback: it never
+// re-pastes, so it has nothing for patience to protect, and it tracks no
+// verifiable prompt prefix, so a short codex prompt renders no chip there and
+// would simply wait the full window for nothing.
+export const PASTE_COMMIT_PATIENCE_MS = 45000;
+
/**
* Extract a verifiable prefix from a prompt for paste verification. The prefix
* is a unique-enough substring from the prompt's first "content" line (skipping
@@ -135,6 +168,8 @@ export function verifyPasteRendered(strippedBuffer, prefix) {
return collapseWhitespace(strippedBuffer).includes(collapseWhitespace(prefix));
}
+const PASTE_MARKER_PATTERN_GLOBAL = new RegExp(PASTE_MARKER_PATTERN.source, 'gi');
+
/**
* Count paste-commit markers from Claude Code, Codex, OpenCode, or Grok in
* `strippedText`.
@@ -163,8 +198,9 @@ export function verifyPasteRendered(strippedBuffer, prefix) {
*/
export function countPasteMarkers(strippedText) {
if (typeof strippedText !== 'string' || !strippedText) return 0;
- const re = new RegExp(PASTE_MARKER_PATTERN.source, 'gi');
- const m = strippedText.match(re);
+ // `match` with a /g regex ignores and resets lastIndex, so one shared
+ // instance is safe and saves recompiling it on every poll tick.
+ const m = strippedText.match(PASTE_MARKER_PATTERN_GLOBAL);
return m ? m.length : 0;
}
@@ -239,17 +275,41 @@ export function isCollapsedPasteChip(strippedText) {
* possible, so this returns true (nothing to disconfirm).
*
* Callers MUST pass an ANSI-STRIPPED buffer (both signals require it — see
- * countPasteMarkers / verifyPasteRendered).
+ * countPasteMarkers / verifyPasteRendered). Signals 1/1b/2 live in
+ * isPasteCommitted below; this wrapper adds only the "nothing to verify" pass.
*
* @param {string} strippedBuffer — ANSI-stripped post-paste output accumulator.
* @param {{ verifiablePrefix?: string|null, promptMarkerCount?: number }} [opts]
* @returns {boolean}
*/
-export function isPasteConfirmed(strippedBuffer, { verifiablePrefix = null, promptMarkerCount = 0 } = {}) {
- if (countPasteMarkers(strippedBuffer) > promptMarkerCount) return true; // marker is authoritative
- if (isCollapsedPasteChip(strippedBuffer)) return true; // collapsed chip is the TUI's own commit (#2228)
- if (!verifiablePrefix) return true; // nothing to verify against
- return verifyPasteRendered(strippedBuffer, verifiablePrefix);
+export function isPasteConfirmed(strippedBuffer, options = {}) {
+ if (isPasteCommitted(strippedBuffer, options)) return true;
+ return !options.verifiablePrefix; // nothing to verify against
+}
+
+/**
+ * The POSITIVE half of isPasteConfirmed: true only when the buffer carries
+ * actual evidence the TUI committed the paste (its own marker, Claude's
+ * collapsed chip, or the prompt text rendering). Unlike isPasteConfirmed it
+ * does NOT return true just because there is nothing to verify against, so a
+ * caller can use it to WAIT for a commit rather than to decide whether to
+ * declare one swallowed. That distinction is what the patient codex paste
+ * attempt (PASTE_COMMIT_PATIENCE_MS) polls on.
+ *
+ * Callers MUST pass an ANSI-STRIPPED buffer.
+ *
+ * @param {string} strippedBuffer - ANSI-stripped post-paste output accumulator.
+ * @param {{ verifiablePrefix?: string|null, promptMarkerCount?: number }} [opts]
+ * @returns {boolean}
+ */
+export function isPasteCommitted(strippedBuffer, { verifiablePrefix = null, promptMarkerCount = 0 } = {}) {
+ // Counted once and reused for the chip check below — isCollapsedPasteChip
+ // would re-scan the whole buffer, and this runs on the paste poll.
+ const markers = countPasteMarkers(strippedBuffer);
+ if (markers > promptMarkerCount) return true; // marker is authoritative
+ // Collapsed chip is the TUI's own commit (#2228).
+ if (markers >= 1 && COLLAPSED_PASTE_CHIP_PATTERN.test(strippedBuffer)) return true;
+ return !!verifiablePrefix && verifyPasteRendered(strippedBuffer, verifiablePrefix);
}
// Positive "the launched program's input is ready to receive a bracketed paste"
@@ -1051,6 +1111,14 @@ export function createMcpBootTracker() {
// window, plus screen chrome) fit cleanly. Consumers should still treat
// overflow as a fault — see `outputBufferTruncated` tracking in
// `tuiPromptRunner.js`.
+// Cap on the spawner's post-paste accumulator (agentTuiSpawning.js's
+// `postPasteBuffer`), which retains stripped output from a paste attempt until
+// the commit resolves. Both signals it carries are LOCAL — a paste-commit chip
+// and a ~40-char prompt prefix — so a few screens of tail is everything the
+// predicate can use, while a codex booting for the full PASTE_COMMIT_PATIENCE_MS
+// window would otherwise retain every byte of its boot repaint and make each
+// poll scan grow without bound.
+export const POST_PASTE_BUFFER_CAP = 64 * 1024;
export const RAW_BUFFER_CAP = 512 * 1024;
export const RAW_BUFFER_HEADROOM = 640 * 1024;
export const OUTPUT_BUFFER_CAP = 8 * 1024 * 1024;
diff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.js
index 54bdb4fa7e..207bd1c13e 100644
--- a/server/lib/tuiHandshake.test.js
+++ b/server/lib/tuiHandshake.test.js
@@ -21,6 +21,8 @@ import {
SELF_CLEARING_RESUBMIT_INTERVAL_MS,
SELF_CLEARING_RESUBMIT_ECHO_MS,
MCP_BOOT_PASTE_DEADLINE_MS,
+ isPasteCommitted,
+ isPasteConfirmed,
MCP_BOOT_PASTE_RETRY_DELAY_MS,
isMcpBootSignal,
createMcpBootTracker,
@@ -2095,3 +2097,20 @@ describe('createStallNudgeGate', () => {
expect(gate.takeNudge(revivedAt + STALL_NUDGE_IDLE_MS, revivedAt)).toBe(1);
});
});
+
+// isPasteConfirmed answers "may I stop treating this as swallowed?", so an
+// unverifiable prompt passes. isPasteCommitted answers "has the TUI actually
+// taken it?", which must stay FALSE there — otherwise the patient wait would
+// submit immediately on an empty buffer and the patience would be dead code.
+describe('isPasteCommitted', () => {
+ it('requires real evidence where isPasteConfirmed accepts an unverifiable prompt', () => {
+ expect(isPasteConfirmed('', {})).toBe(true);
+ expect(isPasteCommitted('', {})).toBe(false);
+ });
+
+ it('accepts the commit marker and the rendered prompt text alike', () => {
+ expect(isPasteCommitted('[Pasted Content 900 chars]', { verifiablePrefix: 'never rendered' })).toBe(true);
+ expect(isPasteCommitted('> audit the provider list', { verifiablePrefix: 'audit the provider list' })).toBe(true);
+ expect(isPasteCommitted('> Ask Codex to do anything', { verifiablePrefix: 'audit the provider list' })).toBe(false);
+ });
+});
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index b5268002e6..17b483ee5b 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -63,6 +63,8 @@ import {
AGY_INPUT_READY_PATTERN,
PASTE_TO_ENTER_MIN_DELAY_MS,
PASTE_TO_ENTER_FALLBACK_MS,
+ PASTE_COMMIT_PATIENCE_MS,
+ POST_PASTE_BUFFER_CAP,
scheduleSubmitEnters,
PASTE_DEADLINE_MS,
TUI_INPUT_READY_DEADLINE_MS,
@@ -74,6 +76,7 @@ import {
PASTE_RETRY_BASE_DELAY_MS,
extractVerifiablePromptPrefix,
isPasteConfirmed,
+ isPasteCommitted,
SUBMIT_KEY,
detectMissingTuiBinary,
} from '../lib/tuiHandshake.js';
@@ -394,6 +397,7 @@ function createPasteRetryController({
prompt,
tuiConfig,
mcpBoot,
+ isCodexSession,
appendLine,
isFinalized,
markPromptSent,
@@ -414,6 +418,25 @@ function createPasteRetryController({
const verifiablePrefix = extractVerifiablePromptPrefix(prompt);
const pasteConfirmed = (buffer) =>
isPasteConfirmed(buffer, { verifiablePrefix, promptMarkerCount });
+ // Same evidence, minus isPasteConfirmed's "nothing to verify against" pass —
+ // the commit-wait below must keep WAITING while a prompt too short to carry a
+ // verifiable prefix has not visibly landed, not treat it as already committed.
+ //
+ // Memoized on buffer identity because the marker poll re-asks every
+ // PASTE_MARKER_POLL_MS for up to PASTE_COMMIT_PATIENCE_MS — ~300 ticks — while
+ // a booting codex is silent, and the predicate is three full-buffer regex
+ // scans plus two whitespace-stripped copies of it. `postPasteBuffer` is only
+ // ever rebound when output actually arrives, so an idle tick is a pointer
+ // compare.
+ let lastCommitBuffer = null;
+ let lastCommitVerdict = false;
+ const pasteCommitted = (buffer) => {
+ if (buffer !== lastCommitBuffer) {
+ lastCommitBuffer = buffer;
+ lastCommitVerdict = isPasteCommitted(buffer, { verifiablePrefix, promptMarkerCount });
+ }
+ return lastCommitVerdict;
+ };
// Bounded post-paste accumulator. Lives from an attempt through its marker /
// verification windows and any bounded retry backoff, so delayed TUI output
@@ -593,6 +616,14 @@ function createPasteRetryController({
};
const pasteSentAt = Date.now();
+ // How long THIS attempt waits for the TUI to commit the paste before
+ // handing over to the verify/retry budget. Read live rather than captured:
+ // codex's MCP-boot banner can latch after the paste went out, and a
+ // swallowing codex must not spend the patient window — see
+ // PASTE_COMMIT_PATIENCE_MS.
+ const commitWaitMs = () => (isCodexSession && attemptNum <= 1 && !mcpBoot.active
+ ? PASTE_COMMIT_PATIENCE_MS
+ : PASTE_TO_ENTER_FALLBACK_MS);
pasteEnterTimer = setInterval(() => {
if (isFinalized()) {
clearInterval(pasteEnterTimer);
@@ -601,12 +632,13 @@ function createPasteRetryController({
return;
}
const elapsed = Date.now() - pasteSentAt;
- const markerSeen = countPasteMarkers(postPasteBuffer) > promptMarkerCount;
- // Submit when EITHER the paste-commit marker appears (preferred) or
- // the fallback window elapses (covers small prompts that don't render
- // the marker).
- if ((markerSeen && elapsed >= PASTE_TO_ENTER_MIN_DELAY_MS)
- || elapsed >= PASTE_TO_ENTER_FALLBACK_MS) {
+ // Submit when EITHER the TUI's paste commit shows up (preferred) or the
+ // commit-wait window elapses (covers small prompts that don't render the
+ // marker). Waiting on the full commit evidence rather than the marker
+ // alone is what lets codex's patient first attempt (PASTE_COMMIT_PATIENCE_MS)
+ // exit in ~200ms when the composer was live all along.
+ if ((pasteCommitted(postPasteBuffer || '') && elapsed >= PASTE_TO_ENTER_MIN_DELAY_MS)
+ || elapsed >= commitWaitMs()) {
clearInterval(pasteEnterTimer);
pasteEnterTimer = null;
// Capture the buffer before clearing, then confirm the paste (issue #2192).
@@ -615,6 +647,8 @@ function createPasteRetryController({
// Marker present (or text already visible, or nothing to verify) → the
// paste landed; submit now. Trusting the marker here is what fixes the
// multi-line-collapse false negative — Claude hides the pasted body text.
+ // pasteConfirmed is a superset of the pasteCommitted exit above, so only
+ // the commitWaitMs timeout can fall through to the verification window.
if (pasteConfirmed(commitBuffer)) {
submitPaste();
return;
@@ -659,7 +693,9 @@ function createPasteRetryController({
// above). A no-op the rest of the time.
const ingestChunk = (stripped) => {
if (postPasteBuffer === null || !stripped) return;
- postPasteBuffer += stripped;
+ // Tail-bounded: see POST_PASTE_BUFFER_CAP for why a few screens is all the
+ // commit predicates can use.
+ postPasteBuffer = (postPasteBuffer + stripped).slice(-POST_PASTE_BUFFER_CAP);
// The retry backoff used to be a blind spot: output was discarded after
// verification failed and before the next attempt began. A late marker or
// prompt echo still proves the existing paste landed, so submit it now and
@@ -883,7 +919,13 @@ export async function spawnTuiAgent({
// TUI whose startup text happened to contain "starting mcp servers" inherit
// codex's 150s budget and its misleading codex-config guidance, breaking the
// "non-codex TUIs are unchanged" contract (codex review [P2]).
- const isCodexSession = commandName.toLowerCase().includes('codex');
+ //
+ // One verdict for the session, through the shared predicate: it also gates the
+ // patient first paste (PASTE_COMMIT_PATIENCE_MS), and the two codex-only paste
+ // mechanisms must agree on what codex is. It keys on `command` (the harness),
+ // not `spawnCommand` — a credential-bootstrap wrap makes the latter the
+ // bootstrap CLI.
+ const isCodexSession = isCodexCommand(tuiConfig.command);
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
@@ -1836,6 +1878,7 @@ export async function spawnTuiAgent({
prompt,
tuiConfig,
mcpBoot,
+ isCodexSession,
appendLine,
isFinalized: isTerminal,
markPromptSent: () => { promptSentAt = Date.now(); },
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 4913614109..e041c890f9 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -2155,6 +2155,80 @@ describe('spawnTuiAgent runtime', () => {
expect(pasteWrites()).toHaveLength(1);
});
+ // Regression (2026-09-20, agent-d4c7c237 and five siblings): codex QUEUES a
+ // bracketed paste written before its composer finished initializing and
+ // commits it once the composer is live — on a cold Windows start that was
+ // ~11s for a paste sent at 3.7s. The old 3.5s marker wait + 2s verify window
+ // expired first and the retry ladder wrote a SECOND full prompt on top of the
+ // queued one; codex committed NEITHER, and the agent was killed
+ // `paste-not-rendered` in ~24s with a healthy composer on screen. The paste
+ // must be left alone long enough for that late commit, and submitted when it
+ // arrives — never re-pasted over.
+ it('codex late paste commit: waits for the chip past the old window instead of re-pasting', async () => {
+ const pasteFailSpy = vi.fn();
+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async (args) => {
+ if (args?.completionReason === 'paste-not-rendered') pasteFailSpy(args);
+ });
+
+ runSpawn({ prompt: 'review the provider install detection on this machine' });
+ await flushMicrotasks();
+ // Ordinary banner — deliberately NOT an MCP-boot signal, so the extended
+ // boot budget is not what rescues this run.
+ await capturedOnData(Buffer.from('>_ OpenAI Codex (v0.155.1)\n directory: loading\n'));
+ await flushMicrotasks();
+ await vi.advanceTimersByTimeAsync(2000);
+ await flushMicrotasks();
+ expect(pasteCount()).toBe(1);
+
+ // Well past the old 5.5s marker+verify budget, codex is still initializing
+ // and has echoed nothing. Nothing may be re-pasted, and nothing may fail.
+ await vi.advanceTimersByTimeAsync(10000);
+ await flushMicrotasks();
+ expect(pasteCount()).toBe(1);
+ expect(pasteFailSpy).not.toHaveBeenCalled();
+
+ // Composer goes live and commits the queued paste.
+ await capturedOnData(Buffer.from('[Pasted Content 29448 chars]\n'));
+ await flushMicrotasks();
+ await vi.advanceTimersByTimeAsync(400);
+ await flushMicrotasks();
+
+ const enterWrites = vi.mocked(shellService.writeToSession).mock.calls
+ .filter(([id, data]) => id === SESSION_ID && data === '\r');
+ expect(enterWrites.length).toBeGreaterThan(0);
+ expect(pasteCount()).toBe(1);
+ expect(pasteFailSpy).not.toHaveBeenCalled();
+ });
+
+ // The patient window is for a paste codex QUEUED. During an MCP boot codex
+ // renders its box early and SWALLOWS pastes outright, so there is nothing to
+ // wait for and patience would only delay the 5s re-paste cadence that IS the
+ // recovery. The boot banner can latch AFTER the paste went out, so the wait
+ // has to be read live rather than fixed when the attempt started.
+ it('codex MCP boot: drops the patient window when the boot banner latches after the paste', async () => {
+ const { PASTE_COMMIT_PATIENCE_MS } = await vi.importActual('../lib/tuiHandshake.js');
+
+ runSpawn({ prompt: 'evaluate our animation prompts and generate drafts' });
+ await flushMicrotasks();
+ await capturedOnData(Buffer.from('>_ OpenAI Codex (v0.155.1)\n'));
+ await flushMicrotasks();
+ await vi.advanceTimersByTimeAsync(2000);
+ await flushMicrotasks();
+ expect(pasteCount()).toBe(1);
+
+ // Boot banner arrives only now — after the paste. The attempt must abandon
+ // the patient window and fall back to the short swallow-recovery ladder.
+ await capturedOnData(Buffer.from('Starting MCP servers (1/2): codex_apps (0s • esc to interrupt)\n'));
+ await flushMicrotasks();
+
+ // Well inside the patient window, so a captured 45s wait would still be
+ // sitting on attempt 1 with nothing re-pasted.
+ await vi.advanceTimersByTimeAsync(20000);
+ await flushMicrotasks();
+ expect(PASTE_COMMIT_PATIENCE_MS).toBeGreaterThan(20000);
+ expect(pasteCount()).toBeGreaterThan(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
@@ -2166,6 +2240,7 @@ describe('spawnTuiAgent runtime', () => {
// 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 { MCP_BOOT_PASTE_DEADLINE_MS } = await vi.importActual('../lib/tuiHandshake.js');
const pasteFailSpy = vi.fn();
vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async (args) => {
if (args?.completionReason === 'paste-not-rendered') pasteFailSpy(args);
@@ -2187,9 +2262,9 @@ describe('spawnTuiAgent runtime', () => {
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);
+ // well past the point where the fixed 3-attempt budget would be exhausted,
+ // but under the MCP-boot deadline.
+ await vi.advanceTimersByTimeAsync(MCP_BOOT_PASTE_DEADLINE_MS - 5000);
await flushMicrotasks();
// Boot-aware budget kept retrying instead of failing paste-not-rendered…
@@ -2204,6 +2279,7 @@ describe('spawnTuiAgent runtime', () => {
PASTE_TO_ENTER_FALLBACK_MS,
PASTE_VERIFY_WINDOW_MS,
PASTE_VERIFY_POLL_MS,
+ PASTE_MARKER_POLL_MS,
} = await vi.importActual('../lib/tuiHandshake.js');
runSpawn({ prompt: 'evaluate our animation prompts and generate drafts' });
@@ -2215,10 +2291,10 @@ describe('spawnTuiAgent runtime', () => {
expect(pasteCount()).toBe(1);
- // Let the marker and text verification windows expire so the controller is
- // inside its MCP-aware retry backoff. The production incident delivered the
- // paste chip in exactly this gap, after output from a busy Codex repaint was
- // delayed; the old controller discarded it and stacked another full prompt.
+ // Deliver the chip well past the old marker + verification windows. The
+ // production incident delivered it in exactly this gap, after output from a
+ // busy Codex repaint was delayed; the old controller discarded it and
+ // stacked another full prompt on top.
await vi.advanceTimersByTimeAsync(
PASTE_TO_ENTER_FALLBACK_MS + PASTE_VERIFY_WINDOW_MS + PASTE_VERIFY_POLL_MS,
);
@@ -2227,6 +2303,11 @@ describe('spawnTuiAgent runtime', () => {
await capturedOnData(Buffer.from('[Pasted Content 12345 chars]\n'));
await flushMicrotasks();
+ // Codex's patient first attempt is still waiting for that chip, so the
+ // submit fires on the next marker poll.
+ await vi.advanceTimersByTimeAsync(PASTE_MARKER_POLL_MS);
+ await flushMicrotasks();
+
const enterWrites = () => vi.mocked(shellService.writeToSession).mock.calls
.filter(([id, data]) => id === SESSION_ID && data === '\r');
expect(enterWrites()).toHaveLength(1);
@@ -2259,7 +2340,8 @@ describe('spawnTuiAgent runtime', () => {
);
});
- it('paste-not-rendered: without an MCP-boot banner, still fails after the fixed 3 attempts (~19s)', async () => {
+ it('paste-not-rendered: without an MCP-boot banner, still fails after the fixed 3 attempts', async () => {
+ const { PASTE_COMMIT_PATIENCE_MS } = await vi.importActual('../lib/tuiHandshake.js');
let resolveComplete;
const completeDone = new Promise((r) => { resolveComplete = r; });
vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });
@@ -2272,9 +2354,10 @@ describe('spawnTuiAgent runtime', () => {
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);
+ // No marker/echo. Advance past attempt 1's patient commit window plus the
+ // two short retries behind it, but well under the 150s MCP-boot deadline —
+ // proving the non-boot path still fails at 3 attempts.
+ await vi.advanceTimersByTimeAsync(PASTE_COMMIT_PATIENCE_MS + 25000);
vi.useRealTimers();
await completeDone;
diff --git a/server/services/tuiPromptRunner.js b/server/services/tuiPromptRunner.js
index 526a58c2f6..0a23faf7a8 100644
--- a/server/services/tuiPromptRunner.js
+++ b/server/services/tuiPromptRunner.js
@@ -54,6 +54,7 @@ import {
DEFAULT_TUI_PROMPT_DELAY_MS,
PASTE_MARKER_POLL_MS,
countPasteMarkers,
+ isPasteCommitted,
PASTE_TO_ENTER_MIN_DELAY_MS,
PASTE_TO_ENTER_FALLBACK_MS,
scheduleSubmitEnters,
@@ -824,7 +825,10 @@ ${prompt}`;
pasteEnterTimer = setInterval(() => {
if (finalized) { clearInterval(pasteEnterTimer); pasteEnterTimer = null; postPasteStripped = null; return; }
const elapsed = Date.now() - pasteSentAt;
- const markerSeen = countPasteMarkers(postPasteStripped) > promptMarkerCount;
+ // Shared with the agent spawner's poll so the two can't drift on what
+ // counts as a commit — without a verifiable prefix this is the marker
+ // count plus Claude's/OpenCode's collapsed-chip shape.
+ const markerSeen = isPasteCommitted(postPasteStripped || '', { promptMarkerCount });
if ((markerSeen && elapsed >= PASTE_TO_ENTER_MIN_DELAY_MS)
|| elapsed >= PASTE_TO_ENTER_FALLBACK_MS) {
clearInterval(pasteEnterTimer);