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 TUI agents stranding the prompt unsent by sending Enter multiple times
[._.]/ Adam Eivycdd030129070
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 1f886d5e9a..e3ac3b27f9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -12,4 +12,6 @@## Fixed+- **TUI agents no longer leave the prompt sitting unsent in the input box** — CoS agents that run inside a terminal-UI provider (Claude Code, Codex) bracketed-paste their task prompt and then send a single Enter to submit it. On a large multi-line prompt that one `\r` could arrive while the TUI was still reflowing the paste and get swallowed — so the prompt sat typed-but-unsubmitted, the agent did no work, idled out after 3 minutes, and was (wrongly) recorded as a successful run. You'd see it only by opening the Shell tab and hitting Enter yourself. The submit Enter now fires a few times spaced ~700ms apart so one lands after the paste settles; re-sending is safe because once the prompt submits the input box is empty and a bare Enter is a no-op. Applies to both the long-running agent path and the one-shot TUI runner. (`server/lib/tuiHandshake.js`, `server/services/agentTuiSpawning.js`, `server/lib/tuiPromptRunner.js`)+- **`calendarSync` test no longer depends on the developer's machine state** — the "throws 401 when Google OAuth is not configured" test read the REAL Google credentials/tokens off disk, so on a machine with OAuth configured it failed with a `GaxiosError` (400 invalid_grant) instead of the pinned 401. The auth client is now mocked to the not-configured state. (`server/services/calendarSync.test.js`)diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.jsindex 84f53ac742..c38d6a3f27 100644--- a/server/lib/tuiHandshake.js+++ b/server/lib/tuiHandshake.js@@ -32,6 +32,52 @@ export const PASTE_MARKER_PATTERN = /\[Pasted text #\d+/;export const PASTE_TO_ENTER_MIN_DELAY_MS = 200;export const PASTE_TO_ENTER_FALLBACK_MS = 3500;+// 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+// 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.+export const SUBMIT_ENTER_ATTEMPTS = 3;+export const SUBMIT_ENTER_SPACING_MS = 700;++/**+ * Submit a freshly-pasted TUI prompt by sending Enter SUBMIT_ENTER_ATTEMPTS+ * times: once immediately, then on a SUBMIT_ENTER_SPACING_MS interval until the+ * attempt budget is spent (see the constants above for why a single Enter is+ * unreliable). Shared by both the agent path and the one-shot runner so the two+ * can't drift.+ *+ * @param {() => void} write — sends one `\r` to the TUI. The caller owns the+ * write mechanism (PTY vs shell session) and its error handling.+ * @param {() => boolean} isFinalized — true once the run has ended; stops the+ * retry loop so it can't write into a torn-down session.+ * @returns {ReturnType<typeof setInterval>|null} the retry interval id (null+ * when no retries were scheduled). The caller stores it so its finalize path+ * can cancel pending retries; calling clearInterval on an already-self-cleared+ * id is a harmless no-op.+ */+export function scheduleSubmitEnters(write, isFinalized) {+ if (isFinalized()) return null;+ write();+ let attemptsLeft = SUBMIT_ENTER_ATTEMPTS - 1;+ if (attemptsLeft <= 0) return null;+ const timer = setInterval(() => {+ if (isFinalized() || attemptsLeft <= 0) {+ clearInterval(timer);+ return;+ }+ attemptsLeft -= 1;+ write();+ }, SUBMIT_ENTER_SPACING_MS);+ return timer;+}+// Defaults the consumer applies when the provider config doesn't pin// per-provider values (provider.tuiPromptDelayMs / .tuiIdleTimeoutMs).export const DEFAULT_TUI_PROMPT_DELAY_MS = 2500;diff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.jsindex 899e676d19..fa8c96944e 100644--- a/server/lib/tuiHandshake.test.js+++ b/server/lib/tuiHandshake.test.js@@ -1,4 +1,4 @@-import { describe, it, expect } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import {READY_POLL_INTERVAL_MS,READY_IDLE_THRESHOLD_MS,@@ -7,6 +7,8 @@ import {PASTE_MARKER_PATTERN,PASTE_TO_ENTER_MIN_DELAY_MS,PASTE_TO_ENTER_FALLBACK_MS,+ SUBMIT_ENTER_ATTEMPTS,+ SUBMIT_ENTER_SPACING_MS,DEFAULT_TUI_PROMPT_DELAY_MS,DEFAULT_TUI_IDLE_TIMEOUT_MS,RAW_BUFFER_CAP,@@ -17,6 +19,7 @@ import {applyCommandDefaults,buildTuiInvocation,detectMissingTuiBinary,+ scheduleSubmitEnters,} from './tuiHandshake.js';import { CODEX_CONFIGURED_DEFAULT } from './providerModels.js';@@ -242,3 +245,39 @@ describe('tuiHandshake.detectMissingTuiBinary', () => {expect(detectMissingTuiBinary(' ', 'codex')).toBe(false);});});++describe('tuiHandshake.scheduleSubmitEnters', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ it('writes SUBMIT_ENTER_ATTEMPTS times: once immediately, the rest spaced apart', () => {+ const write = vi.fn();+ const timer = scheduleSubmitEnters(write, () => false);++ // First Enter fires synchronously; the rest come from the interval.+ expect(write).toHaveBeenCalledTimes(1);+ expect(timer).not.toBeNull();++ vi.advanceTimersByTime(SUBMIT_ENTER_SPACING_MS * (SUBMIT_ENTER_ATTEMPTS + 2));+ expect(write).toHaveBeenCalledTimes(SUBMIT_ENTER_ATTEMPTS);+ });++ it('sends nothing and returns null when already finalized', () => {+ const write = vi.fn();+ const timer = scheduleSubmitEnters(write, () => true);+ expect(write).not.toHaveBeenCalled();+ expect(timer).toBeNull();+ });++ it('stops re-sending once finalized mid-flight (no write into a torn-down session)', () => {+ const write = vi.fn();+ let finalized = false;+ scheduleSubmitEnters(write, () => finalized);+ expect(write).toHaveBeenCalledTimes(1);++ finalized = true;+ vi.advanceTimersByTime(SUBMIT_ENTER_SPACING_MS * (SUBMIT_ENTER_ATTEMPTS + 2));+ // The immediate write already happened; no interval-driven writes follow.+ expect(write).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.jsindex 321053055d..c03abe7942 100644--- a/server/lib/tuiPromptRunner.js+++ b/server/lib/tuiPromptRunner.js@@ -46,6 +46,7 @@ import {PASTE_MARKER_PATTERN,PASTE_TO_ENTER_MIN_DELAY_MS,PASTE_TO_ENTER_FALLBACK_MS,+ scheduleSubmitEnters,PASTE_DEADLINE_MS,READY_POLL_INTERVAL_MS,READY_IDLE_THRESHOLD_MS,@@ -233,6 +234,7 @@ ${prompt}`;let readyTimer = null;let pasteEnterTimer = null;+ let submitEnterTimer = null;let idleWatchTimer = null;let responseFileWatchTimer = null;let hardTimeoutTimer = null;@@ -240,6 +242,7 @@ ${prompt}`;const cleanupTimers = () => {if (readyTimer) { clearInterval(readyTimer); readyTimer = null; }if (pasteEnterTimer) { clearInterval(pasteEnterTimer); pasteEnterTimer = null; }+ if (submitEnterTimer) { clearInterval(submitEnterTimer); submitEnterTimer = null; }if (idleWatchTimer) { clearInterval(idleWatchTimer); idleWatchTimer = null; }if (responseFileWatchTimer) { clearInterval(responseFileWatchTimer); responseFileWatchTimer = null; }if (hardTimeoutTimer) { clearTimeout(hardTimeoutTimer); hardTimeoutTimer = null; }@@ -420,7 +423,14 @@ ${prompt}`;|| elapsed >= PASTE_TO_ENTER_FALLBACK_MS) {clearInterval(pasteEnterTimer);pasteEnterTimer = null;- try { ptyProcess.write('\r'); } catch { /* PTY may have already exited */ }+ // 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()+ // cancels pending retries if the run ends first.+ submitEnterTimer = scheduleSubmitEnters(+ () => { try { ptyProcess.write('\r'); } catch { /* PTY may have already exited */ } },+ () => finalized+ );}}, PASTE_MARKER_POLL_MS);};diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 832a4d6718..635ecb0c35 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -30,6 +30,7 @@ import {PASTE_MARKER_PATTERN,PASTE_TO_ENTER_MIN_DELAY_MS,PASTE_TO_ENTER_FALLBACK_MS,+ scheduleSubmitEnters,PASTE_DEADLINE_MS,OUTPUT_BUFFER_CAP,OUTPUT_BUFFER_HEADROOM,@@ -231,6 +232,7 @@ export async function spawnTuiAgent({let rawBytesWritten = 0;let rawSpoolTruncationWarned = false;let pasteEnterTimer = null;+ let submitEnterTimer = null;const streamingStrip = createStreamingAnsiStripper();@@ -380,6 +382,7 @@ export async function spawnTuiAgent({if (agentData?.promptTimer) clearInterval(agentData.promptTimer);if (agentData?.doneSentinelTimer) clearInterval(agentData.doneSentinelTimer);if (pasteEnterTimer) { clearInterval(pasteEnterTimer); pasteEnterTimer = 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// finalize comes from elsewhere (shell-exit, command-not-found, user@@ -628,9 +631,15 @@ export async function spawnTuiAgent({shellService.writeToSession(sessionId, `\x1b[200~${prompt}\x1b[201~`);appendLine(`📟 Prompt pasted into TUI session ${sessionId.slice(0, 8)} (${reason})`);+ // Submit the pasted prompt with repeated Enters — a single `\r` can be+ // swallowed while the TUI is still reflowing a large paste, stranding the+ // prompt unsent (the "I had to hit Enter myself" bug). Tracked in+ // submitEnterTimer so finish() can cancel pending retries if the agent ends.const submitEnter = () => {- if (finalized) return;- shellService.writeToSession(sessionId, '\r');+ submitEnterTimer = scheduleSubmitEnters(+ () => shellService.writeToSession(sessionId, '\r'),+ () => finalized+ );};const pasteSentAt = Date.now();diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 94375abade..1d013f00e6 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -374,6 +374,50 @@ describe('spawnTuiAgent runtime', () => {);});+ // ── 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,+ // which then idles out and is falsely marked success). The fallback path must+ // fire the Enter SUBMIT_ENTER_ATTEMPTS times, spaced apart, so one lands after+ // the paste settles. Asserts the bracketed paste is written once and `\r` is+ // written exactly SUBMIT_ENTER_ATTEMPTS times.+ it('submit-enter: writes the bracketed paste once and retries the submit Enter SUBMIT_ENTER_ATTEMPTS times', async () => {+ const { SUBMIT_ENTER_ATTEMPTS, SUBMIT_ENTER_SPACING_MS, PASTE_TO_ENTER_FALLBACK_MS } =+ await vi.importActual('../lib/tuiHandshake.js');++ runSpawn({ prompt: 'paste me into the box' });+ await flushMicrotasks();++ // Banner output so firstOutputAt is set, then advance past the prompt-delay+ // floor + readiness idle threshold so the ready poll fires the paste.+ await capturedOnData(Buffer.from('Codex booting...\n'));+ await flushMicrotasks();+ await vi.advanceTimersByTimeAsync(2000);+ await flushMicrotasks();++ const writes = () => vi.mocked(shellService.writeToSession).mock.calls+ .filter(([id]) => id === SESSION_ID);+ const pasteWrites = () => writes().filter(([, data]) => data.startsWith('\x1b[200~'));+ const enterWrites = () => writes().filter(([, data]) => data === '\r');++ // Paste is written exactly once; no Enter has been sent yet (we never+ // emit the [Pasted text] marker, so the 3500ms fallback drives submit).+ expect(pasteWrites()).toHaveLength(1);+ expect(enterWrites()).toHaveLength(0);++ // 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).+ await vi.advanceTimersByTimeAsync(+ PASTE_TO_ENTER_FALLBACK_MS + SUBMIT_ENTER_SPACING_MS * (SUBMIT_ENTER_ATTEMPTS + 3)+ );+ await flushMicrotasks();++ // Exactly SUBMIT_ENTER_ATTEMPTS Enters, and the paste was never re-sent.+ expect(enterWrites()).toHaveLength(SUBMIT_ENTER_ATTEMPTS);+ expect(pasteWrites()).toHaveLength(1);+ });+// ── 2. Command-not-found path ────────────────────────────────────────────────it('command-not-found: finalizeAgent called with success:false, exitCode 127, completionReason=command-not-found', async () => {const spawnPromise = runSpawn();