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.

restore: bring back the Release/1.23 work dropped by the 40f5aea merge

Salman Qureshi97c0ee2ed4d5
diff --git a/patches/ink+5.2.1.patch b/patches/ink+5.2.1.patch
index 5f88a7ce..3377fcf4 100644
--- a/patches/ink+5.2.1.patch
+++ b/patches/ink+5.2.1.patch
@@ -159,3 +159,34 @@ 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/src/channels/cli-rerender.test.ts b/src/channels/cli-rerender.test.ts
index 3e1c2f33..608fe78d 100644
--- a/src/channels/cli-rerender.test.ts
+++ b/src/channels/cli-rerender.test.ts
@@ -106,7 +106,7 @@ describe('Mercury Code terminal modes', () => {
vi.restoreAllMocks();
});
- it('enables mouse wheel scrolling in Mercury Code and disables it on exit', () => {
+ it('keeps mouse reporting OFF in Mercury Code (native scrollback: wheel scrolls, drag selects)', () => {
const writes: string[] = [];
vi.spyOn(process.stdout, 'write').mockImplementation(((chunk: string | Uint8Array) => {
writes.push(String(chunk));
@@ -116,16 +116,14 @@ describe('Mercury Code terminal modes', () => {
const channel = new CLIChannel();
const result = channel.enterMercuryCode(process.cwd(), 'test');
- // Wheel scroll is the only natural way back through a full-screen
- // transcript — mouse reporting must be ON while Mercury Code is active.
+ // The transcript prints into the terminal's native scrollback, so the
+ // terminal itself handles wheel scrolling and drag selection. Mouse
+ // reporting must stay OFF — it would capture wheel/drag events and
+ // break both.
expect(result.ok).toBe(true);
- expect(channel.isMouseEnabled()).toBe(true);
- expect(channel.getTuiState().mercuryCode?.mouse).toBe(true);
- expect(writes.join('')).toContain('\x1b[?1006h');
-
- channel.exitMercuryCode();
expect(channel.isMouseEnabled()).toBe(false);
- expect(writes.join('')).toContain('\x1b[?1006l');
+ expect(channel.getTuiState().mercuryCode?.mouse).toBe(false);
+ expect(writes.join('')).not.toContain('\x1b[?1006h');
});
it('adds per-file git statistics to execute-mode completion', () => {
diff --git a/src/channels/cli.ts b/src/channels/cli.ts
index 234b3b72..828de575 100644
--- a/src/channels/cli.ts
+++ b/src/channels/cli.ts
@@ -1424,9 +1424,10 @@ export class CLIChannel extends BaseChannel {
/**
* Enter Mercury Code: full-screen coding TUI bound to `dir`.
- * Switches to plan mode by default (analyze-first). Transcript scrolling
- * stays keyboard-only: terminal mouse reporting survives native process
- * aborts and leaves the user's shell receiving raw mouse escape sequences.
+ * Switches to plan mode by default (analyze-first). The transcript prints
+ * into the terminal's native scrollback (<Static>), so scrolling and
+ * drag-selection are terminal-native: mouse reporting stays OFF — it would
+ * capture wheel/drag events and break both.
*/
enterMercuryCode(dir: string, version: string): { ok: boolean; message: string } {
const target = path.resolve(dir.replace(/^~(?=$|\/)/, process.env.HOME || '~'));
@@ -1452,14 +1453,6 @@ export class CLIChannel extends BaseChannel {
programmingMode: 'auto',
exitEscArmed: false,
});
- // Reset stale mouse state, then enable mouse reporting for THIS
- // Mercury Code session: wheel scroll drives the transcript scrollback
- // (full-screen frames keep history OUT of terminal scrollback — the
- // wheel is the only natural way back up).
- this.setMouseEnabled(true, (ev) => {
- if (ev.wheel === 'up') this.scrollMercuryCode(3);
- else if (ev.wheel === 'down') this.scrollMercuryCode(-3);
- });
try {
process.stdout.write('\x1b[2J\x1b[H');
} catch { /* ignore */ }
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 6f53a19c..56765304 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -77,7 +77,7 @@ import { updateCliProviderStatus } from './provider-status.js';
import { isTaskHeapUnsafe, taskHeapAbortThreshold, taskHeapExitThreshold } from './memory-guard.js';
import { compactConversation, memoryGovernorThresholds, memoryGovernorVerdict } from './memory-governor.js';
import { classifyStreamCompletion, isLengthTruncation, truncationContinuationPrompt, toolTruncationContinuationPrompt } from './stream-completion.js';
-import { MAX_EXECUTE_CONTINUATIONS, MAX_VERIFICATION_CONTINUATIONS, executeContinuationPrompt, shouldForceExecuteContinuation, isFailedToolResult, shouldRequireVerification, verificationPrompt, responseAsksUser, EXECUTE_MUTATING_TOOLS, VERIFICATION_COMMAND_PATTERN, wakeUpPrompt } from './execute-guard.js';
+import { MAX_EXECUTE_CONTINUATIONS, MAX_VERIFICATION_CONTINUATIONS, executeContinuationPrompt, shouldForceExecuteContinuation, isFailedToolResult, shouldRequireVerification, verificationPrompt, responseAsksUser, isTextDeliverableRequest, EXECUTE_MUTATING_TOOLS, VERIFICATION_COMMAND_PATTERN, wakeUpPrompt } from './execute-guard.js';
import { classifyTurnEnd, stepsExhaustedPrompt, STEPS_PAUSED_BANNER, WORK_NOT_STARTED_BANNER, type LoopEndCause } from './completion-verdict.js';
import { StallWatchdog } from './stall-watchdog.js';
import { buildFileChangePreview } from '../utils/file-preview.js';
@@ -3149,14 +3149,22 @@ export class Agent {
this.markProgress('Finalizing response...');
this.pushLiveActivity('Finalizing response');
- // ── Execute-mode completion guard ──
+ // ── Delivery completion guard ──
// In Mercury Code execute mode, a narration-only turn ("Building X per
// its spec. Reading it first.") with zero mutating tool calls must NOT
- // be celebrated as "Task complete". Force a bounded number of
- // continuation rounds that push the model to actually use its tools.
+ // be celebrated as "Task complete". The same contract holds in plain
+ // chat on every channel: an implementation-style request must actually
+ // run its tools — narration is not delivery, and the task does not
+ // end without having done anything. Conservative gating: questions,
+ // chit-chat, and text deliverables (poems, emails — the reply itself
+ // is the work) are excluded, so only repo/code-shaped requests are
+ // forced through their tools.
while (
- this.programmingMode.isExecute()
- && !loopAbortController.signal.aborted
+ !loopAbortController.signal.aborted
+ && (this.programmingMode.isExecute()
+ || (this.programmingMode.getState() === 'off'
+ && msg.channelType !== 'internal'
+ && !isTextDeliverableRequest(msg.content)))
&& executeGuardRounds < (narrationSecondWind ? MAX_EXECUTE_CONTINUATIONS * 2 : MAX_EXECUTE_CONTINUATIONS)
// A turn that ends by asking the user something in plain text is a
// legitimate pause — forcing rounds here looped the model forever
@@ -3433,10 +3441,13 @@ export class Agent {
// ── Verification gate ──
// Implementation work happened, but nothing objectively verified it
// (no build/test/typecheck ran). Force one bounded evidence round.
+ // Same contract in plain chat: a change that landed but was never
+ // verified is not a delivered change.
if (
!loopAbortController.signal.aborted
&& turnEnd() === 'text-stop'
- && this.programmingMode.isExecute()
+ && (this.programmingMode.isExecute()
+ || (this.programmingMode.getState() === 'off' && msg.channelType !== 'internal'))
&& verificationContinuations < MAX_VERIFICATION_CONTINUATIONS
&& shouldRequireVerification({
taskText: msg.content,
diff --git a/src/core/execute-guard.test.ts b/src/core/execute-guard.test.ts
index 0bdeb906..abcac510 100644
--- a/src/core/execute-guard.test.ts
+++ b/src/core/execute-guard.test.ts
@@ -4,6 +4,7 @@ import {
MAX_VERIFICATION_CONTINUATIONS,
executeContinuationPrompt,
isFailedToolResult,
+ isTextDeliverableRequest,
responseAsksUser,
shouldForceExecuteContinuation,
shouldRequireVerification,
@@ -13,6 +14,46 @@ import {
const ok = (names: string[]): Map<string, boolean> => new Map(names.map((n) => [n, true]));
+describe('chat delivery contract', () => {
+ it('text deliverables are exempt — the reply itself is the work', () => {
+ for (const text of [
+ 'write a poem about the sea',
+ 'draft an email to the landlord',
+ 'give me a catchy slogan for the app',
+ 'write a short story about a fox',
+ 'write the lyrics for a chorus',
+ 'write a haiku about autumn',
+ 'brainstorm names for the project',
+ 'write a blog post intro',
+ ]) {
+ expect(isTextDeliverableRequest(text), text).toBe(true);
+ }
+ });
+
+ it('repo/code-shaped requests are NOT text deliverables — the guard applies in chat', () => {
+ for (const text of [
+ 'fix the login bug',
+ 'build a dashboard for the API',
+ 'add tests to the auth module',
+ 'refactor the session store',
+ 'create a component for the settings page',
+ 'implement the endpoint',
+ 'set up the database schema',
+ ]) {
+ expect(isTextDeliverableRequest(text), text).toBe(false);
+ }
+ });
+
+ it('the narration guard still fires for chat implementation requests with no tools', () => {
+ expect(shouldForceExecuteContinuation({
+ taskText: 'fix the login bug',
+ hasApprovedPlan: false,
+ toolsUsed: [],
+ toolsSucceeded: new Map(),
+ })).toBe(true);
+ });
+});
+
describe('execute-mode completion guard', () => {
it('forces continuation when an implementation request ended with no tools', () => {
expect(shouldForceExecuteContinuation({
diff --git a/src/core/execute-guard.ts b/src/core/execute-guard.ts
index f2e5c7b1..7dbfaeca 100644
--- a/src/core/execute-guard.ts
+++ b/src/core/execute-guard.ts
@@ -80,6 +80,20 @@ const PURE_CONVERSATION_PATTERN = /^(thanks|thank you|thx|ty|cool|nice|great|awe
/** Interrogatives: the user wants an answer, not (necessarily) file changes. */
const QUESTION_PATTERN = /^(what|whats|what's|why|how|when|where|who|which|explain|describe|tell me|walk me through|compare|list)\b/i;
+/**
+ * Text-deliverable writing: in plain chat the response itself IS the
+ * deliverable — a poem, an email, an essay. No tool work is required to
+ * fulfill these, so the narration guard must not force the model through
+ * file tools for them. Repo/code-shaped requests ("fix the login bug",
+ * "build a dashboard") never match this pattern and stay guarded.
+ */
+const TEXT_DELIVERABLE_PATTERN =
+ /\b(poems?|poetry|haiku|stor(y|ies)|essay|essays|lyrics|song|joke|jokes|slogans?|taglines?|e-?mails?|letters?|blog|blogs|articles?|summaries|summari[sz]e|translat\w*|captions?|tweets?|outlines?|brainstorm|names?|titles?|description|descriptions)\b/i;
+
+export function isTextDeliverableRequest(taskText: string): boolean {
+ return TEXT_DELIVERABLE_PATTERN.test(taskText);
+}
+
export interface ExecuteGuardInput {
/** The user's request for this turn. */
taskText: string;
diff --git a/src/index.ts b/src/index.ts
index c26335c3..b87d41d9 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -70,6 +70,7 @@ import { SkillLoader } from './skills/loader.js';
import { registerSkillsCommand } from './skills/cli.js';
import { getManual } from './utils/manual.js';
import { startBackground, stopDaemon, showLogs, getDaemonStatus, registerRuntimeProcess, releaseRuntimeProcess, restartDaemon, tryAutoDaemonize, isStandaloneBinary, getForegroundRuntimeStatus, stopForegroundRuntime } from './cli/daemon.js';
+import { runAttach } from './cli/attach.js';
import { installService, uninstallService, showServiceStatus, isServiceInstalled } from './cli/service.js';
import { runWithWatchdog } from './cli/watchdog.js';
import { setGitHubToken } from './utils/github.js';
@@ -78,7 +79,7 @@ import { ProviderModelFetchError, fetchProviderModelCatalog } from './utils/prov
import { initCloudTokenStore } from './cloud/token-store.js';
import { clearCloudRuntimeOnline, markCloudRuntimeOnline } from './cloud/runtime-status.js';
import { startWebServer, stopWebServer, updateStatus as updateWebStatus, setUserMemory as setWebUserMemory, setWebChannel as setWebWebChannel, setScheduler as setWebScheduler, setAgentSupervisor as setWebSupervisor, setBackgroundTaskManager as setWebBgTasks, setSpotifyClient as setWebSpotify, setProgrammingMode as setWebProgrammingMode, setModelSwitchCallback as setWebModelSwitch, setCurrentProviderCallback as setWebCurrentProvider, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders, setSessionRepository as setWebSessions, setSessionSyncEnabledCallback as setWebSessionSyncEnabled } from './web/server.js';
-import { isWebAuthInitialized, setWebPassword } from './web/auth.js';
+import { isWebAuthInitialized, setWebPassword, writeAttachToken } from './web/auth.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
let pkgVersion: string;
@@ -2127,7 +2128,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
const message = String(reason instanceof Error ? reason.message : reason || '');
if (/already running|EADDRINUSE|registerRuntimeProcess/i.test(message)) {
try {
- process.stderr.write(`\n✗ Mercury cannot start: ${message}\n Stop the other instance with \`mercury stop\` or \`kill <pid>\`.\n`);
+ process.stderr.write(`\n✗ Mercury cannot start: ${message}\n Attach to it with \`mercury attach\`, or stop it with \`mercury stop\` / \`kill <pid>\`.\n`);
} catch { /* stderr gone */ }
process.exit(1);
}
@@ -3252,6 +3253,9 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
if (config.web.enabled) {
startWebServer();
+ // Rotate the machine-local attach token for this boot so second
+ // terminals can connect without the web login flow.
+ writeAttachToken();
updateWebStatus({
running: true,
pid: process.pid,
@@ -3307,6 +3311,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
await channels.startAll();
if (config.web.enabled) {
startWebServer();
+ writeAttachToken();
updateWebStatus({
running: true,
pid: process.pid,
@@ -3399,6 +3404,13 @@ program
autoDaemonize();
return;
}
+ // A second terminal joins the running runtime instead of fighting it.
+ const foreground = getForegroundRuntimeStatus();
+ if (foreground.running && foreground.pid) {
+ console.log(chalk.cyan(` ⚿ Mercury is already running (PID: ${foreground.pid}) — attaching.`));
+ await runAttach();
+ return;
+ }
autoDaemonize();
await runAgent();
});
@@ -3423,6 +3435,12 @@ program
}
if (opts.foreground) {
+ const foreground = getForegroundRuntimeStatus();
+ if (foreground.running && foreground.pid) {
+ console.log(chalk.cyan(` ⚿ Mercury is already running (PID: ${foreground.pid}) — attaching.`));
+ await runAttach();
+ return;
+ }
await runAgent();
return;
}
@@ -3430,6 +3448,13 @@ program
startBackground();
});
+program
+ .command('attach')
+ .description('Attach this terminal to an already-running Mercury runtime (chat + live streaming)')
+ .action(async () => {
+ await runAttach();
+ });
+
program
.command('stop')
.description('Stop a running Mercury process (daemon or foreground)')
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index 6530d796..d3bf2f28 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -6,8 +6,8 @@ import type { PermissionMode } from '../channels/base.js';
import type { ProgrammingModeState } from '../core/programming-mode.js';
import { renderMarkdown } from '../utils/markdown.js';
import { highlightCodeBlock } from '../utils/highlight.js';
-import { anchorViewportDistance, normalizeTerminalText, getViewportWindow, moveViewport } from './terminal-viewport.js';
-import { buildMercuryMessageLines, buildMercuryBrandLines, wrapMercuryText, type MercuryTranscriptLine } from './mercury-transcript.js';
+import { normalizeTerminalText, getViewportWindow } from './terminal-viewport.js';
+import { buildMercuryMessageLines, buildMercuryBrandLines, buildStreamTailLines, type MercuryTranscriptLine } from './mercury-transcript.js';
import { PLAYER_CONTROLS, formatNowPlaying } from '../spotify/ui.js';
import type { SpotifyClient } from '../spotify/client.js';
import type { SubAgentStatus } from '../types/agent.js';
@@ -451,16 +451,40 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
if (key.leftArrow) { setCursorPos((p) => Math.max(0, p - 1)); return; }
if (key.rightArrow) { setCursorPos((p) => Math.min(input.length, p + 1)); return; }
- if (key.upArrow) { onInput('/mc scroll 1'); return; }
- if (key.downArrow) { onInput('/mc scroll -1'); return; }
- const transcriptPage = Math.max(5, terminalSize.rows - 12);
- if (key.pageUp) { onInput(`/mc scroll ${transcriptPage}`); return; }
- if (key.pageDown) { onInput(`/mc scroll -${transcriptPage}`); return; }
- if ((key as any).home) { onInput('/mc scroll 1000000000'); return; }
- if ((key as any).end) { onInput('/mc live'); return; }
- if (key.ctrl && (ch === 'u' || ch === 'U')) { onInput(`/mc scroll ${transcriptPage}`); return; }
- if (key.ctrl && (ch === 'a' || ch === 'A')) { onInput('/mc scroll 1000000000'); return; }
- if (key.ctrl && (ch === 'e' || ch === 'E')) { onInput('/mc live'); return; }
+ // Transcript scrolling is terminal-native now (the transcript prints
+ // into scrollback via <Static>): ↑/↓ navigate input history instead.
+ if (key.upArrow) {
+ if (inputHistory.length === 0) return;
+ if (historyIndex === -1) {
+ setHistoryDraft(input);
+ const next = inputHistory.length - 1;
+ setHistoryIndex(next);
+ setInputAndCursor(inputHistory[next] ?? '');
+ return;
+ }
+ const next = Math.max(0, historyIndex - 1);
+ setHistoryIndex(next);
+ setInputAndCursor(inputHistory[next] ?? '');
+ return;
+ }
+ if (key.downArrow) {
+ if (historyIndex === -1) return;
+ const next = historyIndex + 1;
+ if (next >= inputHistory.length) {
+ setHistoryIndex(-1);
+ setInputAndCursor(historyDraft);
+ return;
+ }
+ setHistoryIndex(next);
+ setInputAndCursor(inputHistory[next] ?? '');
+ return;
+ }
+ if ((key as any).home) { setCursorPos(0); return; }
+ if ((key as any).end) { setCursorPos(input.length); return; }
+ // Readline-style cursor shortcuts (the old Ctrl+A/Ctrl+E scroll
+ // bindings are gone with the in-app viewport).
+ if (key.ctrl && (ch === 'a' || ch === 'A')) { setCursorPos(0); return; }
+ if (key.ctrl && (ch === 'e' || ch === 'E')) { setCursorPos(input.length); return; }
if (key.backspace || key.delete) {
if (cursorPos > 0) {
setInput((prev) => prev.slice(0, cursorPos - 1) + prev.slice(cursorPos));
@@ -944,23 +968,24 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
{state.mode === 'mercury-code' ? (
<MercuryCodeView
state={state}
- height={Math.max(10, terminalSize.rows)}
cols={terminalSize.cols}
input={input}
cursorPos={cursorPos}
- onInput={onInput}
- onScrollClamp={(distance) => onInput(`/mc scroll-set ${distance}`)}
permIdx={permIdx}
/>
) : null}
{state.mode === 'spotify' ? <SpotifyBody activeIdx={spotifyIdx} nowPlaying={spotifyNow} status={spotifyStatus} volume={spotifyVolume} albumArtAnsi={spotifyArtAnsi} /> : null}
{state.mode === 'menu' ? <MenuBody menuIdx={menuIdx} /> : null}
- {state.mode === 'coding' ? <CodingBody state={state} maxDynamicLines={Math.max(3, terminalSize.rows - 14)} /> : null}
+ {state.mode === 'coding' ? <CodingBody state={state} maxDynamicLines={Math.min(12, Math.max(3, terminalSize.rows - 14))} /> : null}
{state.mode === 'workspace' ? (
<WorkspaceBody state={state} gitCursor={gitCursor} height={Math.max(8, terminalSize.rows - 6)} cols={terminalSize.cols} onInput={onInput} />
) : null}
{state.mode === 'chat' ? (
- <ChatBody state={state} maxDynamicLines={Math.max(3, terminalSize.rows - 14)} />
+ // Live-region cap: only the newest few lines of the streaming message
+ // repaint per frame — finalized content is already in <Static>. A
+ // near-full-screen live region was rewritten every 60ms frame, which
+ // read as a visible "on-off" flicker on long chats.
+ <ChatBody state={state} maxDynamicLines={Math.min(12, Math.max(3, terminalSize.rows - 14))} />
) : null}
{state.permissionPrompt && state.mode !== 'mercury-code' && (
<PermPromptView prompt={state.permissionPrompt} activeIdx={permIdx} />
@@ -2181,176 +2206,6 @@ function InputBox({
// ─── Mercury Code (full-screen /code) ───────────────────────────────────────
-/** Per-message transcript index entry: exact row count plus optional lines. */
-interface MercuryCacheEntry {
- key: string;
- count: number;
- lines?: MercuryTranscriptLine[];
-}
-/**
- * Bounded transcript projection index. Counts are retained for every known
- * message (tiny numbers) so scroll math stays exact, but rendered lines are
- * kept only for a small LRU window around the viewport. Formatting work is
- * amortized: each message is built once per (content, width) revision.
- */
-const mercuryTranscriptIndex = new Map<string, MercuryCacheEntry>();
-const MERCURY_INDEX_MAX_ENTRIES = 4096;
-const MERCURY_LINES_MAX_ENTRIES = 64;
-const MERCURY_LINES_MAX_LINES = 6000;
-let mercuryLineCacheEntries = 0;
-let mercuryLineCacheLines = 0;
-
-function mercuryCacheKey(msg: ChatMessage, width: number): string {
- return `${msg.id}|${msg.role}|${msg.content.length}|${msg.timestamp}|${msg.streaming ? 1 : 0}|${width}`;
-}
-
-function evictMercuryLineCache(): void {
- while ((mercuryLineCacheEntries > MERCURY_LINES_MAX_ENTRIES || mercuryLineCacheLines > MERCURY_LINES_MAX_LINES)) {
- const oldest = mercuryTranscriptIndex.keys().next().value;
- if (oldest === undefined) break;
- const entry = mercuryTranscriptIndex.get(oldest)!;
- if (entry.lines) {
- mercuryLineCacheLines -= entry.lines.length;
- mercuryLineCacheEntries -= 1;
- entry.lines = undefined;
- // Move the count-only entry to the end so line eviction progresses.
- mercuryTranscriptIndex.delete(oldest);
- mercuryTranscriptIndex.set(oldest, entry);
- continue;
- }
- if (mercuryLineCacheEntries === 0 && mercuryLineCacheLines === 0) break;
- break;
- }
- while (mercuryTranscriptIndex.size > MERCURY_INDEX_MAX_ENTRIES) {
- const oldest = mercuryTranscriptIndex.keys().next().value;
- if (oldest === undefined) break;
- const entry = mercuryTranscriptIndex.get(oldest)!;
- if (entry.lines) {
- mercuryLineCacheLines -= entry.lines.length;
- mercuryLineCacheEntries -= 1;
- }
- mercuryTranscriptIndex.delete(oldest);
- }
-}
-
-function getMercuryEntry(msg: ChatMessage, width: number, wantLines: boolean): MercuryCacheEntry {
- const key = mercuryCacheKey(msg, width);
- const existing = mercuryTranscriptIndex.get(msg.id);
- if (existing && existing.key === key) {
- if (existing.lines) {
- // LRU touch: refresh insertion order.
- mercuryTranscriptIndex.delete(msg.id);
- mercuryTranscriptIndex.set(msg.id, existing);
- return existing;
- }
- if (wantLines) {
- const lines = buildMercuryMessageLines(msg, width);
- existing.lines = lines;
- mercuryLineCacheEntries += 1;
- mercuryLineCacheLines += lines.length;
- evictMercuryLineCache();
- }
- return existing;
- }
- const lines = buildMercuryMessageLines(msg, width);
- const entry: MercuryCacheEntry = { key, count: lines.length };
- if (existing?.lines) {
- mercuryLineCacheLines -= existing.lines.length;
- mercuryLineCacheEntries -= 1;
- }
- entry.lines = lines;
- mercuryLineCacheEntries += 1;
- mercuryLineCacheLines += lines.length;
- mercuryTranscriptIndex.set(msg.id, entry);
- evictMercuryLineCache();
- return entry;
-}
-
-/** A message-count index used for exact scroll math without retaining text. */
-export interface MercuryTranscriptIndex {
- msgs: ChatMessage[];
- counts: number[];
- total: number;
- /** Brand rows rendered before the first message (scroll away like a header). */
- brandLines: MercuryTranscriptLine[];
-}
-
-export function buildMercuryTranscriptIndex(
- messages: ChatMessage[],
- width: number,
- brandLines: MercuryTranscriptLine[] = [],
-): MercuryTranscriptIndex {
- const msgs: ChatMessage[] = [];
- const counts: number[] = [];
- let total = brandLines.length;
- for (const msg of messages) {
- if (typeof msg.content !== 'string') continue;
- const entry = getMercuryEntry(msg, width, false);
- counts.push(entry.count);
- msgs.push(msg);
- total += entry.count;
- }
- return { msgs, counts, total, brandLines };
-}
-
-/** Format only the transcript rows inside [startRow, endRow). */
-export function renderMercuryTranscriptWindow(
- index: MercuryTranscriptIndex,
- startRow: number,
- endRow: number,
- width: number,
-): MercuryTranscriptLine[] {
- const out: MercuryTranscriptLine[] = [];
- // Brand block occupies the leading rows of the transcript.
- const brandCount = index.brandLines.length;
- if (startRow < brandCount && endRow > 0) {
- out.push(...index.brandLines.slice(startRow, Math.min(brandCount, endRow)));
- }
- let offset = brandCount;
- for (let i = 0; i < index.msgs.length; i++) {
- const count = index.counts[i];
- const msgStart = offset;
- const msgEnd = offset + count;
- offset = msgEnd;
- if (msgEnd <= startRow || msgStart >= endRow) continue;
- const entry = getMercuryEntry(index.msgs[i], width, true);
- const lines = entry.lines ?? [];
- const from = Math.max(0, startRow - msgStart);
- const to = Math.max(0, Math.min(count, endRow - msgStart));
- if (to > from) out.push(...lines.slice(from, to));
- }
- return out;
-}
-
-/**
- * Format a viewport range across the transcript PLUS the live streaming tail.
- *
- * The tail is a virtual block appended after the finalized transcript: it is
- * part of the scroll math (grand total = index.total + tail.length), so the
- * viewport slices across both naturally. Appending tail rows after a full
- * height window instead overflowed the fixed-height transcript box — bottom
- * rows clipped, scroll distances wrong, top messages seemingly trimmed.
- */
-export function renderMercuryTranscriptRange(
- index: MercuryTranscriptIndex,
- tail: MercuryTranscriptLine[],
- startRow: number,
- endRow: number,
- width: number,
-): MercuryTranscriptLine[] {
- const finalizedTotal = index.total;
- const out: MercuryTranscriptLine[] = [];
- if (startRow < finalizedTotal && endRow > 0) {
- out.push(...renderMercuryTranscriptWindow(index, startRow, Math.min(endRow, finalizedTotal), width));
- }
- if (endRow > finalizedTotal && tail.length > 0) {
- const from = Math.max(0, startRow - finalizedTotal);
- const to = Math.min(tail.length, endRow - finalizedTotal);
- if (to > from) out.push(...tail.slice(from, to));
- }
- return out;
-}
-
const CODE_HINTS: Array<[string, string, string]> = [
['/code auto', 'plan & build automatically — the default', ''],
['/code plan', 'analyze & propose before coding', 'ctrl+p'],
@@ -2406,8 +2261,10 @@ 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. */
-const STREAM_TAIL_MAX_LINES = 40;
+/** 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;
/**
* Vibrant Mercury palette for the wordmark. Background-adaptive: on a dark
@@ -2580,48 +2437,138 @@ function MercuryCodeExitConfirm({ boxWidth }: { boxWidth: number }): React.React
);
}
+/**
+ * Static-output item key for the Mercury Code brand block: printed once when
+ * Mercury Code mounts, then it lives in terminal scrollback like any other
+ * transcript row (native scrollback model — same as ChatBody above).
+ */
+const MERCURY_BRAND_ITEM_KEY = '__mercury_code_brand__';
+
+/** One formatted transcript row (shared by the brand block, Static items, and the live stream tail). */
+function MercuryTranscriptRow({ line }: { line: MercuryTranscriptLine }): React.ReactNode {
+ const roleColor = line.role === 'user' ? 'yellow' : line.role === 'agent' ? 'cyan' : 'gray';
+ if (line.kind === 'brand') {
+ // Indent is baked into the text for exact centering.
+ return (
+ <Box>
+ {line.accent && line.accent.length > 0 ? (
+ <>
+ <Text bold color={WORDMARK_COLORS.mercury}>{line.text}</Text>
+ <Text bold color={WORDMARK_COLORS.code}>{line.accent}</Text>
+ </>
+ ) : (
+ <Text bold color="cyan">{line.text}</Text>
+ )}
+ </Box>
+ );
+ }
+ if (line.kind === 'spacer') {
+ return <Box paddingX={2}><Text> </Text></Box>;
+ }
+ if (line.kind === 'header') {
+ return (
+ <Box paddingX={2}>
+ <Text bold color={roleColor}>● {line.text}</Text>
+ </Box>
+ );
+ }
+ if (line.kind === 'code-label') {
+ return (
+ <Box paddingX={2}>
+ <Text color={roleColor}>│ </Text><Text dimColor>┌─ {line.text}</Text>
+ </Box>
+ );
+ }
+ if (line.kind === 'code') {
+ const highlighted = highlightCodeBlock(line.text, line.lang)[0] ?? line.text;
+ return (
+ <Box paddingX={2}>
+ <Text color={roleColor}>│ </Text><Text>{highlighted || ' '}</Text>
+ </Box>
+ );
+ }
+ if (line.kind === 'system') {
+ const complete = line.text.startsWith('Task complete');
+ return (
+ <Box paddingX={2}>
+ <Text color={complete ? 'green' : 'gray'} bold={complete}>─ {line.text || ' '}</Text>
+ </Box>
+ );
+ }
+ if (line.kind === 'file') {
+ return (
+ <Box paddingX={2}>
+ <Text color="green"> ↳ </Text><Text>{line.text}</Text>
+ </Box>
+ );
+ }
+ return (
+ <Box paddingX={2}>
+ <Text color={roleColor}>│ </Text><Text>{line.text || ' '}</Text>
+ </Box>
+ );
+}
+
+function MercuryBrandBlock({ brandLines }: { brandLines: MercuryTranscriptLine[] }): React.ReactNode {
+ return (
+ <Box flexDirection="column" flexShrink={0}>
+ {brandLines.map((line) => <MercuryTranscriptRow key={line.key} line={line} />)}
+ </Box>
+ );
+}
+
+function MercuryMessageBlock({ message, width }: { message: ChatMessage; width: number }): React.ReactNode {
+ const lines = buildMercuryMessageLines(message, width);
+ return (
+ <Box flexDirection="column" flexShrink={0}>
+ {lines.map((line) => <MercuryTranscriptRow key={line.key} line={line} />)}
+ </Box>
+ );
+}
+
+/**
+ * Mercury Code transcript — native scrollback model. Finalized messages print
+ * once through <Static> into the terminal's own scrollback, so the ENTIRE
+ * transcript (brand wordmark included) scrolls with the terminal's native
+ * scrolling and every row is drag-selectable. No sticky header, no in-app
+ * viewport: only a small live region (streaming tail, feedback, prompts,
+ * input, status) repaints per frame, which also removes the per-stream
+ * full-frame repaint flicker.
+ */
export function MercuryCodeView({
state,
- height,
cols,
- onInput,
input,
cursorPos,
- onScrollClamp,
permIdx,
}: {
state: TuiState;
- height: number;
cols: number;
- onInput: (text: string) => void;
input?: string | undefined;
cursorPos?: number | undefined;
- onScrollClamp?: (distance: number) => void;
permIdx?: number | undefined;
}): React.ReactNode {
const mc = state.mercuryCode;
const contentWidth = Math.max(20, cols - 4);
- // Bounded projection: retain exact per-message row counts for scroll math
- // and format only the rows currently visible. No full-transcript flatten,
- // no 60k-line render cache. The brand block is the transcript's first rows,
- // centered across the terminal width, so new content scrolls it up and
- // away like a web page header.
const brandLines = React.useMemo(() => buildMercuryBrandLines(state.version, cols), [state.version, cols]);
// Streaming message exclusion: the streaming message's content grows on
- // every chunk, so including it in the memoized index would invalidate the
- // memo and re-run buildMercuryMessageLines (full markdown parse + wrap) on
- // the entire buffer each 60ms frame — O(frames × chars) churn that caused
- // multi-GB allocation storms during long streaming responses.
+ // every chunk, so it must stay out of <Static> (its identity key would
+ // print it once at whatever length it had when it first appeared). It
+ // renders in the live tail below and joins <Static> when finalized.
const finalizedMessages = React.useMemo(
() => state.chatMessages.filter((m) => !m.streaming && !m.id.startsWith('heartbeat-')),
[state.chatMessages],
);
const streamingMessage = state.chatMessages.find((m) => m.streaming && !m.id.startsWith('heartbeat-'));
- const transcriptIndex = React.useMemo(
- () => buildMercuryTranscriptIndex(finalizedMessages, contentWidth, brandLines),
- [finalizedMessages, contentWidth, brandLines],
+
+ // Live streaming tail: rendered through the same markdown pipeline as
+ // 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],
);
- const totalLines = transcriptIndex.total;
if (!mc) {
return (
@@ -2631,184 +2578,79 @@ export function MercuryCodeView({
);
}
- // Row budget: the transcript owns the full screen height (brand rows are
- // part of the scrollable content); chrome is input, live feedback, exit
- // confirm, and the status line.
- const inputLines = Math.max(1, (input ?? '').split('\n').length);
- const inputRows = 2 + inputLines;
- const confirmRows = mc.exitConfirm ? 3 : 0;
- const liveVisible = state.isThinking || state.toolSteps.some((s) => s.status === 'running') || state.subAgents.some((a) => a.status === 'running');
- const liveRows = liveVisible
- ? 1 + Math.min(2, state.toolSteps.filter((s) => s.status === 'done').slice(-2).length) + (state.subAgents.some((a) => a.status === 'running') ? 1 + Math.min(4, state.subAgents.filter((a) => a.status === 'running').length) : 0)
- : 0;
- const statusRows = 1;
- // Plan checklist + interactive prompt rows are part of the fixed chrome.
- const planRows = state.planProgress && state.planProgress.length > 0
- ? Math.min(7, state.planProgress.length + 1)
- : 0;
- const promptRows = state.permissionPrompt
- ? 2 + (state.permissionPrompt.options?.length ?? 0)
- : 0;
- const transcriptHeight = Math.max(3, height - inputRows - 1 - liveRows - confirmRows - planRows - promptRows);
-
- // Live streaming tail: a bounded, fixed-cost projection of the stream
- // buffer (last STREAM_TAIL_CHARS, no markdown parsing). It participates in
- // the scroll math as a virtual block after the finalized transcript, so
- // the viewport slices across both — never appended on top of a full
- // window (that overflowed the box and clipped bottom rows).
- const streamTail = React.useMemo(() => {
- if (!streamingMessage) return [] as MercuryTranscriptLine[];
- const content = streamingMessage.content;
- const tail = content.length > STREAM_TAIL_CHARS ? content.slice(-STREAM_TAIL_CHARS) : content;
- const lines: MercuryTranscriptLine[] = [{ key: `${streamingMessage.id}:hdr`, kind: 'header', role: streamingMessage.role, text: 'MERCURY' }];
- for (const row of tail.split('\n')) {
- for (const chunk of wrapMercuryText(row, contentWidth)) {
- lines.push({ key: `${streamingMessage.id}:${lines.length}`, kind: 'text', role: streamingMessage.role, text: chunk });
- if (lines.length > STREAM_TAIL_MAX_LINES) {
- // Bound the block: keep the newest rows (replace header position).
- lines.splice(1, lines.length - STREAM_TAIL_MAX_LINES);
- }
- }
- }
- return lines;
- }, [streamingMessage, contentWidth]);
- const totalWithTail = totalLines + streamTail.length;
-
- const previousLineCount = React.useRef(totalWithTail);
- const anchoredOffset = anchorViewportDistance(mc.scrollOffset, previousLineCount.current, totalWithTail);
-
- // Sticky compact brand replaces the pixel wordmark once its rows scroll
- // away — the session header stays visible without consuming scroll space.
- // Its single row is reserved by shrinking the transcript box (below), and
- // the viewport height is reduced to match so rows are never clipped.
- const preliminaryViewport = getViewportWindow(totalWithTail, transcriptHeight, anchoredOffset);
- const wordmarkOnScreen = preliminaryViewport.start < brandLines.length;
- const effectiveViewportRows = wordmarkOnScreen ? transcriptHeight : transcriptHeight - 1;
- const viewport = getViewportWindow(totalWithTail, effectiveViewportRows, anchoredOffset);
- const adjustedVisible = renderMercuryTranscriptRange(transcriptIndex, streamTail, viewport.start, viewport.end, contentWidth);
-
- React.useEffect(() => {
- previousLineCount.current = totalWithTail;
- if (onScrollClamp && viewport.distanceFromBottom !== mc.scrollOffset) {
- onScrollClamp(viewport.distanceFromBottom);
- }
- }, [totalWithTail, onScrollClamp, mc.scrollOffset, viewport.distanceFromBottom]);
+ const staticItems: Array<string | ChatMessage> = [
+ MERCURY_BRAND_ITEM_KEY,
+ ...finalizedMessages.slice(-MAX_STATIC_MESSAGES),
+ ];
- // Status line (single row): left hint, right context.
+ // Status bar (single row): a short contextual hint on the left, session
+ // state on the right. Everything that isn't state is dropped — the old bar
+ // listed a wall of key hints ("esc esc exit · wheel scrolls · drag
+ // selects · …") that wrapped onto a second line and pushed the state
+ // segments (model, tokens) out of view. Non-git workspaces show no git
+ // segment at all instead of the meaningless "⎇ not-a-git-repo · ✓".
const mode = state.programmingMode;
const modeLabel = mode === 'execute' ? 'EXECUTE' : mode === 'plan' ? 'PLAN' : mode === 'auto' ? 'AUTO' : 'CHAT';
- const modeColor = mode === 'execute' ? 'green' : mode === 'plan' ? 'yellow' : 'cyan';
const git = mc.git;
- const gitBits: string[] = [];
- if (git.branch !== 'no-git') {
- gitBits.push(`⎇ ${git.branch}`);
+ const hasGit = git.branch !== 'no-git' && git.branch !== 'not-a-git-repo';
+ const rightSegs: Array<{ text: string; color: string }> = [{ text: mc.dirName, color: 'cyan' }];
+ if (hasGit) {
+ const gitBits = [`⎇ ${git.branch}`];
if (git.ahead > 0) gitBits.push(`↑${git.ahead}`);
if (git.behind > 0) gitBits.push(`↓${git.behind}`);
- gitBits.push(git.dirty > 0 ? `±${git.dirty}` : '✓');
+ if (git.dirty > 0) gitBits.push(`±${git.dirty}`);
+ rightSegs.push({ text: gitBits.join(' '), color: 'blue' });
}
- const rightParts = [mc.dirName, ...gitBits, modeLabel];
+ rightSegs.push({ text: modeLabel, color: mode === 'execute' ? 'green' : mode === 'plan' ? 'yellow' : 'cyan' });
+ if (state.provider) rightSegs.push({ text: `${state.provider.name} ${state.provider.model}`, color: 'magenta' });
// Developer status HUD: token budget is otherwise invisible in Mercury
// Code (TokenBarView only renders in chat surfaces).
- if (state.tokenInfo) {
- const pct = Math.round(state.tokenInfo.percentage);
- rightParts.push(`⚡ ${pct}%`);
+ if (state.tokenInfo) rightSegs.push({ text: `⚡ ${Math.round(state.tokenInfo.percentage)}%`, color: 'green' });
+ // Fit: drop whole segments from the right when the terminal is narrow.
+ const SEP = ' · ';
+ let segWidth = 4; // paddingX on both sides
+ rightSegs.forEach((seg, i) => { segWidth += seg.text.length + (i > 0 ? SEP.length : 0); });
+ while (segWidth > cols - 2 && rightSegs.length > 1) {
+ const removed = rightSegs.pop()!;
+ segWidth -= removed.text.length + SEP.length;
}
- if (state.provider) rightParts.push(`${state.provider.name} ${state.provider.model}`);
- const rightStr = rightParts.join(' · ');
+ const leftHint = 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
+ : '↵ send · /help';
+
+ const showHints = finalizedMessages.length === 0 && streamTail.length === 0;
return (
- <Box flexDirection="column" height={height} overflow="hidden">
- {!wordmarkOnScreen && (
- <Box paddingX={1} flexShrink={0}>
- <Text bold color="cyan">☿ MERCURY </Text>
- <Text bold color={WORDMARK_COLORS.code}>CODE</Text>
- <Text dimColor> v{state.version}</Text>
- <Text dimColor> · </Text>
- <Text dimColor>{mc.dirName}</Text>
+ <Box flexDirection="column" flexShrink={0}>
+ <Static items={staticItems} itemKey={staticItemKey}>
+ {(item) => typeof item === 'string'
+ ? <MercuryBrandBlock key={item} brandLines={brandLines} />
+ : <MercuryMessageBlock key={item.id} message={item} width={contentWidth} />}
+ </Static>
+ {streamTail.length > 0 && (
+ <Box flexDirection="column" flexShrink={0}>
+ {streamTail.map((line) => <MercuryTranscriptRow key={line.key} line={line} />)}
</Box>
)}
- <Box flexDirection="column" height={effectiveViewportRows} overflow="hidden">
- {adjustedVisible.length === 0 && streamTail.length === 0 && totalWithTail === 0 ? (
- <MercuryCodeHints cols={cols} />
- ) : (
- adjustedVisible.map((line) => {
- const roleColor = line.role === 'user' ? 'yellow' : line.role === 'agent' ? 'cyan' : 'gray';
- if (line.kind === 'brand') {
- // Indent is baked into the text for exact centering.
- return (
- <Box key={line.key}>
- {line.accent && line.accent.length > 0 ? (
- <>
- <Text bold color={WORDMARK_COLORS.mercury}>{line.text}</Text>
- <Text bold color={WORDMARK_COLORS.code}>{line.accent}</Text>
- </>
- ) : (
- <Text bold color="cyan">{line.text}</Text>
- )}
- </Box>
- );
- }
- if (line.kind === 'spacer') {
- return <Box key={line.key} paddingX={2}><Text> </Text></Box>;
- }
- if (line.kind === 'header') {
- return (
- <Box key={line.key} paddingX={2}>
- <Text bold color={roleColor}>● {line.text}</Text>
- </Box>
- );
- }
- if (line.kind === 'code-label') {
- return (
- <Box key={line.key} paddingX={2}>
- <Text color={roleColor}>│ </Text><Text dimColor>┌─ {line.text}</Text>
- </Box>
- );
- }
- if (line.kind === 'code') {
- const highlighted = highlightCodeBlock(line.text, line.lang)[0] ?? line.text;
- return (
- <Box key={line.key} paddingX={2}>
- <Text color={roleColor}>│ </Text><Text>{highlighted || ' '}</Text>
- </Box>
- );
- }
- if (line.kind === 'system') {
- const complete = line.text.startsWith('Task complete');
- return (
- <Box key={line.key} paddingX={2}>
- <Text color={complete ? 'green' : 'gray'} bold={complete}>─ {line.text || ' '}</Text>
- </Box>
- );
- }
- if (line.kind === 'file') {
- return (
- <Box key={line.key} paddingX={2}>
- <Text color="green"> ↳ </Text><Text>{line.text}</Text>
- </Box>
- );
- }
- return (
- <Box key={line.key} paddingX={2}>
- <Text color={roleColor}>│ </Text><Text>{line.text || ' '}</Text>
- </Box>
- );
- })
- )}
- </Box>
+ {showHints && <MercuryCodeHints cols={cols} />}
{state.planProgress && state.planProgress.length > 0 && <PlanProgressView steps={state.planProgress} />}
<MercuryLiveFeedback state={state} />
{state.permissionPrompt && <PermPromptView prompt={state.permissionPrompt} activeIdx={permIdx ?? 0} />}
{mc.exitConfirm && <MercuryCodeExitConfirm boxWidth={Math.max(40, cols - 4)} />}
<MercuryCodeInput input={input ?? ''} cursorPos={cursorPos ?? 0} mode={state.programmingMode} boxWidth={Math.max(40, cols - 4)} />
- <Box paddingX={3} flexShrink={0}>
- {viewport.distanceFromBottom > 0 ? (
- <Text color="yellow">↑↓ scroll · PgUp/PgDn page · Ctrl+E back to live</Text>
- ) : (
- <Text dimColor>↵ send · esc esc exit · ⇧drag copy · ctrl+c quit</Text>
- )}
+ <Box height={1} overflow="hidden" paddingX={2} flexShrink={0}>
+ <Text dimColor>{leftHint}</Text>
<Spacer />
- <Text color="blue" wrap="truncate-end">{rightStr}</Text>
+ <Text wrap="truncate-end">
+ {rightSegs.map((seg, i) => (
+ <React.Fragment key={seg.text}>
+ {i > 0 && <Text color="gray">{SEP}</Text>}
+ <Text color={seg.color}>{seg.text}</Text>
+ </React.Fragment>
+ ))}
+ </Text>
</Box>
</Box>
);
diff --git a/src/ui/mercury-projection.test.ts b/src/ui/mercury-projection.test.ts
deleted file mode 100644
index f8a7869d..00000000
--- a/src/ui/mercury-projection.test.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import type { ChatMessage } from './types.js';
-import { buildMercuryMessageLines, buildMercuryBrandLines, type MercuryTranscriptLine } from './mercury-transcript.js';
-import { buildMercuryTranscriptIndex, renderMercuryTranscriptWindow, renderMercuryTranscriptRange } from './App.js';
-
-const WIDTH = 60;
-const BRAND = buildMercuryBrandLines('test', WIDTH);
-
-function agentMessage(id: string, lines: number): ChatMessage {
- return {
- id,
- role: 'agent',
- content: Array.from({ length: lines }, (_, i) => `row ${id} ${i}`).join('\n'),
- timestamp: 1,
- };
-}
-
-function tailBlock(rows: number): MercuryTranscriptLine[] {
- const lines: MercuryTranscriptLine[] = [{ key: 'stream:hdr', kind: 'header', role: 'agent', text: 'MERCURY' }];
- for (let i = 0; i < rows; i++) {
- lines.push({ key: `stream:${i}`, kind: 'text', role: 'agent', text: `stream row ${i}` });
- }
- return lines;
-}
-
-describe('Mercury Code bounded transcript projection', () => {
- it('produces a window identical to a full flatten', () => {
- const messages = Array.from({ length: 12 }, (_, i) => agentMessage(`m${i}`, 5));
- const index = buildMercuryTranscriptIndex(messages, WIDTH);
- const flat = messages.flatMap((m) => buildMercuryMessageLines(m, WIDTH));
- expect(index.total).toBe(flat.length);
-
- const window = renderMercuryTranscriptWindow(index, 10, 20, WIDTH);
- expect(window).toEqual(flat.slice(10, 20));
- });
-
- it('renders the live tail exactly when scrolled to the bottom', () => {
- const messages = Array.from({ length: 7 }, (_, i) => agentMessage(`m${i}`, 9));
- const index = buildMercuryTranscriptIndex(messages, WIDTH);
- const flat = messages.flatMap((m) => buildMercuryMessageLines(m, WIDTH));
- const window = renderMercuryTranscriptWindow(index, Math.max(0, flat.length - 8), flat.length, WIDTH);
- expect(window).toEqual(flat.slice(-8));
- });
-
- it('keeps the index tiny for long sessions', () => {
- const messages = Array.from({ length: 500 }, (_, i) => agentMessage(`m${i}`, 40));
- const index = buildMercuryTranscriptIndex(messages, WIDTH);
- expect(index.msgs.length).toBe(500);
- expect(index.total).toBeGreaterThan(0);
- const rendered = renderMercuryTranscriptWindow(index, index.total - 5, index.total, WIDTH);
- expect(rendered.length).toBe(5);
- });
-
- it('treats brand rows as leading transcript rows that scroll away', () => {
- const messages = [agentMessage('m0', 8), agentMessage('m1', 8)];
- const index = buildMercuryTranscriptIndex(messages, WIDTH, BRAND);
- const flat = [...BRAND, ...messages.flatMap((m) => buildMercuryMessageLines(m, WIDTH))];
- expect(index.total).toBe(flat.length);
-
- // Top of transcript: brand rows visible first.
- expect(renderMercuryTranscriptWindow(index, 0, 6, WIDTH)).toEqual(flat.slice(0, 6));
- // Scrolled past the brand: message rows only.
- const scrolled = renderMercuryTranscriptWindow(index, BRAND.length + 2, BRAND.length + 8, WIDTH);
- expect(scrolled).toEqual(flat.slice(BRAND.length + 2, BRAND.length + 8));
- // Live tail: brand rows fully out of the window.
- const tail = renderMercuryTranscriptWindow(index, flat.length - 4, flat.length, WIDTH);
- expect(tail).toEqual(flat.slice(-4));
- expect(tail.some((l) => l.kind === 'brand')).toBe(false);
- });
-});
-
-describe('Mercury Code streaming-tail viewport integration', () => {
- it('slices across finalized transcript and streaming tail as one document', () => {
- const messages = Array.from({ length: 5 }, (_, i) => agentMessage(`m${i}`, 6));
- const index = buildMercuryTranscriptIndex(messages, WIDTH);
- const tail = tailBlock(8);
- const grandTotal = index.total + tail.length;
-
- // Equivalent flatten: finalized rows followed by the tail block.
- const flat = [
- ...messages.flatMap((m) => buildMercuryMessageLines(m, WIDTH)),
- ...tail,
- ];
- expect(grandTotal).toBe(flat.length);
-
- // A bottom window covers tail rows; a middle window straddles the seam.
- const bottom = renderMercuryTranscriptRange(index, tail, grandTotal - 10, grandTotal, WIDTH);
- expect(bottom).toEqual(flat.slice(-10));
-
- const seamStart = index.total - 4;
- const seam = renderMercuryTranscriptRange(index, tail, seamStart, seamStart + 10, WIDTH);
- expect(seam).toEqual(flat.slice(seamStart, seamStart + 10));
- });
-
- it('never returns more rows than the requested window (no overflow)', () => {
- const messages = Array.from({ length: 30 }, (_, i) => agentMessage(`m${i}`, 12));
- const index = buildMercuryTranscriptIndex(messages, WIDTH);
- const tail = tailBlock(25);
- const grandTotal = index.total + tail.length;
-
- const windowRows = renderMercuryTranscriptRange(index, tail, grandTotal - 20, grandTotal, WIDTH);
- expect(windowRows.length).toBe(20);
-
- // Scrolled up: rows come only from the finalized transcript.
- const scrolled = renderMercuryTranscriptRange(index, tail, 0, 20, WIDTH);
- expect(scrolled.length).toBe(20);
- expect(scrolled.some((l) => l.key.startsWith('stream:'))).toBe(false);
- });
-
- it('empty tail behaves exactly like the finalized-only window', () => {
- const messages = Array.from({ length: 8 }, (_, i) => agentMessage(`m${i}`, 7));
- const index = buildMercuryTranscriptIndex(messages, WIDTH);
- const noTail = renderMercuryTranscriptRange(index, [], index.total - 12, index.total, WIDTH);
- expect(noTail).toEqual(renderMercuryTranscriptWindow(index, index.total - 12, index.total, WIDTH));
- });
-});
\ No newline at end of file
diff --git a/src/ui/mercury-transcript.ts b/src/ui/mercury-transcript.ts
index f5e7dfdc..1fa38a76 100644
--- a/src/ui/mercury-transcript.ts
+++ b/src/ui/mercury-transcript.ts
@@ -79,6 +79,50 @@ export function buildMercuryBrandLines(version: string, cols: number): MercuryTr
/** Visible rows per code block before it collapses to a pointer. */
export const CODE_BLOCK_VISIBLE_ROWS = 40;
+/**
+ * Live, rendered tail of a streaming message.
+ *
+ * The full markdown pipeline (renderMarkdown + code highlighting + wrap)
+ * runs on the TAIL SLICE only, so per-frame work stays bounded by the tail
+ * budget — never O(full buffer), which caused multi-GB allocation storms
+ * during long streams.
+ *
+ * The slice is line-aligned and, when the pre-tail region ends inside a code
+ * fence, backed up to the fence opener so the live block always contains a
+ * complete fence (label + code rows) and renders as code — never as broken
+ * prose. The capped row budget keeps the live frame small either way.
+ */
+export function buildStreamTailLines(
+ message: ChatMessage,
+ width: number,
+ tailChars = 8 * 1024,
+ maxLines = 12,
+): MercuryTranscriptLine[] {
+ const content = message.content;
+ if (content.length === 0) return [];
+ const rawStart = Math.max(0, content.length - tailChars);
+ const head = content.slice(0, rawStart);
+ const insideFence = (head.match(/```/g) || []).length % 2 === 1;
+ // Plain line alignment: never start the slice mid-line.
+ let start = rawStart === 0 ? 0 : content.indexOf('\n', rawStart) + 1;
+ 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;
+ }
+ const tailMessage: ChatMessage = { ...message, content: content.slice(start) };
+ const lines = buildMercuryMessageLines(tailMessage, width);
+ // Keep the header row, then the newest rows below it.
+ if (lines.length > maxLines) {
+ return [lines[0], ...lines.slice(-(maxLines - 1))];
+ }
+ return lines;
+}
+
export function buildMercuryMessageLines(message: ChatMessage, width: number): MercuryTranscriptLine[] {
if (message.id.startsWith('heartbeat-')) return [];
const contentWidth = Math.max(12, width - 4);
diff --git a/src/ui/stream-tail.test.ts b/src/ui/stream-tail.test.ts
index 7fda7fc1..8ba13d0b 100644
--- a/src/ui/stream-tail.test.ts
+++ b/src/ui/stream-tail.test.ts
@@ -1,29 +1,34 @@
import { describe, expect, it } from 'vitest';
-import { wrapMercuryText } from './mercury-transcript.js';
+import { buildStreamTailLines, type MercuryTranscriptLine } from './mercury-transcript.js';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
+import type { ChatMessage } from './types.js';
const src = (p: string) => readFileSync(join(dirname(fileURLToPath(import.meta.url)), p), 'utf8');
/**
- * Regression guard for the streaming-tail projection: the per-frame render
- * cost must be bounded by the TAIL budget (chars + rows), never by the total
- * accumulated stream length. A 64KB streaming buffer re-formatted per frame
- * was the O(frames × chars) allocation storm behind the 2.5GB OOM.
+ * Regression guards for the streaming-tail projection. The live tail is
+ * rendered through the full markdown pipeline (beautiful live output), but
+ * per-frame work must stay bounded by the TAIL budget (chars + rows), never
+ * by the total accumulated stream length — a full-buffer markdown parse +
+ * wrap per frame was the O(frames × chars) allocation storm behind the
+ * 2.5GB OOM.
*/
describe('streaming tail projection bounds', () => {
const STREAM_TAIL_CHARS = 8 * 1024;
- const STREAM_TAIL_MAX_LINES = 40;
+ const STREAM_TAIL_MAX_LINES = 12;
const WIDTH = 80;
- function projectTail(content: string): string[] {
- const tail = content.length > STREAM_TAIL_CHARS ? content.slice(-STREAM_TAIL_CHARS) : content;
- const out: string[] = [];
- for (const row of tail.split('\n')) {
- out.push(...wrapMercuryText(row, WIDTH));
- }
- return out.slice(-STREAM_TAIL_MAX_LINES);
+ function projectTail(content: string): MercuryTranscriptLine[] {
+ const message: ChatMessage = {
+ id: 'live_1',
+ role: 'agent',
+ content,
+ timestamp: 1,
+ streaming: true,
+ };
+ return buildStreamTailLines(message, WIDTH, STREAM_TAIL_CHARS, STREAM_TAIL_MAX_LINES);
}
it('render cost stays constant as the stream grows 100x', () => {
@@ -42,8 +47,8 @@ describe('streaming tail projection bounds', () => {
let content = '';
for (let i = 0; i < 200; i++) content += 'x'.repeat(100) + '\n';
const projected = projectTail(content);
- const totalChars = projected.reduce((sum, l) => sum + l.length, 0);
- // Rows wrapped from an 8KB window cannot exceed the window + wrap slack.
+ const totalChars = projected.reduce((sum, l) => sum + l.text.length, 0);
+ // Rows rendered from an 8KB window cannot exceed the window + wrap slack.
expect(totalChars).toBeLessThan(STREAM_TAIL_CHARS + STREAM_TAIL_MAX_LINES * WIDTH + 1024);
});
@@ -52,17 +57,73 @@ describe('streaming tail projection bounds', () => {
const rows = projectTail(huge);
expect(rows.length).toBeLessThanOrEqual(STREAM_TAIL_MAX_LINES);
});
+
+ it('renders markdown live (header rows, code blocks)', () => {
+ const content = '# Title\n\nsome prose\n\n```ts\nconst x = 1;\n```\n\n- bullet one\n- bullet two\n';
+ const lines = projectTail(content);
+ const kinds = lines.map((l) => l.kind);
+ // A markdown header renders as its own rendered text rows; the fenced
+ // block gets a code-label + code rows, not plain text.
+ expect(kinds).toContain('code-label');
+ expect(kinds).toContain('code');
+ expect(kinds).toContain('header');
+ expect(lines[0].kind).toBe('header');
+ });
+
+ it('renders a complete code block whose opener sits inside the tail window', () => {
+ // Fence opener inside the tail: the slice must contain the complete
+ // block (label + rows) rendered as code; earlier prose renders as text.
+ const longProse = 'prose line\n'.repeat(800); // > 8KB pre-tail region
+ const content = longProse + '```ts\nconst x = 1;\nconst y = 2;\n';
+ const projected = projectTail(content);
+ const kinds = projected.map((l) => l.kind);
+ expect(kinds).toContain('code');
+ expect(kinds).toContain('code-label');
+ });
+
+ it('aligns the tail to the fence opener when the window opens mid-block', () => {
+ // The raw window starts INSIDE an unclosed code block — backing up to the
+ // opener keeps the block rendered as CODE, never as broken prose.
+ const content = '```ts\n' + 'const a = 1;\n'.repeat(800); // > 8KB, fence still open
+ const projected = projectTail(content);
+ const kinds = projected.map((l) => l.kind);
+ // All visible rows are code (newest rows; the label row is capped out of
+ // the window by the row budget — covered by the opener-in-window test).
+ expect(kinds).toContain('code');
+ expect(kinds).not.toContain('text');
+ });
+
+ it('never starts the slice mid-line', () => {
+ const longLine = 'word '.repeat(2000); // > 8KB, single line
+ const content = longLine + '\nheader text\n\nmore prose';
+ const projected = projectTail(content);
+ const texts = projected.filter((l) => l.kind === 'text').map((l) => l.text);
+ // The first rendered row must not be a fragment of the long line.
+ for (const text of texts) {
+ expect(text.startsWith('rd ') || text === 'rd').toBe(false);
+ }
+ expect(texts.join('\n')).toContain('header text');
+ });
});
-describe('streaming tail viewport integration', () => {
- it('tail is part of the scroll math, never appended after the window', () => {
+
+describe('streaming tail live-region integration', () => {
+ it('Mercury Code prints finalized rows via <Static>; the tail is a small live region', () => {
const app = src('App.tsx');
- // The tail must be included in the grand total used for viewport math.
- expect(app).toContain('totalWithTail = totalLines + streamTail.length');
- // Rendering must go through the combined range renderer.
- expect(app).toContain('renderMercuryTranscriptRange(transcriptIndex, streamTail');
- // Forbidden pattern: appending tail rows after the viewport slice
- // (overflowed the fixed-height box and clipped bottom rows).
- expect(app).not.toContain('[...visible, ...liveVisibleRows]');
- expect(app).not.toContain('liveVisibleRows');
+ // 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');
+ // 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.
+ expect(app).not.toContain('getViewportWindow(totalWithTail');
+ expect(app).not.toContain('wordmarkOnScreen');
+ // No in-app scroll dispatches left in the TUI (the workspace IDE's
+ // AgentOutputPanel viewport is a separate, fixed-panel scroll and stays).
+ expect(app).not.toContain("'/mc scroll");
+ // Live-region cap in chat surfaces too.
+ expect(app).toContain('Math.min(12, Math.max(3, terminalSize.rows - 14))');
});
-});
+});
\ No newline at end of file
diff --git a/src/web/server.ts b/src/web/server.ts
index 8e6136e7..498a8735 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -224,7 +224,7 @@ process.on('unhandledRejection', (reason: any) => {
const fatal = /already running|EADDRINUSE|registerRuntimeProcess/i.test(message);
if (fatal) {
try {
- process.stderr.write(`\n✗ Mercury cannot start: ${message}\n Stop the other instance with \`mercury stop\` or \`kill <pid>\`.\n`);
+ process.stderr.write(`\n✗ Mercury cannot start: ${message}\n Attach to it with \`mercury attach\`, or stop it with \`mercury stop\` / \`kill <pid>\`.\n`);
} catch { /* stderr gone */ }
process.exit(1);
}