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: trust the paste-commit marker so Claude Code TUI agents stop failing paste-not-rendered

Adam Eivy6df87fe6b44a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 82d45f9837..59bca853f0 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## CoS Agents
+- **Claude Code TUI agents no longer fail `paste-not-rendered` on every multi-line prompt.** The #2192 paste-verification guard confirmed a paste had landed by looking for the prompt's literal text in the TUI buffer — but Claude Code collapses a multi-line bracketed paste into a `[Pasted text #N]` chip and *hides* the pasted body text, and it reflows single lines with cursor-positioning escapes instead of literal space bytes between words. Both made the text check false-negative, so every `claude-code-tui` CoS agent retried 3× and died with `paste-not-rendered` despite the paste landing perfectly (100% reproduction across real runs, 2026-07-05). The gate now treats the TUI's own paste-commit **marker** as authoritative proof of delivery (checked first, via a new `isPasteConfirmed` helper), and only falls back to text matching for the markerless path — where the match is now whitespace-insensitive so a space-less reflowed line still matches. Captured transcripts from the real incident are pinned as regression tests. (`server/lib/tuiHandshake.js`, `server/services/agentTuiSpawning.js`)
- **A live agent TUI no longer gets reaped mid-paste.** The idle-timeout reaper only tracked `lastOutputAt` (PTY output), not client input, so pasting a large multi-line command into a running agent's session could sit in a silent reflow/commit window with no echo yet — indistinguishable from "idle" to the 5s poll. If the session happened to already be near its idle threshold, the reaper killed the PTY mid-paste, showing "[Session removed externally]" in the Shell page. The idle timer in `agentTuiSpawning.js` now also checks a new `shell.js` export, `getLastInputAt()`, and skips the reap while input arrived within the last 15s. This is deliberately keyed on input *recency*, not "is a Shell viewer attached": a regular (non-external) session's socket stays bound after its viewer navigates away — only external one-shot `tuiPromptRunner.js` runs get released via `shell:release-views` — so an attachment-based guard would have permanently suppressed idle-complete for any agent glanced at once in the Shell UI. (`server/services/shell.js`, `server/services/agentTuiSpawning.js`)
- **Swarm claim-issue runs now write the completion sentinel so the task actually finishes.** In `/do:next --swarm` mode the orchestrator ships every issue via a PR and never touches the working tree, so it was skipping the `.agent-done` completion sentinel — leaving the CoS task hanging with no summary as if the run never ended. Phase C of the swarm directive now explicitly instructs the orchestrator to write the sentinel (with a run summary of the issues claimed, their PRs, and merge outcomes) after the serialized merges, while still skipping the per-agent `/simplify`/push steps. (`server/services/cosTaskGenerator.js`)
- **[issue-2190] OpenCode Ollama providers now accept any --model flag.** The static `OPENCODE_CONFIG_CONTENT` lacked a models map, so OpenCode rejected every model with "not valid" and the agent sat idle. The config is now built dynamically at spawn time, declaring the provider's configured models (plus the model being run) under `provider.ollama.models` with bare ids — the exact shape OpenCode's `@ai-sdk/openai-compatible` provider validates `--model ollama/<id>` against. Applied across every OpenCode spawn path (CoS CLI/TUI agents, the toolkit CLI/TUI runners, and the light fire-and-collect CLI run), and a migration backfills existing installs' `data/providers.json` so a configured model's map is persisted too. Fixes the TUI eval path for local Ollama models.
diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.js
index 3c1c62accb..b5fe21ecbf 100644
--- a/server/lib/tuiHandshake.js
+++ b/server/lib/tuiHandshake.js
@@ -88,20 +88,35 @@ export function extractVerifiablePromptPrefix(prompt) {
}
/**
- * True when the verifiable prompt prefix appears in the post-paste buffer. Both
- * arguments must be whitespace-normalized (single spaces) and ANSI-stripped.
+ * True when the verifiable prompt prefix appears in the post-paste buffer.
+ * ANSI-stripped input; internal whitespace differences are ignored (see below).
* A null/empty prefix always returns true (no verification possible).
*
- * @param {string} strippedBuffer — ANSI-stripped, whitespace-normalized post-paste output.
+ * Whitespace is stripped ENTIRELY (not just collapsed to a single space) before
+ * comparing, on both sides. Claude Code (and potentially other TUIs) can
+ * redraw/reflow a pasted multi-word line using cursor-positioning escapes
+ * instead of literal space bytes between words — the same "inter-glyph cursor
+ * moves" quirk already documented above (BRACKETED_PASTE_MODE_PATTERN) as the
+ * reason createInputReadyTracker avoids literal footer-text matching. ANSI
+ * stripping drops those inter-word spaces entirely, so a genuinely-rendered
+ * paste can still fail a single-space-normalized substring match (real
+ * incident: every claude-code-tui CoS agent failed immediately with
+ * "paste-not-rendered" after 3 retries — see tuiHandshake.test.js's "real
+ * incident" regression test for the captured transcript). Comparing with all
+ * whitespace removed makes the match robust to however a given TUI reflows a
+ * line, at the cost of a (very low, given the ~40-char prefix) chance of a
+ * spurious match spanning a word boundary that only lines up once spaces are
+ * gone.
+ *
+ * @param {string} strippedBuffer — ANSI-stripped post-paste output.
* @param {string|null} prefix — the prefix from extractVerifiablePromptPrefix.
* @returns {boolean}
*/
export function verifyPasteRendered(strippedBuffer, prefix) {
if (!prefix) return true; // no verification possible
if (typeof strippedBuffer !== 'string') return false;
- // Normalize both to collapse any remaining whitespace differences
- const normalizedBuffer = strippedBuffer.replace(/\s+/g, ' ');
- return normalizedBuffer.includes(prefix);
+ const collapseWhitespace = (s) => s.replace(/\s+/g, '');
+ return collapseWhitespace(strippedBuffer).includes(collapseWhitespace(prefix));
}
/**
@@ -144,6 +159,39 @@ export function detectPasteMarker(strippedText) {
return countPasteMarkers(strippedText) > 0;
}
+/**
+ * True when a post-paste buffer proves the TUI actually RECEIVED the prompt
+ * paste — the gate before sending the submit Enter(s). Two independent signals,
+ * checked in priority order:
+ *
+ * 1. The TUI's own paste-commit MARKER (`[Pasted text #N]`) count exceeds the
+ * count the prompt itself carried (promptMarkerCount). This is AUTHORITATIVE
+ * and is checked FIRST because Claude Code collapses a multi-line bracketed
+ * paste INTO that chip and HIDES the pasted body text from the buffer — so on
+ * every multi-line prompt the literal text is genuinely absent even though
+ * the paste landed perfectly. Real incident (2026-07-05): every
+ * claude-code-tui CoS agent failed `paste-not-rendered` after 3 retries
+ * because #2192's text-only check never saw the collapsed body — while the
+ * marker was sitting right there. (agent-656efa6e et al.)
+ * 2. Fallback for the MARKERLESS path — a paste too small to render the marker,
+ * or one genuinely SWALLOWED by a still-initializing TUI (the #2192 case,
+ * which renders no marker at all): fall back to confirming the prompt text
+ * literally rendered. A null/empty verifiablePrefix means no verification is
+ * possible, so this returns true (nothing to disconfirm).
+ *
+ * Callers MUST pass an ANSI-STRIPPED buffer (both signals require it — see
+ * countPasteMarkers / verifyPasteRendered).
+ *
+ * @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 (!verifiablePrefix) return true; // nothing to verify against
+ return verifyPasteRendered(strippedBuffer, verifiablePrefix);
+}
+
// Positive "the launched program's input is ready to receive a bracketed paste"
// signal, derived from the terminal's bracketed-paste-mode toggles in the RAW
// (un-stripped) PTY stream. A program enables bracketed-paste mode (`ESC[?2004h`)
diff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.js
index 24d58cc4dd..1118e09ffa 100644
--- a/server/lib/tuiHandshake.test.js
+++ b/server/lib/tuiHandshake.test.js
@@ -40,6 +40,7 @@ import {
PASTE_RETRY_BASE_DELAY_MS,
extractVerifiablePromptPrefix,
verifyPasteRendered,
+ isPasteConfirmed,
} from './tuiHandshake.js';
import { CODEX_CONFIGURED_DEFAULT } from './providerModels.js';
@@ -698,4 +699,71 @@ describe('tuiHandshake.verifyPasteRendered', () => {
// Also verify partial echo (just the middle portion where the prefix is from)
expect(verifyPasteRendered(`Ask anything... o:next --issues --swarm using the trunca...`, prefix)).toBe(true);
});
+
+ // Every claude-code-tui CoS agent started failing immediately after #2192
+ // shipped, all with identical "paste-not-rendered" after 3 retries — 100%
+ // reproduction across real agent runs (agent-65e4d17f, agent-1f0bda99,
+ // agent-ec5a000c, agent-7dda893e, agent-9916b7be, agent-f5c8ca2a,
+ // agent-d0fa3cdc, 2026-07-05). Root cause: Claude Code redraws/reflows a
+ // pasted multi-word line using cursor-positioning escapes instead of literal
+ // space bytes between words — the exact "inter-glyph cursor moves" quirk
+ // already documented above (BRACKETED_PASTE_MODE_PATTERN comment) as the
+ // reason createInputReadyTracker deliberately avoids literal footer-text
+ // matching. #2192's verifyPasteRendered was never carved out for Claude (the
+ // changelog claimed "Claude TUIs ... are unaffected" but sendPrompt/
+ // attemptPaste is shared across all providers), so it inherited the same
+ // trap: normalizing to a SINGLE space still requires a space to exist, and a
+ // reflowed line has none. Captured verbatim (post-production-ansiStrip) from
+ // agent-147ad88f's raw.txt.
+ it('finds a pasted prompt whose words got glued together by Claude Code reflow (real incident)', () => {
+ const prompt = 'On the tasks page when we render pending/active/blocked task cards, I want to truncate the prompt and only show the first couple of lines with an expand button\n\nBegin working on the task now.';
+ const prefix = extractVerifiablePromptPrefix(prompt);
+ const renderedBuffer = '⏵⏵ bypass permissions on (shift+tab to cycle) · ← for agents Opus 4.8 (1M context) │ agent-147ad88f [Pastedtext#1+3lines] paste again to expand ctrl+g to edit in Vim ──────── ❯ Onthetaskspagewhenwerenderpending/active/blockedtaskcards,Iwant totruncatethepromptandonlyshowthefirstcoupleoflineswithan expandbutton Begin working on the task now.';
+ expect(verifyPasteRendered(renderedBuffer, prefix)).toBe(true);
+ });
+});
+
+describe('tuiHandshake.isPasteConfirmed', () => {
+ const PROMPT = 'On the tasks page when we render pending/active/blocked task cards, I want to truncate the prompt and only show the first couple of lines with an expand button\n\nBegin working on the task now.';
+ const prefix = extractVerifiablePromptPrefix(PROMPT);
+
+ // THE core regression: Claude Code collapses a multi-line paste into a
+ // `[Pasted text #1 +3 lines]` chip and HIDES the body text. Verbatim
+ // (ANSI-stripped) from agent-656efa6e's failed run, 2026-07-05 — the body text
+ // ("On the tasks page…") is genuinely absent, only the marker + the trailing
+ // "Begin working…" line survive. The old text-only gate false-failed here and
+ // killed every claude-code-tui CoS agent after 3 retries. The marker is
+ // authoritative proof the paste landed, so this MUST confirm.
+ it('confirms a multi-line paste that Claude collapsed to a chip (body text hidden) — real incident', () => {
+ const collapsedBuffer = 'Opus 4.8 │ agent-656efa6e [Pastedtext#1+3lines] paste again to expand ──────── ❯ [Pastedtext#1+3lines] ──────── Begin working on the task now. ⏵⏵ bypass permissions on (shift+tab to cycle)';
+ // The body prefix really is NOT in the buffer — verifyPasteRendered alone fails…
+ expect(verifyPasteRendered(collapsedBuffer, prefix)).toBe(false);
+ // …but the marker proves delivery, so isPasteConfirmed confirms it.
+ expect(isPasteConfirmed(collapsedBuffer, { verifiablePrefix: prefix, promptMarkerCount: 0 })).toBe(true);
+ });
+
+ it('confirms when the prompt text DID render inline (markerless small paste)', () => {
+ const inlineBuffer = '❯ Onthetaskspagewhenwerenderpending/active/blockedtaskcards Begin working on the task now.';
+ expect(isPasteConfirmed(inlineBuffer, { verifiablePrefix: prefix, promptMarkerCount: 0 })).toBe(true);
+ });
+
+ it('does NOT confirm when neither the marker nor the text appears (paste swallowed by a not-ready TUI)', () => {
+ const swallowedBuffer = '❯ Try "how does PipelineEditorialChecks.jsx work?" ⏵⏵ bypass permissions on (shift+tab to cycle)';
+ expect(isPasteConfirmed(swallowedBuffer, { verifiablePrefix: prefix, promptMarkerCount: 0 })).toBe(false);
+ });
+
+ it('ignores paste markers echoed from the prompt itself (count must EXCEED promptMarkerCount)', () => {
+ // A transcript-analysis prompt that itself contains a `[Pasted text #1]` chip:
+ // the echoed marker must not be mistaken for the TUI's own commit marker.
+ const echoOnlyBuffer = '❯ [Pastedtext#1+2lines] analyze this transcript';
+ expect(isPasteConfirmed(echoOnlyBuffer, { verifiablePrefix: prefix, promptMarkerCount: 1 })).toBe(false);
+ // One MORE marker than the prompt carried → the TUI's genuine commit → confirmed.
+ const echoPlusCommit = '❯ [Pastedtext#1+2lines] analyze this transcript [Pastedtext#2+2lines]';
+ expect(isPasteConfirmed(echoPlusCommit, { verifiablePrefix: prefix, promptMarkerCount: 1 })).toBe(true);
+ });
+
+ it('confirms when there is nothing to verify against (no verifiable prefix)', () => {
+ expect(isPasteConfirmed('anything at all', { verifiablePrefix: null, promptMarkerCount: 0 })).toBe(true);
+ expect(isPasteConfirmed('anything at all', {})).toBe(true);
+ });
});
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 593f54540e..0357583a86 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -52,7 +52,7 @@ import {
PASTE_RETRY_MAX_ATTEMPTS,
PASTE_RETRY_BASE_DELAY_MS,
extractVerifiablePromptPrefix,
- verifyPasteRendered,
+ isPasteConfirmed,
} from '../lib/tuiHandshake.js';
import { agentGuardEnv } from '../lib/agentGuard/index.js';
import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';
@@ -903,32 +903,35 @@ export async function spawnTuiAgent({
);
};
- // After paste-commit conditions are met, verify the prompt text actually
- // rendered before submitting. If verification fails, retry with backoff.
- const verifyAndSubmit = (capturedBuffer) => {
+ // Confirms the TUI actually received the paste before we submit. The
+ // paste-commit MARKER ([Pasted text #N]) is authoritative — Claude Code
+ // collapses a multi-line paste into that chip and HIDES the body text, so a
+ // literal text check false-negatives on every multi-line prompt (real
+ // incident 2026-07-05: agent-656efa6e et al. failed `paste-not-rendered`
+ // despite the marker being present). Literal-text verification is only the
+ // fallback for the markerless path — see isPasteConfirmed.
+ const pasteConfirmed = (buffer) =>
+ 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.
+ const retryOrFailPaste = () => {
if (finalized) return;
- // If we have a verifiable prefix, check it appeared in the buffer
- if (verifiablePrefix && !verifyPasteRendered(capturedBuffer, verifiablePrefix)) {
- // Paste was swallowed — the TUI wasn't ready (issue #2192)
- 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`);
- 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 }));
+ 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`);
+ setTimeout(() => {
+ if (finalized) return;
+ attemptPaste(reason);
+ }, retryDelayMs);
return;
}
- // Verification passed (or no prefix to verify) — submit
- submitEnter();
+ // 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 }));
};
const pasteSentAt = Date.now();
@@ -948,39 +951,41 @@ export async function spawnTuiAgent({
|| elapsed >= PASTE_TO_ENTER_FALLBACK_MS) {
clearInterval(pasteEnterTimer);
pasteEnterTimer = null;
- // Capture the buffer before clearing, then run verification (issue #2192).
- // Start a short verification poll to allow a bit more time for the prompt
- // text to render after the paste-commit marker appears.
+ // Capture the buffer before clearing, then confirm the paste (issue #2192).
const commitBuffer = postPasteBuffer || '';
postPasteBuffer = null;
- // If verification is possible and the prompt text isn't visible yet, give
- // it a short window to render (the marker can appear before the full echo).
- if (verifiablePrefix && !verifyPasteRendered(commitBuffer, verifiablePrefix)) {
- let verifyBuffer = commitBuffer;
- const verifyStartedAt = Date.now();
- // Resume accumulation for the verification window
- postPasteBuffer = commitBuffer;
- pasteVerifyTimer = setInterval(() => {
- if (finalized) {
- clearInterval(pasteVerifyTimer);
- pasteVerifyTimer = null;
- postPasteBuffer = null;
- return;
- }
- verifyBuffer = postPasteBuffer || verifyBuffer;
- const verifyElapsed = Date.now() - verifyStartedAt;
- // Check if now verified, or if window expired
- if (verifyPasteRendered(verifyBuffer, verifiablePrefix) || verifyElapsed >= PASTE_VERIFY_WINDOW_MS) {
- clearInterval(pasteVerifyTimer);
- pasteVerifyTimer = null;
- postPasteBuffer = null;
- verifyAndSubmit(verifyBuffer);
- }
- }, PASTE_VERIFY_POLL_MS);
- } else {
- // Already verified or no verification needed
- verifyAndSubmit(commitBuffer);
+ // 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.
+ if (pasteConfirmed(commitBuffer)) {
+ submitEnter();
+ return;
}
+ // Markerless AND text not visible yet: give the prompt a short window to
+ // render (a late marker also counts as confirmed) before declaring it
+ // swallowed. Resume accumulation for the verification window.
+ let verifyBuffer = commitBuffer;
+ const verifyStartedAt = Date.now();
+ postPasteBuffer = commitBuffer;
+ pasteVerifyTimer = setInterval(() => {
+ if (finalized) {
+ clearInterval(pasteVerifyTimer);
+ pasteVerifyTimer = null;
+ postPasteBuffer = null;
+ return;
+ }
+ verifyBuffer = postPasteBuffer || verifyBuffer;
+ const verifyElapsed = Date.now() - verifyStartedAt;
+ const confirmed = pasteConfirmed(verifyBuffer);
+ // Submit once confirmed, or give up and retry/fail when the window expires.
+ if (confirmed || verifyElapsed >= PASTE_VERIFY_WINDOW_MS) {
+ clearInterval(pasteVerifyTimer);
+ pasteVerifyTimer = null;
+ postPasteBuffer = null;
+ if (confirmed) submitEnter();
+ else retryOrFailPaste();
+ }
+ }, PASTE_VERIFY_POLL_MS);
}
}, PASTE_MARKER_POLL_MS);
};