Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: verify TUI prompt paste actually rendered before submitting (#2192)
[._.]/ Adam Eivy057a66b148dc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex edd945d247..0b88142bed 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -83,3 +83,4 @@## AI Providers- **A wrong local-model default now self-corrects instead of failing the run.** When an Ollama or LM Studio provider is pointed at a model that isn't actually installed (a stale or mis-typed `defaultModel`, or a model you've since deleted), an API call against it returned a dead-end "model not found" — the user had to notice, open settings, and pick a real model by hand. The shared `callProviderAISimple` path now catches that error, lists the backend's actually-installed models, picks the best fit (the editorial recommender's family/size ranking, skipping embedding-only weights), repoints the provider's `defaultModel` (and any tier slot pointing at a missing model), tells the user via a low-priority notification + activity log, and retries the call once — so the run succeeds and the bad config is fixed going forward. Remote/API and CLI providers are left untouched, since their installed models can't be enumerated. (`server/services/localModelHealing.js`, `server/lib/aiProvider.js`)+- **[issue-2192] OpenCode TUI prompt paste no longer gets silently swallowed during slow startup.** When pasting a task prompt into a non-Claude TUI (OpenCode, Codex, Gemini), the paste could be sent while the TUI was still initializing — the prompt never appeared in the input buffer and the agent sat idle for 185s before being reaped as a false success. The TUI paste-commit path now verifies the pasted text actually rendered in the buffer (extracting a unique prefix from the prompt and checking for it after the paste-marker or fallback timeout). If verification fails, the paste is retried with exponential backoff (800ms, 1.6s, 3.2s); after 3 attempts the agent is finalized as a startup failure with a clear `paste-not-rendered` reason instead of a misleading `idle-complete` success. Claude TUIs already had positive input-ready detection and are unaffected. (`server/lib/tuiHandshake.js`, `server/services/agentTuiSpawning.js`)diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.jsindex c9a2e9a26a..3c1c62accb 100644--- a/server/lib/tuiHandshake.js+++ b/server/lib/tuiHandshake.js@@ -47,10 +47,63 @@ export const TUI_INPUT_READY_DEADLINE_MS = 45000;// 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;++// Paste verification: after paste-commit (marker or fallback), verify the prompt+// text actually rendered in the buffer before submitting. If verification fails,+// retry the paste with backoff. This catches TUIs that were still initializing+// when the paste was sent and silently swallowed it (issue #2192).+export const PASTE_VERIFY_POLL_MS = 200;+export const PASTE_VERIFY_WINDOW_MS = 2000; // max time to wait for verification after paste-commit+export const PASTE_RETRY_MAX_ATTEMPTS = 3;+export const PASTE_RETRY_BASE_DELAY_MS = 800;+// Minimum prefix length for verification (shorter prompts verify whole-text)+const MIN_VERIFIABLE_PREFIX_LEN = 15;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;+/**+ * 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+ * leading whitespace/common prefixes) that's unlikely to appear in TUI chrome.+ * Used to verify the paste actually rendered rather than being silently swallowed.+ *+ * @param {string} prompt — the full prompt text being pasted.+ * @returns {string|null} a verifiable prefix, or null if the prompt is too short.+ */+export function extractVerifiablePromptPrefix(prompt) {+ if (typeof prompt !== 'string' || !prompt.trim()) return null;+ // Collapse whitespace and take the first content chunk. Skip leading boilerplate+ // that might match TUI chrome (e.g., "You are a..." is generic).+ const normalized = prompt.replace(/\s+/g, ' ').trim();+ if (normalized.length < MIN_VERIFIABLE_PREFIX_LEN) {+ // Very short prompt: use the whole thing+ return normalized.length >= 5 ? normalized : null;+ }+ // For longer prompts, take a prefix from the middle portion to avoid common+ // prefixes like "You are" or "Please" that might appear elsewhere+ const startOffset = Math.min(10, Math.floor(normalized.length * 0.1));+ const prefixLen = Math.min(40, normalized.length - startOffset);+ return normalized.slice(startOffset, startOffset + prefixLen);+}++/**+ * True when the verifiable prompt prefix appears in the post-paste buffer. Both+ * arguments must be whitespace-normalized (single spaces) and ANSI-stripped.+ * A null/empty prefix always returns true (no verification possible).+ *+ * @param {string} strippedBuffer — ANSI-stripped, whitespace-normalized 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);+}+/*** Count the `[Pasted text #N …]` paste-commit markers in `strippedText`.* Callers MUST pass ANSI-STRIPPED output (see PASTE_MARKER_PATTERN above for whydiff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.jsindex 4cf44f8aba..24d58cc4dd 100644--- a/server/lib/tuiHandshake.test.js+++ b/server/lib/tuiHandshake.test.js@@ -34,6 +34,12 @@ import {buildTuiInvocation,detectMissingTuiBinary,scheduleSubmitEnters,+ PASTE_VERIFY_POLL_MS,+ PASTE_VERIFY_WINDOW_MS,+ PASTE_RETRY_MAX_ATTEMPTS,+ PASTE_RETRY_BASE_DELAY_MS,+ extractVerifiablePromptPrefix,+ verifyPasteRendered,} from './tuiHandshake.js';import { CODEX_CONFIGURED_DEFAULT } from './providerModels.js';@@ -589,3 +595,107 @@ describe('tuiHandshake.scheduleSubmitEnters', () => {expect(write).toHaveBeenCalledTimes(1);});});++// Paste verification helpers (issue #2192)+describe('tuiHandshake — paste verification constants', () => {+ it('pins paste verification constants', () => {+ expect(PASTE_VERIFY_POLL_MS).toBe(200);+ expect(PASTE_VERIFY_WINDOW_MS).toBe(2000);+ expect(PASTE_RETRY_MAX_ATTEMPTS).toBe(3);+ expect(PASTE_RETRY_BASE_DELAY_MS).toBe(800);+ // Verification window should be shorter than the overall paste deadline+ expect(PASTE_VERIFY_WINDOW_MS).toBeLessThan(PASTE_DEADLINE_MS);+ });+});++describe('tuiHandshake.extractVerifiablePromptPrefix', () => {+ it('extracts a prefix from a normal prompt', () => {+ const prompt = 'Please implement the feature described in issue #123. The feature should...';+ const prefix = extractVerifiablePromptPrefix(prompt);+ expect(prefix).toBeTruthy();+ expect(prefix.length).toBeGreaterThanOrEqual(15);+ expect(prefix.length).toBeLessThanOrEqual(40);+ // The prefix should be from the prompt, not the very beginning (skips common prefixes)+ expect(prompt.includes(prefix)).toBe(true);+ expect(prompt.startsWith(prefix)).toBe(false);+ });++ it('returns the whole prompt for very short prompts', () => {+ const prompt = 'Fix the bug';+ const prefix = extractVerifiablePromptPrefix(prompt);+ expect(prefix).toBe('Fix the bug');+ });++ it('returns null for prompts too short to verify', () => {+ expect(extractVerifiablePromptPrefix('Hi')).toBeNull();+ expect(extractVerifiablePromptPrefix('')).toBeNull();+ expect(extractVerifiablePromptPrefix(null)).toBeNull();+ expect(extractVerifiablePromptPrefix(undefined)).toBeNull();+ });++ it('collapses whitespace in the prefix', () => {+ const prompt = 'Please implement\n\nthe feature';+ const prefix = extractVerifiablePromptPrefix(prompt);+ expect(prefix).not.toMatch(/\s{2,}/);+ expect(prefix).not.toContain('\n');+ });++ it('handles prompts with leading boilerplate', () => {+ const prompt = 'You are a helpful assistant. Please implement the truncateMiddle function.';+ const prefix = extractVerifiablePromptPrefix(prompt);+ // Should skip the first few characters to avoid matching common prefixes+ expect(prefix.startsWith('You are')).toBe(false);+ expect(prompt.replace(/\s+/g, ' ').includes(prefix)).toBe(true);+ });+});++describe('tuiHandshake.verifyPasteRendered', () => {+ it('returns true when prefix is found in buffer', () => {+ const prefix = 'implement the truncateMiddle function';+ const buffer = 'Some TUI chrome... implement the truncateMiddle function ...more text';+ expect(verifyPasteRendered(buffer, prefix)).toBe(true);+ });++ it('returns false when prefix is not found in buffer', () => {+ const prefix = 'implement the truncateMiddle function';+ const buffer = 'Some TUI chrome without the prompt text';+ expect(verifyPasteRendered(buffer, prefix)).toBe(false);+ });++ it('handles whitespace normalization', () => {+ const prefix = 'implement the function';+ const buffer = 'implement the\n function';+ expect(verifyPasteRendered(buffer, prefix)).toBe(true);+ });++ it('returns true for null/empty prefix (no verification possible)', () => {+ expect(verifyPasteRendered('any buffer', null)).toBe(true);+ expect(verifyPasteRendered('any buffer', '')).toBe(true);+ expect(verifyPasteRendered('any buffer', undefined)).toBe(true);+ });++ it('returns false for non-string buffer', () => {+ expect(verifyPasteRendered(null, 'prefix')).toBe(false);+ expect(verifyPasteRendered(undefined, 'prefix')).toBe(false);+ expect(verifyPasteRendered(123, 'prefix')).toBe(false);+ });++ it('handles real-world OpenCode scenario (issue #2192)', () => {+ // Simulates the case where OpenCode was still initializing+ const prompt = 'Run /do:next --issues --swarm using the truncateMiddle helper';+ const prefix = extractVerifiablePromptPrefix(prompt);++ // Empty buffer = paste was swallowed+ expect(verifyPasteRendered('', prefix)).toBe(false);++ // Only TUI chrome = paste was swallowed+ expect(verifyPasteRendered('Ask anything... (ESC to exit)', prefix)).toBe(false);++ // Prompt text visible (with the full prompt echoed) = paste succeeded+ // The buffer would contain the actual prompt text after a successful paste+ expect(verifyPasteRendered(`Ask anything... ${prompt}`, prefix)).toBe(true);++ // 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);+ });+});diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex d68bc3d11e..0ea2813ce2 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -47,6 +47,12 @@ import {RAW_SPOOL_MAX_BYTES,inferTuiCommand,applyCommandDefaults,+ PASTE_VERIFY_POLL_MS,+ PASTE_VERIFY_WINDOW_MS,+ PASTE_RETRY_MAX_ATTEMPTS,+ PASTE_RETRY_BASE_DELAY_MS,+ extractVerifiablePromptPrefix,+ verifyPasteRendered,} from '../lib/tuiHandshake.js';import { agentGuardEnv } from '../lib/agentGuard/index.js';import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';@@ -383,6 +389,7 @@ export async function spawnTuiAgent({let rawBytesWritten = 0;let rawSpoolTruncationWarned = false;let pasteEnterTimer = null;+ let pasteVerifyTimer = null;let submitEnterTimer = null;const streamingStrip = createStreamingAnsiStripper();@@ -533,6 +540,7 @@ export async function spawnTuiAgent({if (agentData?.promptTimer) clearInterval(agentData.promptTimer);if (agentData?.doneSentinelTimer) clearInterval(agentData.doneSentinelTimer);if (pasteEnterTimer) { clearInterval(pasteEnterTimer); pasteEnterTimer = null; }+ if (pasteVerifyTimer) { clearInterval(pasteVerifyTimer); pasteVerifyTimer = null; }if (submitEnterTimer) { clearInterval(submitEnterTimer); submitEnterTimer = null; }// Release the post-paste accumulator even when finalize fires mid-paste-// window. The pasteEnterTimer's own cleanup path nulls this too, but if@@ -831,6 +839,11 @@ export async function spawnTuiAgent({});};+ // Extract a verifiable prefix from the prompt for paste verification (issue #2192).+ // Computed once up front so retry attempts use the same verification target.+ const verifiablePrefix = extractVerifiablePromptPrefix(prompt);+ let pasteAttempt = 0;+const sendPrompt = async (reason) => {if (finalized || promptSentAt) return;promptSentAt = Date.now();@@ -848,13 +861,26 @@ export async function spawnTuiAgent({);return;}+ // Start the paste attempt — may be retried if verification fails (issue #2192).+ attemptPaste(reason);+ };++ // Actually perform a paste attempt. Separated from sendPrompt so retries don't+ // re-run the liveness guard or re-set promptSentAt. Increments pasteAttempt on+ // each call; clears any pending timers from the previous attempt first.+ const attemptPaste = (reason) => {+ pasteAttempt += 1;+ const attemptNum = pasteAttempt;+ if (pasteEnterTimer) { clearInterval(pasteEnterTimer); pasteEnterTimer = null; }+ if (pasteVerifyTimer) { clearInterval(pasteVerifyTimer); pasteVerifyTimer = null; }// Start capturing post-paste output. Set BEFORE writing the paste so// every chunk that arrives in response gets appended. Cleared the moment// detection resolves (marker seen or fallback elapsed) so the accumulator// never lives beyond the paste-marker window.postPasteBuffer = '';shellService.writeToSession(sessionId, `\x1b[200~${prompt}\x1b[201~`);- appendLine(`📟 Prompt pasted into TUI session ${sessionId.slice(0, 8)} (${reason})`);+ const attemptSuffix = attemptNum > 1 ? ` [attempt ${attemptNum}/${PASTE_RETRY_MAX_ATTEMPTS}]` : '';+ appendLine(`📟 Prompt pasted into TUI session ${sessionId.slice(0, 8)} (${reason})${attemptSuffix}`);// Submit the pasted prompt with repeated Enters — a single `\r` can be// swallowed while the TUI is still reflowing a large paste, stranding the@@ -870,6 +896,34 @@ 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) => {+ 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 }));+ return;+ }+ // Verification passed (or no prefix to verify) — submit+ submitEnter();+ };+const pasteSentAt = Date.now();pasteEnterTimer = setInterval(() => {if (finalized) {@@ -887,8 +941,39 @@ 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.+ const commitBuffer = postPasteBuffer || '';postPasteBuffer = null;- submitEnter();+ // 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);+ }}}, PASTE_MARKER_POLL_MS);};diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex dcde170ef5..0a4efc45d3 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -435,6 +435,12 @@ describe('spawnTuiAgent runtime', () => {await vi.advanceTimersByTimeAsync(2000);await flushMicrotasks();+ // Emit the prompt echo so paste verification passes (issue #2192).+ // In a real TUI, the paste is echoed in the input buffer; tests must+ // simulate this or verification fails and Enter is never sent.+ await capturedOnData(Buffer.from('do the thing\n'));+ await flushMicrotasks();+// Advance past PASTE_TO_ENTER_FALLBACK_MS (3500ms) so the submit-Enter fires// and promptSubmittedAt is set — work-activity is only observed AFTER submit// (the prompt echo before that must not be scanned; issue #1229 review).@@ -764,6 +770,11 @@ describe('spawnTuiAgent runtime', () => {expect(pasteWrites()).toHaveLength(1);expect(enterWrites()).toHaveLength(0);+ // Emit the prompt echo so paste verification passes (issue #2192).+ // In a real TUI, the paste is echoed in the input buffer.+ await capturedOnData(Buffer.from('ste me into the box\n'));+ await flushMicrotasks();+// Advance past the fallback window AND the full spread of retry spacing// intervals. Once the budget is exhausted the interval stops re-sending// (Enter into an empty box would be a no-op anyway).@@ -1027,6 +1038,9 @@ describe('spawnTuiAgent runtime', () => {await flushMicrotasks();await vi.advanceTimersByTimeAsync(2000);await flushMicrotasks();+ // Emit the prompt echo so paste verification passes (issue #2192).+ await capturedOnData(Buffer.from('do the thing\n'));+ await flushMicrotasks();await vi.advanceTimersByTimeAsync(3600); // submit-Enter fires → promptSubmittedAt setawait flushMicrotasks();await capturedOnData(Buffer.from('(1s · thinking with high effort)\n'));