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.

feat(code): full streaming preview + scroll lock (Ctrl+S) — free scroll during in-progress chat

Salman Qureshif7eee7956cdf
diff --git a/patches/ink+5.2.1.patch b/patches/ink+5.2.1.patch
index 3377fcf4..41c3e200 100644
--- a/patches/ink+5.2.1.patch
+++ b/patches/ink+5.2.1.patch
@@ -93,11 +93,77 @@ 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
+--- a/node_modules/ink/build/ink.js
++++ b/node_modules/ink/build/ink.js
+@@ -14,6 +14,14 @@ import logUpdate from './log-update.js';
+ import instances from './instances.js';
+ import App from './components/App.js';
+ const noop = () => { };
++// Freeze gate (Cosmic Stack patch): while frozen, onRender writes NOTHING
++// and must not advance lastOutput / log-update's baseline — the resume frame
++// must diff against the last frame actually on screen. `armed` lets exactly
++// one frame through (the "⏸ frozen" hint) if its output contains `marker`.
++// Exposed on globalThis so host code can reach it without a type-level
++// import of this internal module.
++export const frameGate = { frozen: false, armed: false, marker: '' };
++globalThis.__mercuryFrameGate = frameGate;
+ export default class Ink {
+ options;
+ log;
+@@ -99,6 +107,14 @@ export default class Ink {
+ return;
+ }
+ const { 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
++ // ends the freeze diffs against what is actually on screen.
++ if (frameGate.frozen && !(frameGate.armed && frameGate.marker && output.includes(frameGate.marker))) {
++ return;
++ }
++ if (frameGate.armed) frameGate.armed = false;
+ // 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
+--- 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 } = {}) => {
+ if (output === previousOutput) {
+ return;
+ }
++ // Diff-render (Cosmic Stack patch): erase and rewrite only the rows
++ // from the first changed line onward; identical rows above stay on
++ // screen untouched. Ink 5's log-update erased and rewrote the ENTIRE
++ // frame on every render — a prompt-selection change or spinner tick
++ // repainted the whole live region, which read as a full-UI flash.
++ // The row bytes are compared verbatim (layout is deterministic), and
++ // the erase count accounts for the trailing blank line exactly like
++ // `previousLineCount` does, so `clear()` and cursor arithmetic stay
++ // in sync with the original accounting.
++ const previousRows = previousOutput === '' ? [] : previousOutput.slice(0, -1).split('\n');
++ const nextRows = output.slice(0, -1).split('\n');
++ const common = Math.min(previousRows.length, nextRows.length);
++ let firstChange = 0;
++ while (firstChange < common && previousRows[firstChange] === nextRows[firstChange]) {
++ firstChange++;
++ }
++ const eraseCount = previousLineCount - firstChange;
+ previousOutput = output;
+- stream.write(ansiEscapes.eraseLines(previousLineCount) + output);
+ previousLineCount = output.split('\n').length;
++ stream.write(ansiEscapes.eraseLines(eraseCount) + nextRows.slice(firstChange).join('\n') + '\n');
+ };
+ render.clear = () => {
+ stream.write(ansiEscapes.eraseLines(previousLineCount));
diff --git a/node_modules/ink/build/reconciler.js b/node_modules/ink/build/reconciler.js
-index 55acec7..035907a 100644
+index 55acec7..f440fa9 100644
--- a/node_modules/ink/build/reconciler.js
+++ b/node_modules/ink/build/reconciler.js
-@@ -58,6 +58,42 @@ const cleanupYogaNode = (node) => {
+@@ -58,6 +58,40 @@ const cleanupYogaNode = (node) => {
node?.unsetMeasureFunc();
node?.freeRecursive();
};
@@ -105,10 +171,8 @@ index 55acec7..035907a 100644
+// reference pointing at freed memory. The renderer and layout code read those
+// references through optional chaining, so nulling them here turns what was a
+// fatal WASM trap ("RuntimeError: memory access out of bounds" in
-+// getComputedWidth) into a clean no-op. Upstream only clears the direct
-+// reference (ink >=7); ancestors of <Static> that were freed wholesale left
-+// `rootNode.staticNode` dangling. See facebook/yoga#1818 and the equivalent
-+// downstream fix in qwen-code#7816.
++// getComputedWidth) into a clean no-op. See facebook/yoga#1818 and the
++// equivalent downstream fix in qwen-code#7816. (Cosmic Stack patch.)
+const clearYogaRefs = (node) => {
+ node.yogaNode = undefined;
+ // Host elements carry a childNodes array; ink's `#text` nodes do not.
@@ -140,7 +204,7 @@ index 55acec7..035907a 100644
export default createReconciler({
getRootHostContext: () => ({
isInsideText: false,
-@@ -173,7 +209,7 @@ export default createReconciler({
+@@ -173,7 +207,7 @@ export default createReconciler({
insertInContainerBefore: insertBeforeNode,
removeChildFromContainer(node, removeNode) {
removeChildNode(node, removeNode);
@@ -149,7 +213,7 @@ index 55acec7..035907a 100644
},
prepareUpdate(node, _type, oldProps, newProps, rootNode) {
if (node.internal_static) {
-@@ -213,7 +249,7 @@ export default createReconciler({
+@@ -213,7 +247,7 @@ export default createReconciler({
},
removeChild(node, removeNode) {
removeChildNode(node, removeNode);
@@ -159,34 +223,3 @@ index 55acec7..035907a 100644
});
//# sourceMappingURL=reconciler.js.map
\ No newline at end of file
-diff --git a/node_modules/ink/build/log-update.js b/node_modules/ink/build/log-update.js
---- a/node_modules/ink/build/log-update.js
-+++ b/node_modules/ink/build/log-update.js
-@@ -13,9 +13,26 @@
- if (output === previousOutput) {
- return;
- }
-+ // Diff-render (Cosmic Stack patch): erase and rewrite only the rows
-+ // from the first changed line onward; identical rows above stay on
-+ // screen untouched. Ink 5's log-update erased and rewrote the ENTIRE
-+ // frame on every render — a prompt-selection change or spinner tick
-+ // repainted the whole live region, which read as a full-UI flash.
-+ // The row bytes are compared verbatim (layout is deterministic), and
-+ // the erase count accounts for the trailing blank line exactly like
-+ // `previousLineCount` does, so `clear()` and cursor arithmetic stay
-+ // in sync with the original accounting.
-+ const previousRows = previousOutput === '' ? [] : previousOutput.slice(0, -1).split('\n');
-+ const nextRows = output.slice(0, -1).split('\n');
-+ const common = Math.min(previousRows.length, nextRows.length);
-+ let firstChange = 0;
-+ while (firstChange < common && previousRows[firstChange] === nextRows[firstChange]) {
-+ firstChange++;
-+ }
-+ const eraseCount = previousLineCount - firstChange;
- previousOutput = output;
-- stream.write(ansiEscapes.eraseLines(previousLineCount) + output);
- previousLineCount = output.split('\n').length;
-+ stream.write(ansiEscapes.eraseLines(eraseCount) + nextRows.slice(firstChange).join('\n') + '\n');
- };
- render.clear = () => {
- stream.write(ansiEscapes.eraseLines(previousLineCount));
diff --git a/scripts/apply-ink-patch.cjs b/scripts/apply-ink-patch.cjs
index 8ca76037..f4964c9b 100644
--- a/scripts/apply-ink-patch.cjs
+++ b/scripts/apply-ink-patch.cjs
@@ -25,21 +25,60 @@ const inkDir = path.join(root, 'node_modules', 'ink', 'build');
const reconcilerPath = path.join(inkDir, 'reconciler.js');
const staticJsPath = path.join(inkDir, 'components', 'Static.js');
const staticDtsPath = path.join(inkDir, 'components', 'Static.d.ts');
+const inkJsPath = path.join(inkDir, 'ink.js');
+const logUpdatePath = path.join(inkDir, 'log-update.js');
function isPatched() {
try {
const reconciler = fs.readFileSync(reconcilerPath, 'utf8');
const staticComponent = fs.readFileSync(staticJsPath, 'utf8');
+ const inkJs = fs.readFileSync(inkJsPath, 'utf8');
+ const logUpdate = fs.readFileSync(logUpdatePath, 'utf8');
return reconciler.includes('clearYogaRefs')
&& reconciler.includes('Array.isArray(node.childNodes)')
&& reconciler.includes('rootNode.staticNode = undefined')
&& staticComponent.includes('itemKey')
- && staticComponent.includes('setCommitTick');
+ && staticComponent.includes('setCommitTick')
+ && logUpdate.includes('Diff-render (Cosmic Stack patch)')
+ && inkJs.includes(FRAME_GATE_MARKER);
} catch {
return false;
}
}
+const FRAME_GATE_MARKER = '__mercuryFrameGate';
+
+/** Diff-render log-update + freeze gate. Both live in already-patched
+ * files, so this is an idempotent string-insert on the applied state. */
+function applyInkFrameGate() {
+ let s = fs.readFileSync(inkJsPath, 'utf8');
+ if (s.includes(FRAME_GATE_MARKER)) return true;
+ const noopAnchor = "const noop = () => { };";
+ if (!s.includes(noopAnchor)) return false;
+ s = s.replace(noopAnchor, `${noopAnchor}
+// Freeze gate (Cosmic Stack patch): while frozen, onRender writes NOTHING
+// and must not advance lastOutput / log-update's baseline — the resume frame
+// must diff against the last frame actually on screen. \`armed\` lets exactly
+// one frame through (the "⏸ frozen" hint) if its output contains \`marker\`.
+// Exposed on globalThis so host code can reach it without a type-level
+// import of this internal module.
+export const frameGate = { frozen: false, armed: false, marker: '' };
+globalThis.${FRAME_GATE_MARKER} = frameGate;`);
+ const renderAnchor = " const { output, outputHeight, staticOutput } = render(this.rootNode);";
+ if (!s.includes(renderAnchor)) return false;
+ s = s.replace(renderAnchor, `${renderAnchor}
+ // 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
+ // ends the freeze diffs against what is actually on screen.
+ if (frameGate.frozen && !(frameGate.armed && frameGate.marker && output.includes(frameGate.marker))) {
+ return;
+ }
+ if (frameGate.armed) frameGate.armed = false;`);
+ fs.writeFileSync(inkJsPath, s);
+ return true;
+}
+
function applyReconcilerFix() {
let s = fs.readFileSync(reconcilerPath, 'utf8');
if (s.includes('clearYogaRefs')) return true;
@@ -217,12 +256,16 @@ function apply() {
try {
const reconcilerOk = applyReconcilerFix();
const staticOk = applyStaticFix();
+ const frameGateOk = applyInkFrameGate();
if (!reconcilerOk) {
return { ok: false, applied: true, error: 'reconciler.js no longer matches the expected ink 5.2.1 shape — patch anchors not found' };
}
if (!staticOk) {
return { ok: false, applied: true, error: 'Static.js could not be rewritten' };
}
+ if (!frameGateOk) {
+ return { ok: false, applied: true, error: 'ink.js frame gate could not be inserted' };
+ }
} catch (err) {
return { ok: false, applied: true, error: err.message };
}
diff --git a/src/channels/cli-freeze.test.ts b/src/channels/cli-freeze.test.ts
new file mode 100644
index 00000000..017d24ec
--- /dev/null
+++ b/src/channels/cli-freeze.test.ts
@@ -0,0 +1,115 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { CLIChannel } from './cli.js';
+
+/** Notifications flush via setImmediate (check phase) — same pattern as cli-rerender.test.ts. */
+const flushRenders = () => new Promise<void>((resolve) => setImmediate(resolve));
+
+/**
+ * Scroll-lock (freeze) regression guards. While frozen the TUI must write
+ * NOTHING (the user is reading/copying in native scrollback) while the
+ * agent's state keeps merging underneath — and a message finalized during
+ * the freeze must print exactly once on resume. The freeze gate lives in
+ * rerender(): state merges always, only the React notification is
+ * suppressed — <Static> never commits mid-freeze (committing without
+ * printing would lose finalized messages, since Static marks keys
+ * committed at the React level).
+ */
+describe('CLIChannel TUI freeze (scroll lock)', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ const gate = (globalThis as any).__mercuryFrameGate;
+ if (gate) { gate.frozen = false; gate.armed = false; gate.marker = ''; }
+ });
+
+ it('freezing stops frame notifications but keeps merging state', async () => {
+ vi.spyOn(process.stdout, 'write').mockImplementation((() => true) as typeof process.stdout.write);
+ const channel = new CLIChannel();
+ let notifications = 0;
+ channel.subscribeToTuiState(() => { notifications++; });
+
+ channel.setTuiFrozen(true);
+ // The hint frame is allowed through exactly once during the armed window.
+ await flushRenders();
+ const notificationsAfterHint = notifications;
+ expect(channel.getTuiState().tuiFrozen).toBe(true);
+ // The write gate closes after ink's 32ms onRender throttle (90ms timer).
+ await new Promise((resolve) => setTimeout(resolve, 120));
+
+ // Stream continues underneath: state advances, no frame goes out.
+ channel.setLiveActivity('Streaming response', 'generating answer');
+ (channel as any).update({ chatMessages: [...channel.getTuiState().chatMessages] });
+ await flushRenders();
+ await flushRenders();
+ expect(notifications).toBe(notificationsAfterHint);
+ expect(channel.getTuiState().liveActivity?.phase).toBe('Streaming response');
+ });
+
+ it('resume emits exactly one notification with the merged state', async () => {
+ vi.spyOn(process.stdout, 'write').mockImplementation((() => true) as typeof process.stdout.write);
+ const channel = new CLIChannel();
+ let notifications = 0;
+ channel.subscribeToTuiState(() => { notifications++; });
+
+ channel.setTuiFrozen(true);
+ await flushRenders();
+ await new Promise((resolve) => setTimeout(resolve, 120)); // gate fully closed
+ const afterHint = notifications;
+ (channel as any).update({ toolSteps: [{ id: 's1', label: 'read_file', status: 'done' } as any] });
+ await flushRenders();
+ expect(notifications).toBe(afterHint); // merged silently
+
+ channel.setTuiFrozen(false);
+ await flushRenders();
+ expect(notifications).toBe(afterHint + 1);
+ expect(channel.getTuiState().toolSteps).toHaveLength(1);
+ expect(channel.getTuiState().tuiFrozen).toBe(false);
+ });
+
+ it('a permission prompt arriving while frozen auto-resumes', async () => {
+ vi.spyOn(process.stdout, 'write').mockImplementation((() => true) as typeof process.stdout.write);
+ const channel = new CLIChannel();
+ channel.setTuiFrozen(true);
+ // Wait out the armed hint window (90ms) so the gate is fully closed.
+ await new Promise((resolve) => setTimeout(resolve, 120));
+ await flushRenders();
+
+ const prompt = { type: 'choice' as const, message: 'Allow?', options: [], resolve: () => {} };
+ (channel as any).update({ permissionPrompt: prompt as any });
+ await flushRenders();
+ // The gate must be open: the prompt frame went out (listener notified).
+ expect(channel.getTuiState().tuiFrozen).toBe(false);
+ expect(channel.getTuiState().permissionPrompt).toBeTruthy();
+ });
+
+ it('freeze while a stream finishes keeps the finalized message for the resume frame', async () => {
+ // Simulates stream() finalizing during a freeze: the message lands in
+ // state (streaming: false) but React never renders it — on resume, the
+ // single frame carries it and <Static> commits it exactly once.
+ vi.spyOn(process.stdout, 'write').mockImplementation((() => true) as typeof process.stdout.write);
+ const channel = new CLIChannel();
+ channel.setTuiFrozen(true);
+ await flushRenders();
+ (channel as any).update({
+ chatMessages: [...channel.getTuiState().chatMessages, { id: 'm1', role: 'agent', content: 'final text', timestamp: 1 }],
+ });
+ await flushRenders();
+ await flushRenders();
+ expect(channel.getTuiState().chatMessages.some((m) => m.id === 'm1')).toBe(true);
+
+ channel.setTuiFrozen(false);
+ await flushRenders();
+ expect(channel.getTuiState().tuiFrozen).toBe(false);
+ });
+
+ it('teardown clears the freeze state and the ink gate', async () => {
+ vi.spyOn(process.stdout, 'write').mockImplementation((() => true) as typeof process.stdout.write);
+ const channel = new CLIChannel();
+ (channel as any).inkInstance = { unmount: () => {}, rerender: () => {} };
+ (globalThis as any).__mercuryFrameGate = { frozen: true, armed: false, marker: '⏸ frozen' };
+ channel.setTuiFrozen(true);
+ await flushRenders();
+ (channel as any).teardownTui();
+ expect((globalThis as any).__mercuryFrameGate.frozen).toBe(false);
+ expect((globalThis as any).__mercuryFrameGate.marker).toBe('');
+ });
+});
\ No newline at end of file
diff --git a/src/channels/cli.ts b/src/channels/cli.ts
index 47d54c3a..dd10add9 100644
--- a/src/channels/cli.ts
+++ b/src/channels/cli.ts
@@ -220,6 +220,11 @@ export class MouseSequenceFilter {
}
}
+/** Status-bar hint shown while the TUI is frozen (Ctrl+S scroll lock). The
+ * substring '⏸ frozen' is also the ink freeze-gate marker (the armed window
+ * lets through only the frame that carries it) — keep them in sync. */
+export const TUI_FROZEN_HINT_MARKER = '⏸ frozen';
+
export interface TuiState {
mode: AppMode;
viewMode: 'balanced' | 'detailed';
@@ -256,6 +261,9 @@ export interface TuiState {
exitEscArmed: boolean;
/** Real-time activity phase (what the agent is doing right now), or null when idle. */
liveActivity: LiveActivityState | null;
+ /** TUI frame freeze (scroll lock): all frame writes stop so the user can
+ * scroll/copy freely while the chat continues underneath. Ctrl+S toggles. */
+ tuiFrozen: boolean;
}
const defaultState: TuiState = {
@@ -287,6 +295,7 @@ const defaultState: TuiState = {
mercuryCode: null,
exitEscArmed: false,
liveActivity: null,
+ tuiFrozen: false,
};
function shallowEqualSubAgents(a: SubAgentInfo[], b: SubAgentInfo[]): boolean {
@@ -363,6 +372,12 @@ export class CLIChannel extends BaseChannel {
}
private teardownTui(): void {
+ // The gate must never survive teardown: ink's final unmount writes
+ // (log.done(), cursor restore) have to reach the terminal.
+ this.writeGateFrozen = false;
+ this.frozenHintPending = false;
+ this.tuiFrozen = false;
+ this.frameGateSet({ armed: false, frozen: false, marker: '' });
const inkInstance = this.inkInstance;
this.inkInstance = null;
// Unmount may throw on a corrupted Yoga heap; shutdown must still
@@ -412,11 +427,87 @@ export class CLIChannel extends BaseChannel {
}
}
+ /** Scroll-lock (freeze) bookkeeping. `tuiFrozen` is the user-facing state;
+ * `writeGateFrozen` is the actual frame gate (opens after the hint frame);
+ * `frozenHintPending` lets the one hint frame through the gate. */
+ private tuiFrozen = false;
+ private writeGateFrozen = false;
+ private frozenHintPending = false;
+
private update(partial: Partial<TuiState>): void {
+ // Blocking interactions must never be invisible: auto-resume BEFORE the
+ // update so the frame that carries the prompt goes out — and the
+ // tuiFrozen flag must clear in the SAME state merge, otherwise the
+ // resumed frame still renders the frozen status bar.
+ if (this.writeGateFrozen && (partial.permissionPrompt || partial.mercuryCode?.exitConfirm)) {
+ this.unfreezeForInteraction();
+ partial = { ...partial, tuiFrozen: false };
+ }
this.state = { ...this.state, ...partial };
this.rerender();
}
+ /**
+ * Freeze/unfreeze the TUI frame stream (scroll lock, Ctrl+S). While frozen
+ * the agent keeps streaming — state keeps merging in this.update — but
+ * rerender() stops notifying React, so ink writes nothing and the user's
+ * terminal is untouched: they can scroll, read, and drag-select freely in
+ * native scrollback while the chat is in progress. Resume emits one fresh
+ * frame (the ink diff-render rewrites only rows that changed since the
+ * freeze frame).
+ *
+ * Freezing shows the status hint FIRST (one frame), then closes the write
+ * gate after ink's 32ms onRender throttle has had its chance — so the user
+ * always sees what happened. Auto-resume on permission prompts / exit
+ * confirms: they own the keyboard and must never be invisible.
+ */
+ setTuiFrozen(frozen: boolean): void {
+ if (frozen === this.tuiFrozen) return;
+ this.tuiFrozen = frozen;
+ if (frozen) {
+ this.frozenHintPending = true;
+ // Pass 1: write the hint frame (gate still open, hint marker armed).
+ this.frameGateSet({ armed: true, frozen: false, marker: TUI_FROZEN_HINT_MARKER });
+ this.update({ tuiFrozen: true });
+ // ink's onRender is throttled to 32ms; 90ms safely covers the flush.
+ const timer = setTimeout(() => {
+ this.frozenHintPending = false;
+ this.writeGateFrozen = true;
+ this.frameGateSet({ armed: false, frozen: true, marker: '' });
+ }, 90);
+ timer.unref?.();
+ } else {
+ this.writeGateFrozen = false;
+ this.frozenHintPending = false;
+ this.frameGateSet({ armed: false, frozen: false, marker: '' });
+ this.update({ tuiFrozen: false });
+ }
+ }
+
+ /** The ink patch's freeze gate (undefined when ink is unpatched — e.g. a
+ * dev checkout where the patch applier hasn't run). */
+ private get frameGate(): { frozen: boolean; armed: boolean; marker: string } | undefined {
+ return (globalThis as any).__mercuryFrameGate;
+ }
+
+ private frameGateSet(gate: { frozen: boolean; armed: boolean; marker: string }): void {
+ const g = this.frameGate;
+ if (g) Object.assign(g, gate);
+ }
+
+ /** Resume rendering: a blocking interaction (prompt/confirm) or explicit
+ * unfreeze arrived. Opens the write gate before the state update so the
+ * frame that carries the interaction is not dropped. Called from inside
+ * update() — the partial itself must carry tuiFrozen: false so the frame
+ * renders the resumed state. */
+ private unfreezeForInteraction(): void {
+ if (!this.tuiFrozen && !this.writeGateFrozen) return;
+ this.writeGateFrozen = false;
+ this.frozenHintPending = false;
+ this.tuiFrozen = false;
+ this.frameGateSet({ armed: false, frozen: false, marker: '' });
+ }
+
/** useSyncExternalStore contract: read the latest immutable state snapshot. */
getTuiStateSnapshot = (): TuiState => {
return this.state;
@@ -440,6 +531,13 @@ export class CLIChannel extends BaseChannel {
}
private rerender(): void {
+ // Freeze gate: state has already merged (this.update) — only the frame
+ // is suppressed. React never re-renders while frozen, so <Static> never
+ // commits new items (committing without printing would lose finalized
+ // messages — Static marks keys committed at the React level). The one
+ // exception is the armed hint window: the freeze hint frame must go out
+ // so the user sees the frozen state.
+ if (this.writeGateFrozen && !this.frozenHintPending) return;
// Notify React subscribers instead of calling inkInstance.rerender().
// Imperative re-rendering enters the reconciler synchronously from
// arbitrary call sites and races React's own renders (spinner/size
@@ -530,6 +628,10 @@ export class CLIChannel extends BaseChannel {
return;
}
if (sub === 'live') { this.scrollMercuryCodeToLive(); return; }
+ // Scroll lock (freeze): stop all frame writes so the user can scroll
+ // and copy freely in native scrollback while the chat streams on.
+ if (sub === 'freeze' || sub === 'resume' || sub === 'unfreeze') { this.setTuiFrozen(sub === 'freeze'); return; }
+ if (sub === 'freeze-toggle') { this.setTuiFrozen(!this.state.tuiFrozen); return; }
if (sub === 'esc-arm') {
this.exitEscArmed = true;
// Auto-disarm after 1.5s so Esc-Esc window is bounded.
diff --git a/src/core/agent-memory-bounds.test.ts b/src/core/agent-memory-bounds.test.ts
index f2ab22ff..866bb2e8 100644
--- a/src/core/agent-memory-bounds.test.ts
+++ b/src/core/agent-memory-bounds.test.ts
@@ -54,7 +54,10 @@ describe('agent memory bounds', () => {
it('bounds Ink Static output and the streaming-tail projection', () => {
const app = src('../ui/App.tsx');
expect(app).toContain('MAX_STATIC_MESSAGES = 100');
- expect(app).toContain('STREAM_TAIL_CHARS = 8 * 1024');
+ // The tail budget is still bounded (32KB slice through the markdown
+ // pipeline, hard 48-row ceiling) — "full preview" never means O(buffer).
+ expect(app).toContain('STREAM_TAIL_CHARS = 32 * 1024');
+ expect(app).toContain('STREAM_TAIL_MAX_LINES = 48');
expect(app).toContain('!m.streaming &&');
const channel = src('../channels/cli.ts');
// Render notifications must leave the timer phase runnable (no microtask
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index d3bf2f28..8c92b175 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -1,6 +1,7 @@
import React, { useSyncExternalStore } from 'react';
import { Box, Text, Spacer, Static, useApp, useInput, useStdout } from 'ink';
import type { TuiState } from '../channels/cli.js';
+import { TUI_FROZEN_HINT_MARKER } from '../channels/cli.js';
import type { AppMode, ChatMessage, ToolStep, SubAgentInfo, PermissionPromptState, SidebarSection, BackgroundTaskInfo, WorkspaceState, LiveActivityState, PlanStep } from './types.js';
import type { PermissionMode } from '../channels/base.js';
import type { ProgrammingModeState } from '../core/programming-mode.js';
@@ -420,6 +421,11 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
if (key.ctrl && (ch === 'd' || ch === 'D')) { onInput('/mc exit-force'); return; }
+ // Scroll lock (freeze): stop all frame writes so the user can scroll,
+ // read, and copy in native scrollback while a response streams. The
+ // chat continues underneath; Ctrl+S again resumes.
+ if (key.ctrl && (ch === 's' || ch === 'S' || ch === '\x13')) { onInput('/mc freeze-toggle'); return; }
+
// Ctrl+P / Ctrl+X plan/execute shortcuts
if (key.ctrl && (ch === 'p' || ch === 'P')) { onInput('/code plan'); return; }
if (key.ctrl && (ch === 'x' || ch === 'X')) { onInput('/code execute'); return; }
@@ -969,6 +975,7 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
<MercuryCodeView
state={state}
cols={terminalSize.cols}
+ rows={terminalSize.rows}
input={input}
cursorPos={cursorPos}
permIdx={permIdx}
@@ -1972,7 +1979,7 @@ function ToolStepsView({ steps, viewMode, idle }: { steps: ToolStep[]; viewMode:
);
}
-function ThinkingIndicator({ agentName, steps, mode, liveActivity, thinkingPreview }: { agentName: string; steps: ToolStep[]; mode: AppMode; liveActivity?: LiveActivityState | null; thinkingPreview?: string | null }) {
+function ThinkingIndicator({ agentName, steps, mode, liveActivity, thinkingPreview, frozen }: { agentName: string; steps: ToolStep[]; mode: AppMode; liveActivity?: LiveActivityState | null; thinkingPreview?: string | null; frozen?: boolean }) {
const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
const [frame, setFrame] = React.useState(0);
const [elapsed, setElapsed] = React.useState(0);
@@ -1980,12 +1987,14 @@ function ThinkingIndicator({ agentName, steps, mode, liveActivity, thinkingPrevi
React.useEffect(() => {
startRef.current = Date.now();
+ // Scroll lock: the self-ticker must not repaint while frames are frozen.
+ if (frozen) return;
const timer = setInterval(() => {
setFrame((v) => (v + 1) % frames.length);
setElapsed(Math.floor((Date.now() - startRef.current) / 1000));
}, 80);
return () => clearInterval(timer);
- }, []);
+ }, [frozen]);
const spinner = frames[frame % frames.length];
const runningStep = [...steps].reverse().find((s) => s.status === 'running');
@@ -2212,6 +2221,7 @@ const CODE_HINTS: Array<[string, string, string]> = [
['/code execute', 'approve & implement the plan', 'ctrl+x'],
['/init', 'scan repo & write AGENTS.md', ''],
['/code diff', 'show working-tree diff', 'ctrl+g'],
+ ['/code freeze', 'freeze frames to scroll/copy freely', 'ctrl+s'],
['/code chat', 'switch back to regular chat', 'esc esc'],
['/code exit', 'leave Mercury Code (confirm)', 'ctrl+d'],
];
@@ -2260,11 +2270,27 @@ function PlanProgressView({ steps }: { steps: PlanStep[] }): React.ReactNode {
}
/** Live streaming tail budget: chars of the stream buffer rendered per frame. */
-const STREAM_TAIL_CHARS = 8 * 1024;
-/** Live streaming tail budget: max wrapped rows rendered per frame. The live
- * region must stay well under one screen so each frame's rewrite is small —
- * a full-screen live region was repainted every streaming frame (flicker). */
-const STREAM_TAIL_MAX_LINES = 12;
+const STREAM_TAIL_CHARS = 32 * 1024;
+const STREAM_TAIL_MIN_LINES = 6;
+/** Absolute ceiling on live tail rows: bounds per-frame markdown + highlight
+ * work regardless of terminal height. */
+const STREAM_TAIL_MAX_LINES = 48;
+/** Live-region chrome below the tail block: input box (2 borders + lines),
+ * status bar, live-feedback block (≤5), plan checklist (≤6), prompts. Kept in
+ * sync with MercuryCodeView's render tree. */
+const MERCURY_CODE_LIVE_CHROME_ROWS = 14;
+
+/**
+ * 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.
+ */
+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));
+}
/**
* Vibrant Mercury palette for the wordmark. Background-adaptive: on a dark
@@ -2318,6 +2344,9 @@ function MercuryLiveFeedback({ state }: { state: TuiState }): React.ReactNode {
const active = Boolean(running || state.isThinking || doneRecently.length > 0 || activeAgents.length > 0 || activity);
React.useEffect(() => {
if (!active || state.mode !== 'mercury-code') return;
+ // Scroll lock: the self-ticker must not repaint while the TUI is frozen
+ // (each tick commits a frame — frame writes are what freezing stops).
+ if (state.tuiFrozen) return;
// 100ms tick: smooth spinner AND a live seconds counter. The old 250ms
// tick with no elapsed read as frozen during long tool calls.
const t = setInterval(() => {
@@ -2325,7 +2354,7 @@ function MercuryLiveFeedback({ state }: { state: TuiState }): React.ReactNode {
forceTick((v) => v + 1);
}, 100);
return () => clearInterval(t);
- }, [active, state.mode]);
+ }, [active, state.mode, state.tuiFrozen]);
if (state.mode !== 'mercury-code') return null;
if (!active) return null;
@@ -2538,12 +2567,14 @@ function MercuryMessageBlock({ message, width }: { message: ChatMessage; width:
export function MercuryCodeView({
state,
cols,
+ rows = 24,
input,
cursorPos,
permIdx,
}: {
state: TuiState;
cols: number;
+ rows?: number;
input?: string | undefined;
cursorPos?: number | undefined;
permIdx?: number | undefined;
@@ -2565,10 +2596,42 @@ export function MercuryCodeView({
// finalized messages, but on the bounded TAIL SLICE (fence-aligned with the
// full buffer) so per-frame work stays O(tail) — headers, bullets, and
// syntax-highlighted code render live instead of appearing only at the end.
- const streamTail = React.useMemo(
- () => streamingMessage ? buildStreamTailLines(streamingMessage, contentWidth, STREAM_TAIL_CHARS, STREAM_TAIL_MAX_LINES) : [] as MercuryTranscriptLine[],
- [streamingMessage, contentWidth],
- );
+ // Recompute is throttled to ~120ms: the markdown/highlight pipeline is
+ // O(tail) and the diff-render only rewrites changed rows, so a slightly
+ // stale tail for one throttle window is imperceptible, while re-parsing
+ // the full slice on every 60ms chunk was measurable CPU on long streams.
+ // The block is PADDED to the row cap (spacer rows below the text) so the
+ // live region's height is constant for the whole stream — ink's erase
+ // arithmetic (log-update) never changes the region's line count, which is
+ // what made the user's scroll position churn ("takes me back") while a
+ // response streamed. Released when the message finalizes into <Static>.
+ const tailRef = React.useRef<null | { id: string; at: number; contentLength: number; lines: MercuryTranscriptLine[] }>(null);
+ const tailCap = streamTailRowCap(rows);
+ const streamTail = React.useMemo(() => {
+ if (!streamingMessage) {
+ tailRef.current = null;
+ return [] as MercuryTranscriptLine[];
+ }
+ const now = Date.now();
+ const cache = tailRef.current;
+ if (cache && cache.id === streamingMessage.id && now - cache.at < 120 && cache.contentLength <= streamingMessage.content.length) {
+ return cache.lines;
+ }
+ const lines = buildStreamTailLines(streamingMessage, contentWidth, STREAM_TAIL_CHARS, tailCap);
+ tailRef.current = { id: streamingMessage.id, at: now, contentLength: streamingMessage.content.length, lines };
+ return lines;
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- tailCap derives from rows; cache ref holds state
+ }, [streamingMessage, contentWidth, tailCap]);
+ const paddedStreamTail = React.useMemo(() => {
+ if (streamTail.length === 0) return streamTail;
+ const pad = tailCap - streamTail.length;
+ if (pad <= 0) return streamTail;
+ return [
+ ...streamTail,
+ ...Array.from({ length: pad }, (_, i): MercuryTranscriptLine => ({ key: `tail:pad:${i}`, kind: 'spacer' as const, role: 'system' as const, text: '' })),
+ ];
+ }, [streamTail, tailCap]);
+ const streamTailRows = paddedStreamTail;
if (!mc) {
return (
@@ -2614,7 +2677,11 @@ export function MercuryCodeView({
const removed = rightSegs.pop()!;
segWidth -= removed.text.length + SEP.length;
}
- const leftHint = mc.exitConfirm || state.permissionPrompt
+ // Freeze hint lives in the status bar (not a new row) so the live region's
+ // height stays constant — a new row would re-introduce scrollback churn.
+ const leftHint = state.tuiFrozen
+ ? `${TUI_FROZEN_HINT_MARKER} — Ctrl+S to resume · /mc resume`
+ : mc.exitConfirm || state.permissionPrompt
? '' // the prompt / confirm box already shows its own controls
: state.isThinking || state.toolSteps.some((s) => s.status === 'running') || state.subAgents.some((a) => a.status === 'running')
? '' // the live feedback block above is showing progress
@@ -2629,9 +2696,9 @@ export function MercuryCodeView({
? <MercuryBrandBlock key={item} brandLines={brandLines} />
: <MercuryMessageBlock key={item.id} message={item} width={contentWidth} />}
</Static>
- {streamTail.length > 0 && (
+ {streamTailRows.length > 0 && (
<Box flexDirection="column" flexShrink={0}>
- {streamTail.map((line) => <MercuryTranscriptRow key={line.key} line={line} />)}
+ {streamTailRows.map((line) => <MercuryTranscriptRow key={line.key} line={line} />)}
</Box>
)}
{showHints && <MercuryCodeHints cols={cols} />}
diff --git a/src/ui/freeze-frame.test.tsx b/src/ui/freeze-frame.test.tsx
new file mode 100644
index 00000000..39f4dcdd
--- /dev/null
+++ b/src/ui/freeze-frame.test.tsx
@@ -0,0 +1,185 @@
+import { describe, expect, it, vi } from 'vitest';
+
+// These tests assert on the frames ink writes to a fake stdout. Ink skips
+// ALL frame writes when it detects CI (`is-in-ci` → process.env.CI), which
+// GitHub Actions sets. 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, Text, Box } from 'ink';
+import { EventEmitter } from 'node:events';
+import { MercuryCodeView } from './App.js';
+import type { TuiState } from '../channels/cli.js';
+
+type FrameGate = { frozen: boolean; armed: boolean; marker: string };
+
+const getGate = (): FrameGate | undefined => (globalThis as any).__mercuryFrameGate;
+
+class FakeStdout extends EventEmitter {
+ chunks: string[] = [];
+ columns = 80;
+ rows = 30;
+ isTTY = true;
+ write(chunk: string): boolean {
+ this.chunks.push(chunk);
+ return true;
+ }
+ get output(): string {
+ return this.chunks.join('');
+ }
+ get bytesSince(): (t: number) => number {
+ return (t: number) => this.chunks.length - t;
+ }
+}
+
+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));
+
+/**
+ * Scroll-lock (freeze) frame-level regression guards, against the REAL
+ * patched ink. The ink patch's freeze gate must guarantee ZERO stdout bytes
+ * while frozen — and crucially must NOT advance log-update's baseline
+ * (previousOutput/previousLineCount), so the resume frame diffs against the
+ * freeze frame instead of erasing the wrong rows.
+ */
+describe('ink freeze gate (scroll lock)', () => {
+ it('writes zero bytes while frozen and one clean frame on resume', async () => {
+ if (!getGate()) {
+ throw new Error('ink frame gate missing — the ink patch is not applied');
+ }
+ const stdout = new FakeStdout() as any;
+ const gate = getGate()!;
+
+ const { rerender, unmount } = render(
+ React.createElement(Box, null, React.createElement(Text, null, 'frame A')),
+ { stdout, exitOnCtrlC: false, patchConsole: false },
+ );
+ await sleep(120);
+ const baseline = stdout.output;
+ expect(baseline).toContain('frame A');
+
+ gate.frozen = true;
+ gate.armed = false;
+ gate.marker = '';
+
+ // Several re-renders while frozen: NOT ONE byte may reach the terminal.
+ rerender(React.createElement(Box, null, React.createElement(Text, null, 'frame B')));
+ rerender(React.createElement(Box, null, React.createElement(Text, null, 'frame C')));
+ await sleep(150);
+ expect(stdout.output).toBe(baseline); // zero bytes while frozen
+
+ // Resume: the frame goes out and diffs against the freeze frame.
+ gate.frozen = false;
+ rerender(React.createElement(Box, null, React.createElement(Text, null, 'frame C')));
+ await sleep(120);
+ expect(stdout.output).toContain('frame C');
+ unmount();
+ }, 10_000);
+
+ it('the armed window lets exactly the marker frame through', async () => {
+ if (!getGate()) {
+ throw new Error('ink frame gate missing — the ink patch is not applied');
+ }
+ const stdout = new FakeStdout() as any;
+ const gate = getGate()!;
+ gate.frozen = true;
+ gate.armed = true;
+ gate.marker = '⏸ frozen';
+
+ const { rerender, unmount } = render(
+ React.createElement(Box, null, React.createElement(Text, null, 'base')),
+ { stdout, exitOnCtrlC: false, patchConsole: false },
+ );
+ await sleep(80);
+ // Once the marker frame arrives, armed clears; later plain frames drop.
+ rerender(React.createElement(Box, null, React.createElement(Text, null, 'base with ⏸ frozen hint')));
+ await sleep(150);
+ expect(stdout.output).toContain('⏸ frozen');
+ const writesAfterHint = stdout.output.length;
+ rerender(React.createElement(Box, null, React.createElement(Text, null, 'suppressed')));
+ await sleep(100);
+ expect(stdout.output.length).toBe(writesAfterHint); // armed window consumed
+
+ gate.frozen = false;
+ gate.armed = false;
+ gate.marker = '';
+ unmount();
+ }, 10_000);
+});
+
+/**
+ * Part A: full streaming preview + height-stable live region. The tail block
+ * renders the streaming message up to a row cap derived from the terminal
+ * height (the old 12-row cap hid the last block; a cap >= terminal rows
+ * would make ink clear the whole terminal every frame) and is PADDED to the
+ * cap with spacer rows so the live region's height never churns mid-stream.
+ */
+describe('Mercury Code streaming tail: full preview + padded height', () => {
+ it('renders the tail to the row cap and pads it to a constant height', () => {
+ const longContent = Array.from({ length: 200 }, (_, i) => `Line ${i}: some streaming content here`).join('\n');
+ const state = {
+ mode: 'mercury-code',
+ version: '1.2.5',
+ agentName: 'Mercury',
+ programmingMode: 'auto',
+ projectContext: '/tmp/proj',
+ permissionMode: 'allow-all',
+ chatMessages: [
+ { id: 'u1', role: 'user', content: 'explain git branching', timestamp: 1 },
+ { id: 'a1', role: 'agent', content: longContent, timestamp: 2, streaming: true },
+ ],
+ toolSteps: [],
+ subAgents: [],
+ sidebarSections: [],
+ backgroundTasks: [],
+ skills: [],
+ mercuryCode: {
+ cwd: '/tmp/proj', dirName: 'proj', git: { branch: 'main', ahead: 0, behind: 0, dirty: 0 },
+ scrollOffset: 0, exitConfirm: false,
+ },
+ tuiFrozen: false,
+ isThinking: false,
+ } as unknown as TuiState;
+
+ const stdout = new FakeStdout() as any;
+ const { unmount, rerender } = render(
+ React.createElement(MercuryCodeView, { state, cols: 100, rows: 45 }),
+ { stdout, exitOnCtrlC: false, patchConsole: false },
+ );
+ void rerender;
+ const cap = Math.max(6, Math.min(48, 45 - 14)); // 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.
+ const stripped = stdout.output.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '');
+ const contentRows = stripped.split('\n').filter((l: string) => l.includes('some streaming content'));
+ const uniqueRows = new Set(contentRows.map((r: string) => r.trim()));
+ expect(uniqueRows.size).toBeGreaterThan(12); // far beyond the old 12-row cap
+ expect(uniqueRows.size).toBeLessThanOrEqual(cap);
+ unmount();
+ }, 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);
+ expect(cap(120)).toBe(48);
+ expect(cap(10)).toBe(6); // tiny terminal: floor, never negative
+ });
+});
\ No newline at end of file
diff --git a/src/ui/mercury-transcript.ts b/src/ui/mercury-transcript.ts
index 1fa38a76..f31b4190 100644
--- a/src/ui/mercury-transcript.ts
+++ b/src/ui/mercury-transcript.ts
@@ -95,8 +95,8 @@ export const CODE_BLOCK_VISIBLE_ROWS = 40;
export function buildStreamTailLines(
message: ChatMessage,
width: number,
- tailChars = 8 * 1024,
- maxLines = 12,
+ tailChars = 32 * 1024,
+ maxLines = 48,
): MercuryTranscriptLine[] {
const content = message.content;
if (content.length === 0) return [];
@@ -108,11 +108,14 @@ export function buildStreamTailLines(
if (start === 0 && rawStart > 0) start = rawStart; // no newline (single-line buffer)
if (insideFence) {
// Back up to the last fence opener at or before the raw start so the
- // slice contains the complete block. lastIndexOf scans only the boundary
- // neighborhood; the slice may exceed tailChars for a very long block, and
- // the row cap below (plus code-block collapse) bounds the render cost.
- const opener = content.lastIndexOf('```', Math.max(0, start - 1));
- if (opener >= 0 && opener < start) start = opener;
+ // slice contains the complete block. The scan is WINDOWED (bounded to
+ // the tail budget before the slice start): scanning the whole head with
+ // String.lastIndexOf ran O(head) per recompute on every throttle window.
+ // An opener older than the window is beyond the tail budget anyway —
+ // its block's visible rows are capped out by the row cap below.
+ const windowStart = Math.max(0, start - tailChars);
+ const opener = content.slice(windowStart, start).lastIndexOf('```');
+ if (opener >= 0) start = windowStart + opener;
}
const tailMessage: ChatMessage = { ...message, content: content.slice(start) };
const lines = buildMercuryMessageLines(tailMessage, width);
diff --git a/src/ui/stream-tail.test.ts b/src/ui/stream-tail.test.ts
index 8ba13d0b..281f1883 100644
--- a/src/ui/stream-tail.test.ts
+++ b/src/ui/stream-tail.test.ts
@@ -16,8 +16,8 @@ const src = (p: string) => readFileSync(join(dirname(fileURLToPath(import.meta.u
* 2.5GB OOM.
*/
describe('streaming tail projection bounds', () => {
- const STREAM_TAIL_CHARS = 8 * 1024;
- const STREAM_TAIL_MAX_LINES = 12;
+ const STREAM_TAIL_CHARS = 32 * 1024;
+ const STREAM_TAIL_MAX_LINES = 48;
const WIDTH = 80;
function projectTail(content: string): MercuryTranscriptLine[] {
@@ -93,6 +93,32 @@ describe('streaming tail projection bounds', () => {
expect(kinds).not.toContain('text');
});
+ it('recompute cost is bounded on a full 32KB code-heavy buffer', () => {
+ // The diff-render makes frame WRITES cheap, but the tail recompute (slice
+ // + markdown + highlight) must stay in a few milliseconds — a heavier
+ // recompute per throttle window starves the stream pump.
+ const codeBlock = '```ts\n' + ('const value = 1; // comment here\n').repeat(30) + '```\n\nprose line of explanation here\n\n';
+ let content = '# Long tutorial\n\nintro prose\n\n';
+ while (content.length < 32 * 1024) content += codeBlock;
+ const message: ChatMessage = { id: 'live_2', role: 'agent', content, timestamp: 1, streaming: true };
+ const t0 = performance.now();
+ const lines = buildStreamTailLines(message, WIDTH, STREAM_TAIL_CHARS, STREAM_TAIL_MAX_LINES);
+ const elapsed = performance.now() - t0;
+ expect(lines.length).toBeLessThanOrEqual(STREAM_TAIL_MAX_LINES);
+ // Generous ceiling (CI runners are slow): the real machine measured ~1-3ms.
+ expect(elapsed).toBeLessThan(30);
+ });
+
+ it('windowed fence back-up finds the opener within the bounded neighborhood', () => {
+ // The raw window opens INSIDE an unclosed block whose opener sits >4KB
+ // back (but within the tail budget) → the windowed scan must still align
+ // to it so the block renders as CODE, never as broken prose.
+ const content = 'f\n'.repeat(15000) + '```ts\n' + 'const a = 1;\n'.repeat(4600) + 'tail prose line\n';
+ const projected = projectTail(content);
+ const kinds = projected.map((l) => l.kind);
+ expect(kinds).toContain('code');
+ });
+
it('never starts the slice mid-line', () => {
const longLine = 'word '.repeat(2000); // > 8KB, single line
const content = longLine + '\nheader text\n\nmore prose';
@@ -107,14 +133,18 @@ describe('streaming tail projection bounds', () => {
});
describe('streaming tail live-region integration', () => {
- it('Mercury Code prints finalized rows via <Static>; the tail is a small live region', () => {
+ it('Mercury Code prints finalized rows via <Static>; the tail is a height-derived live region', () => {
const app = src('App.tsx');
// Finalized transcript prints once into native terminal scrollback.
expect(app).toContain('<Static items={staticItems} itemKey={staticItemKey}>');
- // The live tail is capped to a small per-frame budget (no full-screen
- // live region — a near-full-screen region was rewritten every streaming
- // frame, which read as flicker).
- expect(app).toContain('STREAM_TAIL_MAX_LINES = 12');
+ // The tail cap derives from the terminal height (ink clears the whole
+ // terminal and rewrites the static transcript whenever the live region's
+ // height reaches `rows`) and is PADDED to a constant height so the live
+ // region never churns scrollback mid-stream.
+ expect(app).toContain('const STREAM_TAIL_MAX_LINES = 48');
+ expect(app).toContain('export function streamTailRowCap(terminalRows: number)');
+ expect(app).toContain('const tailCap = streamTailRowCap(rows)');
+ expect(app).toContain("kind: 'spacer' as const, role: 'system' as const, text: ''");
// Live tail renders through the markdown pipeline, on the bounded slice.
expect(app).toContain('buildStreamTailLines(streamingMessage, contentWidth');
// Forbidden patterns: the removed in-app viewport machinery.