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(ink): live-region overflow guard — bottom-trim tall frames, never clear scrollback

Salman Qureshib6170844dfb3
diff --git a/patches/ink+5.2.1.patch b/patches/ink+5.2.1.patch
index 41c3e200..b5c6447a 100644
--- a/patches/ink+5.2.1.patch
+++ b/patches/ink+5.2.1.patch
@@ -94,7 +94,7 @@ index 9c54f14..6274f9a 100644
const style = useMemo(() => ({
position: 'absolute',
diff --git a/node_modules/ink/build/ink.js b/node_modules/ink/build/ink.js
-index a9c444f..32e1ae4 100644
+index a9c444f..f3457f7 100644
--- a/node_modules/ink/build/ink.js
+++ b/node_modules/ink/build/ink.js
@@ -14,6 +14,14 @@ import logUpdate from './log-update.js';
@@ -112,10 +112,12 @@ index a9c444f..32e1ae4 100644
export default class Ink {
options;
log;
-@@ -99,6 +107,14 @@ export default class Ink {
+@@ -98,7 +106,33 @@ export default class Ink {
+ if (this.isUnmounted) {
return;
}
- const { output, outputHeight, staticOutput } = render(this.rootNode);
+- const { output, outputHeight, staticOutput } = render(this.rootNode);
++ let { output, outputHeight, staticOutput } = render(this.rootNode);
+ // Freeze gate (Cosmic Stack patch): drop the frame entirely — no
+ // write, and crucially NO advance of `lastOutput` or log-update's
+ // `previousOutput`/`previousLineCount` baseline, so the frame that
@@ -124,11 +126,29 @@ index a9c444f..32e1ae4 100644
+ return;
+ }
+ if (frameGate.armed) frameGate.armed = false;
++ // Live-region guard (Cosmic Stack patch): a live frame as tall as (or
++ // taller than) the terminal cannot go through log-update's cursor
++ // arithmetic, and stock ink's fallback is `clearTerminal +
++ // fullStaticOutput + output` — erasing the ENTIRE scrollback buffer
++ // and re-dumping every static byte ever printed, on EVERY frame. With
++ // a long transcript that is megabytes per frame: the scrollbar jumps
++ // to the top, the UI flickers, and native scrolling becomes
++ // impossible. Instead keep the frame bottom-anchored: trim to what
++ // fits (rows - 1) and let the normal diff path write it. Scrollback
++ // is never cleared, the transcript is never re-dumped, and the newest
++ // rows (live tail, input, status bar) stay visible.
++ const maxLiveRows = Math.max(1, (this.options.stdout.rows || 24) - 1);
++ if (outputHeight >= (this.options.stdout.rows || 24)) {
++ // `output` is newline-terminated per row WITHOUT a trailing blank
++ // line (log-update appends its own), so split and re-join verbatim.
++ output = output.split('\n').slice(-maxLiveRows).join('\n');
++ outputHeight = maxLiveRows;
++ }
// If <Static> output isn't empty, it means new children have been added to it
const hasStaticOutput = staticOutput && staticOutput !== '\n';
if (this.options.debug) {
diff --git a/node_modules/ink/build/log-update.js b/node_modules/ink/build/log-update.js
-index 547421e..a2bbc9b 100644
+index 547421e..73cb297 100644
--- a/node_modules/ink/build/log-update.js
+++ b/node_modules/ink/build/log-update.js
@@ -13,9 +13,26 @@ const create = (stream, { showCursor = false } = {}) => {
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 56765304..db286b72 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -564,8 +564,12 @@ export class Agent {
// Research-y message prompt: when research mode is off and the message looks
// like a deep-research request, ask whether to run a full research pass.
+ // Never prompt in Mercury Code (the coding TUI) — its questions are about
+ // the repo, not web research, so the prompt is pure friction there.
const isUserMessage = msg.channelType !== 'internal' && msg.senderId !== 'system' && !trimmed.startsWith('/');
- if (isUserMessage && !this.researchMode.isActive() && looksResearchy(trimmed)) {
+ const promptChannel = this.channels.getChannelForMessage(msg);
+ const inMercuryCode = promptChannel instanceof CLIChannel && promptChannel.getTuiState().mercuryCode != null;
+ if (isUserMessage && !inMercuryCode && !this.researchMode.isActive() && looksResearchy(trimmed)) {
this.promptResearchMode(msg, workKey).catch((err) => {
logger.warn({ err: err.message }, 'Research-mode prompt failed — proceeding with normal message');
this.queueMessage(msg, workKey);
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index 8c92b175..26aa6648 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -2280,16 +2280,30 @@ const STREAM_TAIL_MAX_LINES = 48;
* sync with MercuryCodeView's render tree. */
const MERCURY_CODE_LIVE_CHROME_ROWS = 14;
+/**
+ * Extra rows of headroom under the terminal height. MERCURY_CODE_LIVE_CHROME_ROWS
+ * is an estimate: MercuryLiveFeedback alone can render ~10 rows (phase, running
+ * tool, done ticks, thinking preview, up to 4 swarm agents) and prompts/checklists
+ * stack on top. If the live region reaches `rows`, stock ink used to clear the
+ * whole terminal (scrollback included) and re-dump the transcript every frame —
+ * the patched ink now bottom-trims the frame instead, but the goal is to never
+ * need the trim, so the tail cap keeps real chrome strictly under `rows`.
+ */
+const LIVE_HEIGHT_SAFETY_MARGIN = 2;
+
/**
* Live streaming tail row cap, derived from the terminal height. The cap must
- * stay well under `rows`: ink clears the whole terminal and rewrites the
- * static transcript whenever the live region's height reaches `rows`
- * (ink.js: `outputHeight >= stdout.rows`) — a fixed 48-row tail on a 30-row
- * terminal would nuke scrollback every frame. Diff-render makes the rewrite
- * itself cheap (only changed rows are re-emitted), so the cap is generous.
+ * keep the live region strictly under `rows`: ink's overflow path rewrites the
+ * whole terminal whenever `outputHeight >= stdout.rows`, and with a long
+ * conversation that re-dump is enormous. Diff-render makes per-frame writes
+ * cheap, so the cap stays generous; the ink-level guard is the backstop when
+ * transient chrome (prompts, plan checklist) pushes the region over.
*/
export function streamTailRowCap(terminalRows: number): number {
- return Math.max(STREAM_TAIL_MIN_LINES, Math.min(STREAM_TAIL_MAX_LINES, terminalRows - MERCURY_CODE_LIVE_CHROME_ROWS));
+ return Math.max(
+ STREAM_TAIL_MIN_LINES,
+ Math.min(STREAM_TAIL_MAX_LINES, terminalRows - MERCURY_CODE_LIVE_CHROME_ROWS - LIVE_HEIGHT_SAFETY_MARGIN),
+ );
}
/**
diff --git a/src/ui/freeze-frame.test.tsx b/src/ui/freeze-frame.test.tsx
index 39f4dcdd..096a39ed 100644
--- a/src/ui/freeze-frame.test.tsx
+++ b/src/ui/freeze-frame.test.tsx
@@ -159,7 +159,7 @@ describe('Mercury Code streaming tail: full preview + padded height', () => {
{ stdout, exitOnCtrlC: false, patchConsole: false },
);
void rerender;
- const cap = Math.max(6, Math.min(48, 45 - 14)); // streamTailRowCap(45)
+ const cap = Math.max(6, Math.min(48, 45 - 14 - 2)); // streamTailRowCap(45)
// The 200-line message must render MANY more rows live than the old
// 12-row cap — full preview of the streaming block — while staying
// bounded by the cap.
@@ -172,13 +172,15 @@ describe('Mercury Code streaming tail: full preview + padded height', () => {
}, 10_000);
it('streamTailRowCap derives from the terminal rows (never >= rows)', () => {
- // 24-row terminal: 10 tail rows; 30 rows: 16; 60+: capped at 48 —
- // always rows - 14 at minimum 6, so ink's clearTerminal path
- // (outputHeight >= rows) can never trip.
- const cap = (rows: number) => Math.max(6, Math.min(48, rows - 14));
- expect(cap(24)).toBe(10);
- expect(cap(30)).toBe(16);
- expect(cap(45)).toBe(31);
+ // 24-row terminal: 8 tail rows; 30 rows: 14; 60+: capped at 48 —
+ // always rows - 16 at minimum 6, so the tail plus the worst realistic
+ // live chrome (~14 rows: feedback block, input box, status bar) stays
+ // strictly under `rows` and ink's overflow path (outputHeight >= rows)
+ // can never trip during a normal stream.
+ const cap = (rows: number) => Math.max(6, Math.min(48, rows - 14 - 2));
+ expect(cap(24)).toBe(8);
+ expect(cap(30)).toBe(14);
+ expect(cap(45)).toBe(29);
expect(cap(120)).toBe(48);
expect(cap(10)).toBe(6); // tiny terminal: floor, never negative
});
diff --git a/src/ui/live-region-guard.test.tsx b/src/ui/live-region-guard.test.tsx
new file mode 100644
index 00000000..a8583773
--- /dev/null
+++ b/src/ui/live-region-guard.test.tsx
@@ -0,0 +1,180 @@
+import { describe, expect, it, vi } from 'vitest';
+
+// Ink skips ALL frame writes when it detects CI (`is-in-ci` → process.env.CI).
+// Setting CI to '0' (the one value is-in-ci treats as false) BEFORE the ink
+// module loads restores normal rendering.
+vi.hoisted(() => {
+ process.env.CI = '0';
+});
+
+import React from 'react';
+import { render, Box, Text, Static } from 'ink';
+import { EventEmitter } from 'node:events';
+import { MercuryCodeView } from './App.js';
+import type { TuiState } from '../channels/cli.js';
+
+class FakeStdout extends EventEmitter {
+ chunks: string[] = [];
+ columns = 80;
+ rows = 12;
+ isTTY = true;
+ write(chunk: string): boolean {
+ this.chunks.push(chunk);
+ return true;
+ }
+ get output(): string {
+ return this.chunks.join('');
+ }
+}
+
+class FakeStdin extends EventEmitter {
+ setEncoding(): void {}
+ setRawMode(): void {}
+ resume(): void {}
+ pause(): void {}
+ ref(): void {}
+ unref(): void {}
+ isTTY = true;
+}
+
+const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
+
+/**
+ * Live-region overflow guard, against the REAL patched ink.
+ *
+ * Stock ink's fallback for a live frame as tall as (or taller than) the
+ * terminal is `clearTerminal + fullStaticOutput + output` — it erases the
+ * ENTIRE scrollback buffer (`\x1b[3J`) and re-dumps every static byte ever
+ * printed, on EVERY frame. In Mercury Code with a long conversation that is
+ * megabytes per frame: the scrollbar jumps to the top, the UI flickers, and
+ * native scrolling becomes impossible. The patched ink must instead trim the
+ * live frame to what fits (bottom-anchored, so the input + status bar
+ * survive) and write it through the normal diff path — scrollback is never
+ * cleared and the transcript is never re-dumped.
+ */
+describe('ink live-region overflow guard', () => {
+ it('never clears scrollback or re-dumps static output when the live frame exceeds the terminal', async () => {
+ const stdout = new FakeStdout() as any;
+
+ const liveRegion = (suffix: string) =>
+ React.createElement(
+ Box,
+ { flexDirection: 'column' },
+ Array.from({ length: 40 }, (_, i) =>
+ React.createElement(Text, { key: i }, `live row ${i}${suffix}`),
+ ),
+ );
+
+ // Static transcript first: finalized content that lives in scrollback.
+ // (createElement's Static typing expects a children-as-function signature
+ // TS can't express generically here — cast through `never`.)
+ const staticBlock = React.createElement(
+ Static,
+ { items: ['static message one', 'static message two'] } as never,
+ ((item: string) => React.createElement(Text, { key: item }, item)) as never,
+ );
+
+ const { rerender, unmount } = render(
+ React.createElement(
+ Box,
+ { flexDirection: 'column' },
+ staticBlock,
+ liveRegion(''),
+ ),
+ { stdout, exitOnCtrlC: false, patchConsole: false },
+ );
+ await sleep(300);
+
+ const firstFrame = stdout.output;
+ expect(firstFrame).toContain('static message one');
+ expect(firstFrame).toContain('live row 39');
+
+ // The overflow path must not fire — not even once.
+ expect(stdout.output).not.toContain('\x1b[3J');
+
+ // The static transcript must never be re-dumped: a clearTerminal pass
+ // would print 'static message one' a second time in the byte stream.
+ const dumpCount = firstFrame.split('static message one').length - 1;
+ rerender(
+ React.createElement(
+ Box,
+ { flexDirection: 'column' },
+ staticBlock,
+ liveRegion(' tick'),
+ ),
+ );
+ await sleep(300);
+ expect(stdout.output.split('static message one').length - 1).toBe(dumpCount);
+ expect(stdout.output).not.toContain('\x1b[3J');
+
+ // The bottom of the live region must stay visible (bottom-anchored trim):
+ // the newest rows — what the user is reading — survive the trim.
+ const lastChunk = stdout.chunks[stdout.chunks.length - 1];
+ expect(lastChunk).toContain('live row 39 tick');
+
+ unmount();
+ }, 10_000);
+
+ it('Mercury Code never trips the clearTerminal path at worst-case live chrome (24-row terminal)', async () => {
+ // Every live block stacked at once on the smallest common macOS terminal
+ // (24 rows): full streaming tail, a running tool, a swarm, a plan
+ // checklist, a permission prompt, and a multi-line input. Before the
+ // guard, any frame this tall erased scrollback and re-dumped the whole
+ // transcript per frame — the long-conversation rerender storm.
+ const longContent = Array.from({ length: 200 }, (_, i) => `Line ${i}: streaming content`).join('\n');
+ const state = {
+ mode: 'mercury-code',
+ version: '1.2.5',
+ agentName: 'Mercury',
+ programmingMode: 'execute',
+ projectContext: '/tmp/proj',
+ permissionMode: 'allow-all',
+ chatMessages: [
+ { id: 'u1', role: 'user', content: 'refactor the auth module', timestamp: 1 },
+ { id: 'a1', role: 'agent', content: longContent, timestamp: 2, streaming: true },
+ ],
+ toolSteps: [
+ { id: 't1', label: 'Running tests', status: 'running', startedAt: 1, outputPreview: '' },
+ { id: 't2', label: 'Edited file', status: 'done', outputPreview: '' },
+ ],
+ subAgents: Array.from({ length: 4 }, (_, i) => ({
+ id: `agent-${i}`, status: 'running', task: `Investigate module ${i}`,
+ })),
+ planProgress: [
+ { label: 'Read auth module', status: 'done' },
+ { label: 'Refactor login flow', status: 'active' },
+ { label: 'Update tests', status: 'pending' },
+ { label: 'Update docs', status: 'pending' },
+ ],
+ permissionPrompt: {
+ type: 'choice' as const, message: 'Proceed?', options: [{ value: 'y', label: 'Yes' }],
+ resolve: () => {},
+ },
+ liveActivity: { phase: 'Implementing', startedAt: 1, stepsDone: 3 },
+ backgroundTasks: [],
+ skills: [],
+ sidebarSections: [],
+ mercuryCode: {
+ cwd: '/tmp/proj', dirName: 'proj', git: { branch: 'main', ahead: 0, behind: 0, dirty: 2 },
+ scrollOffset: 0, exitConfirm: false,
+ },
+ tuiFrozen: false,
+ isThinking: false,
+ } as unknown as TuiState;
+
+ const stdout = new FakeStdout() as any;
+ stdout.rows = 24;
+ const { unmount } = render(
+ React.createElement(MercuryCodeView, { state, cols: 100, rows: 24 }),
+ { stdout, exitOnCtrlC: false, patchConsole: false },
+ );
+ await sleep(300);
+
+ expect(stdout.output).not.toContain('\x1b[3J');
+ // Bottom-anchored trim keeps the newest rows visible: the status bar and
+ // input box (the last rows of the live region) must survive.
+ expect(stdout.output).toContain('proj');
+
+ unmount();
+ }, 10_000);
+});
\ No newline at end of file