Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(tui): never drop terminal writes — stale "Processing" stuck in the transcript

Salman Qureshi159a0c27014a
diff --git a/src/ui/live-region-residue.test.tsx b/src/ui/live-region-residue.test.tsx
new file mode 100644
index 00000000..26fddce2
--- /dev/null
+++ b/src/ui/live-region-residue.test.tsx
@@ -0,0 +1,227 @@
+/**
+ * Regression: the transient "Processing" block (ThinkingIndicator) must never
+ * survive into the transcript. Reported on the first message of a session:
+ * after the reply arrived, "⠦ Processing · 0s / Starting task" stayed frozen
+ * between the user's message and Mercury's reply.
+ *
+ * The test replays every byte the TUI writes through a small VT screen
+ * (vt-screen.ts) and checks the final screen + scrollback.
+ */
+import { describe, expect, it, vi } from 'vitest';
+
+vi.hoisted(() => {
+ process.env.CI = '0';
+});
+
+import React from 'react';
+import { render } from 'ink';
+import { EventEmitter } from 'node:events';
+import { TuiApp } from './App.js';
+import { CLIChannel, type TuiState } from '../channels/cli.js';
+import { VtScreen } from './vt-screen.js';
+
+class FakeStdout extends EventEmitter {
+ chunks: string[] = [];
+ isTTY = true;
+ constructor(public screen: VtScreen) { super(); }
+ get columns(): number { return this.screen.columns; }
+ get rows(): number { return this.screen.rows; }
+ write(chunk: string): boolean {
+ this.chunks.push(chunk);
+ this.screen.write(chunk);
+ return true;
+ }
+}
+
+class FakeStdin extends EventEmitter {
+ isTTY = true;
+ setEncoding(): void {}
+ setRawMode(): void {}
+ resume(): void {}
+ pause(): void {}
+ ref(): void {}
+ unref(): void {}
+ read(): null { return null; }
+}
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+function mount(initial: TuiState, cols = 100, rows = 40) {
+ let snapshot = initial;
+ const listeners = new Set<() => void>();
+ const channel = {
+ getTuiStateSnapshot: () => snapshot,
+ subscribeToTuiState: (l: () => void) => { listeners.add(l); return () => { listeners.delete(l); }; },
+ };
+ const screen = new VtScreen(cols, rows);
+ const stdout = new FakeStdout(screen);
+ const app = render(
+ <TuiApp channel={channel} onInput={() => {}} onPermissionResolve={() => {}} onExit={() => {}} />,
+ { stdout: stdout as any, stdin: new FakeStdin() as any, exitOnCtrlC: false, patchConsole: false },
+ );
+ const setState = (patch: Partial<TuiState>) => {
+ snapshot = { ...snapshot, ...patch } as TuiState;
+ for (const l of listeners) l();
+ };
+ return { screen, stdout, setState, unmount: app.unmount };
+}
+
+const base = (patch: Record<string, unknown> = {}): TuiState => ({
+ ...new CLIChannel().getTuiStateSnapshot(),
+ mode: 'chat',
+ version: '1.3.1',
+ agentName: 'Mercury',
+ provider: { name: 'anthropic', model: 'claude-opus-5-5' },
+ ...patch,
+} as unknown as TuiState);
+
+const userMsg = { id: 'u1', role: 'user', content: 'so sup', timestamp: Date.now() };
+const agentMsg = {
+ id: 'a1', role: 'agent', timestamp: Date.now(),
+ content: 'Hey Salman. Not much — just standing by.\n\nWhat\'s on your mind tonight?',
+};
+
+describe('live region residue', () => {
+ it.each([[100, 40], [100, 12]])('Processing block disappears when the reply lands (%i×%i)', async (cols, rows) => {
+ const { screen, setState, unmount } = mount(base(), cols, rows);
+ await sleep(80);
+ setState({ chatMessages: [userMsg] as any, isThinking: true, liveActivity: { phase: 'Starting task', stepsDone: 0, startedAt: Date.now() } as any });
+ await sleep(250); // a few spinner ticks
+ expect(screen.text().join('\n')).toContain('Processing');
+ // The reply lands and the turn ends in one state update, as in the agent.
+ setState({ chatMessages: [userMsg, agentMsg] as any, isThinking: false, liveActivity: null as any });
+ await sleep(250);
+ const text = screen.text().join('\n');
+ unmount();
+ if (process.env.DUMP_SCREEN) process.stderr.write(`\n----- ${cols}x${rows} -----\n` + screen.text().map((l) => '|' + l).join('\n') + '\n');
+ expect(text).toContain('Hey Salman');
+ expect(text).not.toContain('Processing');
+ expect(text).not.toContain('Starting task');
+ });
+
+ it('Processing block disappears when the turn ends before the reply is added', async () => {
+ const { screen, setState, unmount } = mount(base());
+ await sleep(80);
+ setState({ chatMessages: [userMsg] as any, isThinking: true, liveActivity: { phase: 'Starting task', stepsDone: 0, startedAt: Date.now() } as any });
+ await sleep(250);
+ setState({ isThinking: false, liveActivity: null as any });
+ await sleep(60);
+ setState({ chatMessages: [userMsg, agentMsg] as any });
+ await sleep(250);
+ const text = screen.text().join('\n');
+ unmount();
+ expect(text).toContain('Hey Salman');
+ expect(text).not.toContain('Processing');
+ });
+});
+
+describe('live region residue — streamed reply', () => {
+ const longReply = Array.from({ length: 14 }, (_, i) => `Line ${i + 1} of a streamed reply that is long enough to matter.`).join('\n');
+ it.each([[100, 40], [100, 24], [100, 16], [60, 24]])('Processing never survives a streamed reply (%i×%i)', async (cols, rows) => {
+ const { screen, setState, unmount } = mount(base(), cols, rows);
+ await sleep(80);
+ const live = { phase: 'Starting task', stepsDone: 0, startedAt: Date.now() };
+ setState({ chatMessages: [userMsg] as any, isThinking: true, liveActivity: live as any });
+ await sleep(200);
+ // Stream the reply in chunks while the turn is still thinking.
+ for (let n = 1; n <= 6; n++) {
+ const partial = longReply.split('\n').slice(0, n * 2).join('\n');
+ setState({ chatMessages: [userMsg, { id: 'a1', role: 'agent', content: partial, timestamp: Date.now(), streaming: true }] as any, isThinking: true, liveActivity: { ...live, phase: 'Composing response' } as any });
+ await sleep(90);
+ }
+ setState({ chatMessages: [userMsg, { id: 'a1', role: 'agent', content: longReply, timestamp: Date.now() }] as any, isThinking: false, liveActivity: null as any });
+ await sleep(300);
+ const text = screen.text().join('\n');
+ unmount();
+ if (process.env.DUMP_SCREEN) process.stderr.write(`\n----- streamed ${cols}x${rows} -----\n` + screen.text().map((l) => '|' + l).join('\n') + '\n');
+ expect(text).toContain('Line 14 of a streamed reply');
+ expect(text).not.toContain('Processing');
+ expect(text).not.toContain('Starting task');
+ expect(text).not.toContain('Composing response');
+ });
+});
+
+describe('live region residue — real CLIChannel turn', () => {
+ async function* chunks(text: string) {
+ for (const piece of text.match(/.{1,12}/gs) ?? []) {
+ await sleep(15);
+ yield piece;
+ }
+ }
+ it.each([
+ ['from splash, first message', true, 100, 40],
+ ['from chat', false, 100, 40],
+ ['from splash, short terminal', true, 100, 18],
+ ] as const)('%s: Processing does not survive', async (_label, fromSplash, cols, rows) => {
+ const channel = new CLIChannel();
+ channel.initSplash('Mercury', '1.3.1');
+ (channel as any).update({ provider: { name: 'anthropic', model: 'claude-opus-5-5' } });
+ if (!fromSplash) (channel as any).update({ mode: 'chat' });
+ const screen = new VtScreen(cols, rows);
+ const stdout = new FakeStdout(screen);
+ const app = render(
+ <TuiApp channel={channel as any} onInput={() => {}} onPermissionResolve={() => {}} onExit={() => {}} />,
+ { stdout: stdout as any, stdin: new FakeStdin() as any, exitOnCtrlC: false, patchConsole: false },
+ );
+ await sleep(500); // launch pad draw-in
+ if (fromSplash) (channel as any).update({ mode: 'chat' });
+ await sleep(50);
+ channel.sendUserMessage('so sup');
+ channel.setLiveActivity('Starting task');
+ await sleep(300);
+ await channel.stream(chunks('Hey Salman. Not much — just standing by.\n\nBots are quiet on the surface.\n\nWhat\'s on your mind tonight?'));
+ channel.clearHeartbeat();
+ await sleep(300);
+ app.unmount();
+ const text = screen.text();
+ if (process.env.DUMP_SCREEN) process.stderr.write(`\n----- real ${_label} ${cols}x${rows} -----\n` + text.map((l) => '|' + l).join('\n') + '\n');
+ expect(text.join('\n')).toContain('on your mind tonight');
+ expect(text.join('\n')).not.toContain('Processing');
+ expect(text.join('\n')).not.toContain('Starting task');
+ });
+});
+
+import { ResilientTuiOutput } from './resilient-output.js';
+
+describe('live region residue — terminal backpressure', () => {
+ /** A TTY whose buffer reports "full" for a window of writes, like a busy macOS tty. */
+ class BackpressureStdout extends FakeStdout {
+ needDrainFor = 0;
+ get writableNeedDrain(): boolean { return this.needDrainFor > 0; }
+ write(chunk: string): boolean {
+ super.write(chunk);
+ if (this.needDrainFor > 0) this.needDrainFor -= 1;
+ return true;
+ }
+ }
+
+ it('a full terminal buffer during the first reply leaves no Processing block behind', async () => {
+ let snapshot = base();
+ const listeners = new Set<() => void>();
+ const channel = { getTuiStateSnapshot: () => snapshot, subscribeToTuiState: (l: () => void) => { listeners.add(l); return () => { listeners.delete(l); }; } };
+ const setState = (patch: Partial<TuiState>) => { snapshot = { ...snapshot, ...patch } as TuiState; for (const l of listeners) l(); };
+ const screen = new VtScreen(100, 40);
+ const tty = new BackpressureStdout(screen);
+ const out = new ResilientTuiOutput(tty as any, new FakeStdout(new VtScreen(100, 40)) as any);
+ const app = render(
+ <TuiApp channel={channel} onInput={() => {}} onPermissionResolve={() => {}} onExit={() => {}} />,
+ { stdout: out as any, stdin: new FakeStdin() as any, exitOnCtrlC: false, patchConsole: false },
+ );
+ await sleep(80);
+ setState({ chatMessages: [userMsg] as any, isThinking: true, liveActivity: { phase: 'Starting task', stepsDone: 0, startedAt: Date.now() } as any });
+ await sleep(120);
+ // The buffer is momentarily full while the reply lands.
+ tty.needDrainFor = 2;
+ setState({ chatMessages: [userMsg, agentMsg] as any, isThinking: false, liveActivity: null as any });
+ await sleep(250);
+ setState({ chatMessages: [userMsg, agentMsg, { id: 'u2', role: 'user', content: 'next', timestamp: Date.now() }] as any });
+ await sleep(250);
+ app.unmount();
+ out.dispose();
+ const text = screen.text().join('\n');
+ if (process.env.DUMP_SCREEN) process.stderr.write('\n----- backpressure -----\n' + screen.text().map((l) => '|' + l).join('\n') + '\n');
+ expect(text).toContain('Hey Salman');
+ expect(text).not.toContain('Processing');
+ expect(text).not.toContain('Starting task');
+ });
+});
diff --git a/src/ui/resilient-output.test.ts b/src/ui/resilient-output.test.ts
index 2a5fd5ef..bfb4b0b4 100644
--- a/src/ui/resilient-output.test.ts
+++ b/src/ui/resilient-output.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';
import { EventEmitter } from 'node:events';
import { PassThrough, Writable } from 'node:stream';
-import { ResilientTuiOutput } from './resilient-output.js';
+import { MAX_BACKLOG_BYTES, ResilientTuiOutput } from './resilient-output.js';
function asWriteStream(stream: Writable): NodeJS.WriteStream {
return stream as NodeJS.WriteStream;
@@ -38,24 +38,54 @@ describe('ResilientTuiOutput', () => {
resilient.dispose();
});
- it('drops animation frames while the terminal is backpressured', () => {
+ it('never drops writes while the terminal is only briefly backpressured', () => {
+ // The renderer writes deltas; a dropped write desyncs the screen
+ // (regression: a "Processing" block stuck in the transcript).
+ let writes = 0;
+ const busy = Object.assign(new EventEmitter(), {
+ columns: 120,
+ rows: 40,
+ isTTY: true,
+ writableNeedDrain: true,
+ writableLength: 64 * 1024,
+ write() {
+ writes++;
+ return false;
+ },
+ });
+ const resilient = new ResilientTuiOutput(busy as unknown as NodeJS.WriteStream, asWriteStream(new PassThrough()));
+
+ for (let i = 0; i < 100; i++) resilient.write(`frame-${i}`);
+
+ expect(writes).toBe(100);
+ resilient.dispose();
+ });
+
+ it('sheds writes only past the backlog cap, then repaints once the terminal drains', () => {
let writes = 0;
const stalled = Object.assign(new EventEmitter(), {
columns: 120,
rows: 40,
isTTY: true,
writableNeedDrain: true,
+ writableLength: MAX_BACKLOG_BYTES + 1,
write() {
writes++;
return false;
},
});
- const fallback = new PassThrough();
- const resilient = new ResilientTuiOutput(stalled as unknown as NodeJS.WriteStream, asWriteStream(fallback));
+ const resilient = new ResilientTuiOutput(stalled as unknown as NodeJS.WriteStream, asWriteStream(new PassThrough()));
+ let repaints = 0;
+ resilient.on('resize', () => repaints++);
for (let i = 0; i < 10_000; i++) resilient.write(`frame-${i}`);
-
expect(writes).toBe(0);
+
+ stalled.writableLength = 0;
+ stalled.emit('drain');
+ expect(repaints).toBe(1);
+ resilient.write('after');
+ expect(writes).toBe(1);
resilient.dispose();
});
});
diff --git a/src/ui/resilient-output.ts b/src/ui/resilient-output.ts
index eee0ec01..26cc6805 100644
--- a/src/ui/resilient-output.ts
+++ b/src/ui/resilient-output.ts
@@ -5,6 +5,9 @@ type TtyWriteStream = NodeJS.WriteStream;
/** DECRST 2004 — mirrors `bracketedPasteSequences(false)` in channels/cli.ts. */
const BRACKETED_PASTE_OFF = '\x1b[?2004l';
+/** Backlog beyond which the terminal is considered stalled and writes are shed. */
+export const MAX_BACKLOG_BYTES = 16 * 1024 * 1024;
+
/**
* Keeps Ink alive when its primary terminal stream is closed unexpectedly.
* stderr normally points at the same TTY through a separate descriptor, so it
@@ -13,6 +16,7 @@ const BRACKETED_PASTE_OFF = '\x1b[?2004l';
export class ResilientTuiOutput extends EventEmitter {
private active: TtyWriteStream;
private failedOver = false;
+ private outOfSync = false;
private readonly onPrimaryError = () => this.failOver();
private readonly onFallbackError = () => {
// There is nowhere else to render, but an output failure must not kill an
@@ -58,9 +62,17 @@ export class ResilientTuiOutput extends EventEmitter {
}
/**
- * Deliberately bypasses Node's Writable buffering. Ink repaints whole-screen
- * frames and does not honor backpressure; adding another Writable here would
- * queue every frame when a terminal is slow and eventually exhaust the heap.
+ * Writes are never dropped in normal operation. The vendored renderer
+ * writes DELTAS — only the rows that changed, plus hardware-cursor moves —
+ * and its bookkeeping assumes every write landed. Dropping one while the
+ * terminal buffer was briefly full (common on macOS during the first
+ * reply's burst) left the screen and the renderer out of sync: a stale
+ * "Processing" block stayed in the transcript and the reply could vanish.
+ * Node buffers writes while the terminal catches up.
+ *
+ * Only a truly stalled terminal (backlog beyond MAX_BACKLOG_BYTES) drops
+ * writes, to protect the heap; the screen is then marked out of sync and a
+ * full repaint is requested as soon as the terminal drains.
*/
write(
chunk: string | Uint8Array,
@@ -68,9 +80,8 @@ export class ResilientTuiOutput extends EventEmitter {
callback?: (error?: Error | null) => void,
): boolean {
const destination = this.active;
- // Ink ignores write() backpressure and repaints the whole screen. Dropping
- // an intermediate animation frame is safe; queueing thousands is not.
- if (destination.writableNeedDrain) {
+ if ((destination.writableLength ?? 0) > MAX_BACKLOG_BYTES) {
+ this.markOutOfSync(destination);
const done = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback;
done?.();
return false;
@@ -98,6 +109,17 @@ export class ResilientTuiOutput extends EventEmitter {
}
}
+ /** After writes were dropped, repaint everything once the terminal drains. */
+ private markOutOfSync(destination: TtyWriteStream): void {
+ if (this.outOfSync) return;
+ this.outOfSync = true;
+ destination.once('drain', () => {
+ this.outOfSync = false;
+ // Ink's resize path forgets the on-screen baseline and rewrites every row.
+ this.emit('resize');
+ });
+ }
+
private failOver(): void {
if (this.failedOver) return;
this.failedOver = true;
diff --git a/src/ui/vt-screen.ts b/src/ui/vt-screen.ts
new file mode 100644
index 00000000..feb8dae7
--- /dev/null
+++ b/src/ui/vt-screen.ts
@@ -0,0 +1,125 @@
+/**
+ * A minimal VT100-style screen for tests: replays what the TUI writes and
+ * returns the visible text, including scrollback. It understands exactly
+ * the sequences Ink, log-update and the cursor-parking patch emit — cursor
+ * moves, line/screen erases, save/restore, show/hide — and ignores colour.
+ * Used to assert that transient live-region rows (spinners, "Processing")
+ * never survive into the transcript.
+ */
+export class VtScreen {
+ /** Every line ever written (scrollback + viewport). */
+ lines: string[][] = [[]];
+ row = 0;
+ col = 0;
+ private saved: { row: number; col: number } | null = null;
+
+ constructor(public columns = 100, public rows = 40) {}
+
+ /** Index of the first viewport row inside `lines`. */
+ private get top(): number {
+ return Math.max(0, this.lines.length - this.rows);
+ }
+
+ private ensureRow(r: number): void {
+ while (this.lines.length <= r) this.lines.push([]);
+ }
+
+ private put(ch: string): void {
+ if (this.col >= this.columns) {
+ this.row += 1;
+ this.col = 0;
+ }
+ this.ensureRow(this.row);
+ const line = this.lines[this.row];
+ while (line.length < this.col) line.push(' ');
+ line[this.col] = ch;
+ this.col += 1;
+ }
+
+ write(data: string): void {
+ const chars = [...data];
+ for (let i = 0; i < chars.length; i++) {
+ const c = chars[i];
+ if (c === '\x1b') {
+ const next = chars[i + 1];
+ if (next === '[') {
+ let j = i + 2;
+ let params = '';
+ while (j < chars.length && /[0-9;?<>=]/.test(chars[j])) params += chars[j++];
+ const final = chars[j];
+ this.csi(params, final);
+ i = j;
+ continue;
+ }
+ if (next === ']') {
+ // OSC: skip to BEL or ST
+ let j = i + 2;
+ while (j < chars.length && chars[j] !== '\x07' && !(chars[j] === '\x1b' && chars[j + 1] === '\\')) j++;
+ i = chars[j] === '\x07' ? j : j + 1;
+ continue;
+ }
+ if (next === '7') { this.saved = { row: this.row, col: this.col }; i += 1; continue; }
+ if (next === '8') { if (this.saved) ({ row: this.row, col: this.col } = this.saved); i += 1; continue; }
+ i += 1;
+ continue;
+ }
+ if (c === '\r') { this.col = 0; continue; }
+ // A real tty (ONLCR) turns \n into \r\n.
+ if (c === '\n') { this.row += 1; this.col = 0; this.ensureRow(this.row); continue; }
+ if (c === '\b') { this.col = Math.max(0, this.col - 1); continue; }
+ if (c < ' ') continue;
+ this.put(c);
+ }
+ }
+
+ private csi(params: string, final: string): void {
+ if (params.startsWith('?')) return; // modes: cursor show/hide, bracketed paste, mouse
+ const nums = params.split(';').map((p) => (p === '' ? NaN : Number(p)));
+ const n = Number.isNaN(nums[0]) ? 1 : nums[0];
+ switch (final) {
+ case 'A': this.row = Math.max(this.top, this.row - n); break;
+ case 'B': this.row += n; this.ensureRow(this.row); break;
+ case 'C': this.col += n; break;
+ case 'D': this.col = Math.max(0, this.col - n); break;
+ case 'E': this.row += n; this.col = 0; this.ensureRow(this.row); break;
+ case 'F': this.row = Math.max(this.top, this.row - n); this.col = 0; break;
+ case 'G': this.col = Math.max(0, n - 1); break;
+ case 'H': case 'f': {
+ const r = Number.isNaN(nums[0]) ? 1 : nums[0];
+ const cc = Number.isNaN(nums[1]) ? 1 : nums[1];
+ this.row = this.top + r - 1; this.col = cc - 1; this.ensureRow(this.row);
+ break;
+ }
+ case 'K': {
+ this.ensureRow(this.row);
+ const line = this.lines[this.row];
+ const mode = Number.isNaN(nums[0]) ? 0 : nums[0];
+ if (mode === 0) line.length = Math.min(line.length, this.col);
+ else if (mode === 1) for (let k = 0; k <= this.col && k < line.length; k++) line[k] = ' ';
+ else this.lines[this.row] = [];
+ break;
+ }
+ case 'J': {
+ const mode = Number.isNaN(nums[0]) ? 0 : nums[0];
+ if (mode === 0) {
+ this.ensureRow(this.row);
+ this.lines[this.row].length = Math.min(this.lines[this.row].length, this.col);
+ this.lines.length = this.row + 1;
+ } else if (mode === 2 || mode === 3) {
+ for (let r = this.top; r < this.lines.length; r++) this.lines[r] = [];
+ }
+ break;
+ }
+ case 's': this.saved = { row: this.row, col: this.col }; break;
+ case 'u': if (this.saved) ({ row: this.row, col: this.col } = this.saved); break;
+ default: break; // SGR (m) and anything else: no layout effect
+ }
+ }
+
+ /** All lines, right-trimmed, without trailing blank lines. */
+ text(): string[] {
+ const out = this.lines.map((l) => l.join('').replace(/\s+$/, ''));
+ while (out.length > 0 && out[out.length - 1] === '') out.pop();
+ return out;
+ }
+}