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([issue-1229]): match paste marker on stripped output + gate idle-complete on real work

[._.]/ Adam Eivy13aef117fe48
diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.js
index c38d6a3f27..1440c2cbb6 100644
--- a/server/lib/tuiHandshake.js
+++ b/server/lib/tuiHandshake.js
@@ -27,19 +27,75 @@ export const PASTE_DEADLINE_MS = 10000;
// Claude Code emits `[Pasted text #N +M lines]` after committing a paste.
// Watch for the marker (or fall back after PASTE_TO_ENTER_FALLBACK_MS)
// before sending `\r` so Enter doesn't get swallowed mid-paste-commit.
+//
+// CRITICAL: the marker must be matched against ANSI-STRIPPED output, never the
+// raw PTY stream. Claude Code renders the marker by positioning each token with
+// absolute-column cursor moves instead of literal spaces — the raw bytes look
+// like `[Pasted\x1b[11Gtext\x1b[16G#1\x1b[19G+35\x1b[23Glines]`, so the literal
+// substring "Pasted text #1" never exists contiguously and a space-requiring
+// regex never matches. Once ANSI is stripped the cursor moves vanish and the
+// glyphs collapse adjacent → `[Pastedtext#1+35lines]`. So the pattern tolerates
+// arbitrary (including zero) whitespace between tokens and is case-insensitive,
+// and `detectPasteMarker()` below is the only sanctioned way to test it. This
+// was the root cause of issue #1229: across a month of real transcripts the
+// marker "never appeared" only because the matcher ran against the raw stream;
+// the fast path was effectively dead and every run fell back to the blind timer.
export const PASTE_MARKER_POLL_MS = 150;
-export const PASTE_MARKER_PATTERN = /\[Pasted text #\d+/;
+export const PASTE_MARKER_PATTERN = /\[Pasted\s*text\s*#\d+/i;
export const PASTE_TO_ENTER_MIN_DELAY_MS = 200;
export const PASTE_TO_ENTER_FALLBACK_MS = 3500;
+/**
+ * True when `strippedText` contains Claude Code's `[Pasted text #N …]` paste-
+ * commit marker. Callers MUST pass ANSI-STRIPPED output (see PASTE_MARKER_PATTERN
+ * above for why the raw stream never matches). Shared by both TUI consumers so
+ * the strip-then-match contract can't drift between them.
+ *
+ * @param {string} strippedText — ANSI-stripped post-paste output accumulator.
+ * @returns {boolean}
+ */
+export function detectPasteMarker(strippedText) {
+ return typeof strippedText === 'string' && PASTE_MARKER_PATTERN.test(strippedText);
+}
+
+// "The model is actively processing a submitted prompt" signal. A TUI repaints
+// its banner/status line continuously even with an UNSUBMITTED prompt sitting in
+// the input box, so "any PTY output after the paste" cannot distinguish real
+// work from chrome churn — that conflation is what finalized a never-submitted
+// agent as `success: idle-complete` (issue #1229). These patterns fire only once
+// a request is in flight and never appear on the idle/stuck input screen:
+// - an elapsed-time working counter — `(1s · …` (Claude Code) / `(57s • …`
+// (Codex). The most model-agnostic signal; present in both, absent when stuck.
+// - `esc to interrupt` — the live-request interrupt hint (Codex; some Claude).
+// - `thinking` — Claude Code's working spinner caption.
+// Verified against real transcripts: working runs hit these thousands of times;
+// the two confirmed stuck runs (`agent-92ed2c56`, `agent-30a3ab56`) hit them
+// zero times. Heuristic by nature (spinner captions rotate across versions), so
+// it gates only the FALLBACK idle-complete path — the authoritative success
+// signal remains the `.agent-done` sentinel.
+export const WORK_ACTIVITY_PATTERN = /\(\s*\d+s\b|esc to interrupt|\bthinking\b/i;
+
+/**
+ * True when `strippedText` shows the model is actively working on a submitted
+ * prompt (see WORK_ACTIVITY_PATTERN). Callers MUST pass ANSI-stripped output.
+ *
+ * @param {string} strippedText — ANSI-stripped output (a chunk or accumulator).
+ * @returns {boolean}
+ */
+export function detectWorkActivity(strippedText) {
+ return typeof strippedText === 'string' && WORK_ACTIVITY_PATTERN.test(strippedText);
+}
+
// A SINGLE Enter after a large bracketed paste is unreliable: the TUI can still
// be processing/reflowing the multi-line paste when the `\r` arrives and
// swallow it, leaving the whole prompt sitting unsent in the input box. The
// agent then idles out and is falsely finalized as success — observed as the
-// "the prompt was typed but I had to hit Enter myself" bug. (Modern Claude Code
-// also no longer reliably emits the `[Pasted text #N]` marker, so the fast path
-// above rarely fires and we lean entirely on the fallback Enter.) Send a few
-// Enters spaced apart so at least one lands after the paste settles. Re-sending
+// "the prompt was typed but I had to hit Enter myself" bug. (The marker fast
+// path above now fires again once matched against stripped output — see
+// detectPasteMarker — but the marker only renders for large multi-line pastes;
+// short prompts still lean on the fallback timer, so multi-Enter remains the
+// safety net for both.) Send a few Enters spaced apart so at least one lands
+// after the paste settles. Re-sending
// is safe: once the prompt submits the input box is empty and a bare Enter is a
// no-op in every TUI we drive (claude/codex/gemini), so the extra Enters can't
// fire a spurious empty message.
diff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.js
index fa8c96944e..e82d32f651 100644
--- a/server/lib/tuiHandshake.test.js
+++ b/server/lib/tuiHandshake.test.js
@@ -5,6 +5,9 @@ import {
PASTE_DEADLINE_MS,
PASTE_MARKER_POLL_MS,
PASTE_MARKER_PATTERN,
+ detectPasteMarker,
+ WORK_ACTIVITY_PATTERN,
+ detectWorkActivity,
PASTE_TO_ENTER_MIN_DELAY_MS,
PASTE_TO_ENTER_FALLBACK_MS,
SUBMIT_ENTER_ATTEMPTS,
@@ -57,6 +60,29 @@ describe('tuiHandshake — paste timing constants', () => {
expect(PASTE_MARKER_PATTERN.test('banner stuff [Pasted text #7 +1 lines] trailer')).toBe(true);
});
+ it('PASTE_MARKER_PATTERN matches the SPACE-COLLAPSED form left after ANSI strip', () => {
+ // The raw PTY stream renders the marker with absolute-column cursor moves
+ // between tokens (`[Pasted\x1b[11Gtext\x1b[16G#1…`), so once ANSI is stripped
+ // the spaces vanish and glyphs collapse adjacent. This is the exact shape
+ // observed in real transcripts and the root cause of #1229 — a space-
+ // requiring regex never matched it. (See the integration assertion below
+ // that strips the real escape sequence and matches the result.)
+ expect(PASTE_MARKER_PATTERN.test('[Pastedtext#1+35lines]')).toBe(true);
+ expect(PASTE_MARKER_PATTERN.test('[Pastedtext#42+120lines]')).toBe(true);
+ });
+
+ it('PASTE_MARKER_PATTERN matches the real cursor-positioned marker once ANSI-stripped', () => {
+ // Verbatim byte shape from data/cos/agents/.../raw.txt, stripped the same
+ // way the streaming ANSI stripper does (drop CSI sequences).
+ const rawMarker = '[Pasted\x1b[11Gtext\x1b[16G#1\x1b[19G+35\x1b[23Glines]';
+ const stripped = rawMarker.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '');
+ expect(stripped).toBe('[Pastedtext#1+35lines]');
+ // The raw form must NOT match (regression guard: this is why the fast path
+ // was dead) but the stripped form MUST.
+ expect(detectPasteMarker(rawMarker)).toBe(false);
+ expect(detectPasteMarker(stripped)).toBe(true);
+ });
+
it('PASTE_MARKER_PATTERN does NOT match similar-looking but distinct text', () => {
expect(PASTE_MARKER_PATTERN.test('[Pasted text]')).toBe(false);
expect(PASTE_MARKER_PATTERN.test('[Pasted #1]')).toBe(false);
@@ -64,6 +90,40 @@ describe('tuiHandshake — paste timing constants', () => {
expect(PASTE_MARKER_PATTERN.test('')).toBe(false);
});
+ it('detectPasteMarker guards non-string input', () => {
+ expect(detectPasteMarker(null)).toBe(false);
+ expect(detectPasteMarker(undefined)).toBe(false);
+ expect(detectPasteMarker(123)).toBe(false);
+ expect(detectPasteMarker('[Pasted text #1 +3 lines]')).toBe(true);
+ });
+
+ it('detectWorkActivity recognizes a model actively processing a submitted prompt', () => {
+ // Elapsed working counter — model-agnostic (Claude Code + Codex).
+ expect(detectWorkActivity('(1s · thinking with high effort)')).toBe(true);
+ expect(detectWorkActivity('(57s • esc to interrupt)')).toBe(true);
+ expect(detectWorkActivity('(0s · Churning…)')).toBe(true);
+ // Codex live-request interrupt hint.
+ expect(detectWorkActivity('Working (12s · esc to interrupt)')).toBe(true);
+ // Claude Code working caption.
+ expect(detectWorkActivity('✻ thinking with high effort')).toBe(true);
+ });
+
+ it('detectWorkActivity returns false for the stuck/idle input screen (no work signal)', () => {
+ // The chrome present on a never-submitted-prompt screen (from the #1229
+ // false-success transcript): footer + echoed prompt + effort indicator.
+ expect(detectWorkActivity('⏵⏵ bypass permissions on (shift+tab to cycle)')).toBe(false);
+ expect(detectWorkActivity('● high · /effort')).toBe(false);
+ expect(detectWorkActivity('paste again to expand')).toBe(false);
+ expect(detectWorkActivity('Begin working on the task now.')).toBe(false);
+ expect(detectWorkActivity('Opus 4.8 │ agent-92ed2c56')).toBe(false);
+ expect(detectWorkActivity('')).toBe(false);
+ expect(detectWorkActivity(null)).toBe(false);
+ });
+
+ it('WORK_ACTIVITY_PATTERN is exported as a RegExp for caller reuse', () => {
+ expect(WORK_ACTIVITY_PATTERN).toBeInstanceOf(RegExp);
+ });
+
it('pins provider-default constants', () => {
expect(DEFAULT_TUI_PROMPT_DELAY_MS).toBe(2500);
expect(DEFAULT_TUI_IDLE_TIMEOUT_MS).toBe(180000);
diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.js
index c03abe7942..ad7c3ff22b 100644
--- a/server/lib/tuiPromptRunner.js
+++ b/server/lib/tuiPromptRunner.js
@@ -43,7 +43,7 @@ import { registerExternalSession, unregisterExternalSession, isExternalSessionAt
import {
DEFAULT_TUI_PROMPT_DELAY_MS,
PASTE_MARKER_POLL_MS,
- PASTE_MARKER_PATTERN,
+ detectPasteMarker,
PASTE_TO_ENTER_MIN_DELAY_MS,
PASTE_TO_ENTER_FALLBACK_MS,
scheduleSubmitEnters,
@@ -202,6 +202,12 @@ ${prompt}`;
let outputBuffer = '';
let rawBuffer = '';
let promptSentAt = null;
+ // ANSI-stripped post-paste accumulator for paste-marker detection. The marker
+ // renders with absolute-column cursor moves between glyphs, so it only matches
+ // after stripping — testing the raw stream never matched and left the fast
+ // path dead (issue #1229). Lives only during the paste→Enter window; nulled
+ // when detection resolves or the run finalizes.
+ let postPasteStripped = null;
let firstOutputAt = null;
let lastOutputAt = startTime;
let firstResponseAt = null;
@@ -240,6 +246,9 @@ ${prompt}`;
let hardTimeoutTimer = null;
const cleanupTimers = () => {
+ // Stop the post-paste accumulator from growing on any chunk that lands
+ // between finalize and the PTY kill (onData here has no finalized guard).
+ postPasteStripped = null;
if (readyTimer) { clearInterval(readyTimer); readyTimer = null; }
if (pasteEnterTimer) { clearInterval(pasteEnterTimer); pasteEnterTimer = null; }
if (submitEnterTimer) { clearInterval(submitEnterTimer); submitEnterTimer = null; }
@@ -298,6 +307,7 @@ ${prompt}`;
const stripped = streamingStrip(text);
if (stripped) {
+ if (postPasteStripped !== null) postPasteStripped += stripped;
outputBuffer += stripped;
if (outputBuffer.length > OUTPUT_BUFFER_HEADROOM) {
outputBuffer = outputBuffer.slice(-OUTPUT_BUFFER_CAP);
@@ -389,7 +399,9 @@ ${prompt}`;
const sendPrompt = (reason) => {
if (finalized || promptSentAt) return;
promptSentAt = Date.now();
- const rawLenBeforePaste = rawBuffer.length;
+ // Start capturing stripped post-paste output BEFORE the paste write so the
+ // marker watcher sees every response chunk.
+ postPasteStripped = '';
try {
ptyProcess.write(`\x1b[200~${wrappedPrompt}\x1b[201~`);
} catch (err) {
@@ -415,14 +427,14 @@ ${prompt}`;
const pasteSentAt = Date.now();
pasteEnterTimer = setInterval(() => {
- if (finalized) { clearInterval(pasteEnterTimer); pasteEnterTimer = null; return; }
+ if (finalized) { clearInterval(pasteEnterTimer); pasteEnterTimer = null; postPasteStripped = null; return; }
const elapsed = Date.now() - pasteSentAt;
- const postPaste = rawBuffer.slice(rawLenBeforePaste);
- const markerSeen = PASTE_MARKER_PATTERN.test(postPaste);
+ const markerSeen = detectPasteMarker(postPasteStripped);
if ((markerSeen && elapsed >= PASTE_TO_ENTER_MIN_DELAY_MS)
|| elapsed >= PASTE_TO_ENTER_FALLBACK_MS) {
clearInterval(pasteEnterTimer);
pasteEnterTimer = null;
+ postPasteStripped = null;
// Submit with repeated Enters — a single `\r` can be swallowed while
// the TUI is still reflowing a large paste, stranding the prompt
// unsent. Tracked in submitEnterTimer so finish()'s cleanupTimers()
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 635ecb0c35..e96ef343e6 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -27,7 +27,8 @@ import {
READY_POLL_INTERVAL_MS,
READY_IDLE_THRESHOLD_MS,
PASTE_MARKER_POLL_MS,
- PASTE_MARKER_PATTERN,
+ detectPasteMarker,
+ detectWorkActivity,
PASTE_TO_ENTER_MIN_DELAY_MS,
PASTE_TO_ENTER_FALLBACK_MS,
scheduleSubmitEnters,
@@ -206,6 +207,13 @@ export async function spawnTuiAgent({
let sentinelIngested = false;
let hasStartedWorking = false;
let promptSentAt = null;
+ // True once we've seen evidence the model is actively processing the SUBMITTED
+ // prompt (working counter / interrupt hint / "thinking" — see detectWorkActivity).
+ // Distinct from `hasStartedWorking`, which flips on ANY post-spawn PTY output
+ // including pure banner/status-line chrome. This flag is what gates the
+ // fallback idle-complete path from finalizing a never-submitted prompt as
+ // success (issue #1229).
+ let sawWorkActivity = false;
let firstOutputAt = null;
let lastOutputAt = Date.now();
let lastLine = '';
@@ -522,7 +530,19 @@ export async function spawnTuiAgent({
const stripped = streamingStrip(text);
pendingRawChunks.push(text);
scheduleRawFlush();
- if (postPasteBuffer !== null) postPasteBuffer += text;
+ // Accumulate the ANSI-STRIPPED chunk (not the raw text): the paste marker
+ // is rendered with absolute-column cursor moves between glyphs, so it only
+ // matches after stripping (see detectPasteMarker). Appending raw text here
+ // — as this did before #1229 — left the marker unmatchable and the fast
+ // path dead.
+ if (postPasteBuffer !== null && stripped) postPasteBuffer += stripped;
+ // Once the prompt is submitted, watch for proof the model is actually
+ // working. The TUI repaints chrome continuously even with an unsent prompt,
+ // so we can't trust mere PTY activity — only a working indicator confirms
+ // the prompt left the input box. Gates idle-complete (issue #1229).
+ if (promptSentAt && !sawWorkActivity && stripped && detectWorkActivity(stripped)) {
+ sawWorkActivity = true;
+ }
lastOutputAt = Date.now();
if (firstOutputAt === null) firstOutputAt = lastOutputAt;
@@ -651,9 +671,7 @@ export async function spawnTuiAgent({
return;
}
const elapsed = Date.now() - pasteSentAt;
- const markerSeen = postPasteBuffer
- ? PASTE_MARKER_PATTERN.test(postPasteBuffer)
- : false;
+ const markerSeen = detectPasteMarker(postPasteBuffer);
// Submit when EITHER the paste-commit marker appears (preferred) or
// the fallback window elapses (covers small prompts that don't render
// the marker).
@@ -696,9 +714,27 @@ export async function spawnTuiAgent({
// agents — see handleData.
if (lastOutputAt <= promptSentAt) return;
if (idle >= tuiConfig.idleTimeoutMs) {
- finish({ success: true, exitCode: 0, reason: 'idle-complete' }).catch(err => {
- emitLog('error', `Failed to finalize TUI agent ${agentId}: ${err.message}`, { agentId });
- });
+ // Distinguish a real (sentinel-less) completion from a never-submitted
+ // prompt that just idled out. `lastOutputAt > promptSentAt` only proves
+ // the TUI repainted SOMETHING — banner/status chrome churns even with the
+ // prompt sitting unsent. Only finalize as success when we actually saw the
+ // model working (sawWorkActivity); otherwise this is the #1229 failure mode
+ // (prompt never submitted, zero work done) and must be recorded as a
+ // FAILURE so the orchestrator doesn't treat a no-op run as done.
+ if (sawWorkActivity) {
+ finish({ success: true, exitCode: 0, reason: 'idle-complete' }).catch(err => {
+ emitLog('error', `Failed to finalize TUI agent ${agentId}: ${err.message}`, { agentId });
+ });
+ } else {
+ finish({
+ success: false,
+ exitCode: 1,
+ error: 'TUI agent idled out with no sign of work — the prompt likely never submitted (no working indicator ever appeared after paste).',
+ reason: 'idle-no-activity',
+ }).catch(err => {
+ emitLog('error', `Failed to finalize TUI agent ${agentId}: ${err.message}`, { agentId });
+ });
+ }
}
}, 5000);
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 1d013f00e6..e34c532b5d 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -348,10 +348,12 @@ describe('spawnTuiAgent runtime', () => {
await vi.advanceTimersByTimeAsync(2000);
await flushMicrotasks();
- // Feed one PTY chunk AFTER the paste so lastOutputAt > promptSentAt
- // (the idle gate's "we saw activity post-paste" signal — replaces the
- // old per-line count now that line capture is dropped).
- await capturedOnData(Buffer.from('Agent post-paste activity\n'));
+ // Feed a PTY chunk AFTER the paste that proves the model is actually
+ // WORKING — an elapsed working counter (`(1s · …`). This both sets
+ // lastOutputAt > promptSentAt AND trips sawWorkActivity, which the idle
+ // gate now requires before finalizing as success (issue #1229 — pure
+ // chrome churn must NOT count as completion; see the no-activity test below).
+ await capturedOnData(Buffer.from('(1s · thinking with high effort)\n'));
// Advance past DEFAULT_TUI_MIN_RUNTIME_MS (15 000ms) + idleTimeoutMs (50ms).
// The idle setInterval ticks every 5 000ms; at the >=15s tick the
@@ -374,6 +376,45 @@ describe('spawnTuiAgent runtime', () => {
);
});
+ // ── 1a. Idle-out with NO work activity → failure (issue #1229) ───────────────
+ // The bug: when the prompt never submits, the TUI keeps repainting its banner /
+ // status line, so `lastOutputAt > promptSentAt` passes on pure chrome churn and
+ // the agent — which did ZERO work — was finalized as `success: idle-complete`.
+ // The fix gates idle-complete success on having seen a real work-activity
+ // signal (working counter / interrupt hint / "thinking"). With only chrome
+ // post-paste, idle must finalize as FAILURE with reason 'idle-no-activity'.
+ it('idle-no-activity: finalizes failure when idle fires but no work signal ever appeared (unsubmitted prompt)', async () => {
+ let resolveComplete;
+ const completeDone = new Promise((r) => { resolveComplete = r; });
+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });
+
+ runSpawn();
+ await flushMicrotasks();
+
+ await capturedOnData(Buffer.from('Codex booting...\n'));
+ await flushMicrotasks();
+ await vi.advanceTimersByTimeAsync(2000);
+ await flushMicrotasks();
+
+ // Post-paste output, but ONLY chrome that repaints with an unsent prompt —
+ // the input footer + effort indicator from the real #1229 stuck transcript.
+ // None of this is a work-activity signal, so sawWorkActivity stays false.
+ await capturedOnData(Buffer.from('⏵⏵ bypass permissions on (shift+tab to cycle)\n'));
+ await capturedOnData(Buffer.from('● high · /effort\n'));
+
+ await vi.advanceTimersByTimeAsync(21000);
+ vi.useRealTimers();
+ await completeDone;
+
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ success: false,
+ completionReason: 'idle-no-activity',
+ })
+ );
+ });
+
// ── 1b. Submit-Enter retries ─────────────────────────────────────────────────
// A single `\r` after a large bracketed paste can be swallowed mid-paste-
// commit, stranding the prompt unsent (the "I had to hit Enter myself" bug,
@@ -661,12 +702,14 @@ describe('spawnTuiAgent runtime', () => {
runSpawn();
await flushMicrotasks();
- // Drive the idle-complete success path (mirrors test 1).
+ // Drive the idle-complete success path (mirrors test 1) — the post-paste
+ // chunk must carry a work-activity signal so the idle gate finalizes as
+ // success (issue #1229).
await capturedOnData(Buffer.from('Codex booting...\n'));
await flushMicrotasks();
await vi.advanceTimersByTimeAsync(2000);
await flushMicrotasks();
- await capturedOnData(Buffer.from('Agent post-paste activity\n'));
+ await capturedOnData(Buffer.from('(1s · thinking with high effort)\n'));
await vi.advanceTimersByTimeAsync(21000);
vi.useRealTimers();
await completeDone;