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(mercury-code): render tool calls as transcript blocks

Salman Qureshi5aae3fb11bd0
diff --git a/package-lock.json b/package-lock.json
index ae8bf46f..9c792536 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -34,6 +34,7 @@
"qrcode-terminal": "^0.12.0",
"react": "^18.3.1",
"sql.js": "^1.14.1",
+ "string-width": "^7.2.0",
"undici": "^6.24.1",
"ws": "^8.21.0",
"yaml": "^2.7.0",
@@ -4769,6 +4770,7 @@
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-7.1.2.tgz",
"integrity": "sha512-iOBWFgUX7caIZiuutICxVgX1SdxwAVFFKwt1EvMYYec/NWO5meOJ6K5uQxhrYBdQJne4KxiqZc+KptFOWFSI9w==",
+ "license": "MIT",
"dependencies": {
"ansi-styles": "^6.2.1",
"is-fullwidth-code-point": "^5.0.0"
@@ -4879,6 +4881,7 @@
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",
"integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",
+ "license": "MIT",
"dependencies": {
"emoji-regex": "^10.3.0",
"get-east-asian-width": "^1.0.0",
@@ -6037,6 +6040,7 @@
"version": "9.0.2",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",
"integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",
+ "license": "MIT",
"dependencies": {
"ansi-styles": "^6.2.1",
"string-width": "^7.0.0",
diff --git a/package.json b/package.json
index c676baca..30f01ee3 100644
--- a/package.json
+++ b/package.json
@@ -81,11 +81,12 @@
"marked": "^14.1.4",
"node-cron": "^3.0.3",
"ollama-ai-provider": "^1.2.0",
- "pino": "^10.3.1",
"patch-package": "^8.0.1",
+ "pino": "^10.3.1",
"qrcode-terminal": "^0.12.0",
"react": "^18.3.1",
"sql.js": "^1.14.1",
+ "string-width": "^7.2.0",
"undici": "^6.24.1",
"ws": "^8.21.0",
"yaml": "^2.7.0",
diff --git a/src/channels/cli-live-activity.test.ts b/src/channels/cli-live-activity.test.ts
index 47523bcf..87381868 100644
--- a/src/channels/cli-live-activity.test.ts
+++ b/src/channels/cli-live-activity.test.ts
@@ -86,4 +86,103 @@ describe('CLIChannel live activity feedback', () => {
expect(channel.getTuiState().liveActivity).toBeNull();
expect(channel.getTuiState().isThinking).toBe(false);
});
-});
\ No newline at end of file
+});
+describe('CLIChannel Mercury Code tool transcript', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ async function* chunks(parts: Array<string | (() => Promise<void>)>): AsyncIterable<string> {
+ for (const part of parts) {
+ if (typeof part === 'string') yield part;
+ else await part();
+ }
+ }
+
+ it('interleaves streamed text and finished tool blocks in order', async () => {
+ vi.spyOn(process.stdout, 'write').mockImplementation((() => true) as typeof process.stdout.write);
+ const channel = new CLIChannel();
+ channel.enterMercuryCode(process.cwd(), 'test');
+ const before = channel.getTuiState().chatMessages.length;
+
+ const full = await channel.stream(chunks([
+ 'Let me read the file.',
+ async () => {
+ // The SDK fires tool start/finish between the model's steps.
+ await channel.sendToolEvent('read_file', { path: 'a.ts' }, 'call-1');
+ channel.completeToolEvent('read_file', 'x\ny', false, 10, 'call-1');
+ },
+ '\n\n',
+ 'Done reading.',
+ ]));
+
+ const added = channel.getTuiState().chatMessages.slice(before);
+ expect(added.map((m) => m.tool ? `tool:${m.tool.title}` : `${m.role}:${m.content}`)).toEqual([
+ 'agent:Let me read the file.',
+ 'tool:Read',
+ 'agent:Done reading.',
+ ]);
+ expect(added.every((m) => !m.streaming)).toBe(true);
+ // The caller still receives the whole reply for the session store.
+ expect(full).toBe('Let me read the file.\n\nDone reading.');
+ });
+
+ it('completes parallel calls of the same tool by callId', async () => {
+ vi.spyOn(process.stdout, 'write').mockImplementation((() => true) as typeof process.stdout.write);
+ const channel = new CLIChannel();
+ channel.enterMercuryCode(process.cwd(), 'test');
+ await channel.sendToolEvent('read_file', { path: 'first.ts' }, 'c1');
+ await channel.sendToolEvent('read_file', { path: 'second.ts' }, 'c2');
+ channel.completeToolEvent('read_file', 'one line', false, 5, 'c2');
+ const blocks = channel.getTuiState().chatMessages.filter((m) => m.tool);
+ expect(blocks.map((m) => m.tool!.target)).toEqual(['second.ts']);
+ expect(channel.getTuiState().toolSteps.find((s) => s.callId === 'c1')?.status).toBe('running');
+ });
+
+ it('does not add tool blocks or split replies outside Mercury Code', async () => {
+ vi.spyOn(process.stdout, 'write').mockImplementation((() => true) as typeof process.stdout.write);
+ const channel = new CLIChannel();
+ await channel.stream(chunks([
+ 'Before.',
+ async () => {
+ await channel.sendToolEvent('read_file', { path: 'a.ts' }, 'call-1');
+ channel.completeToolEvent('read_file', 'x', false, 10, 'call-1');
+ },
+ ' After.',
+ ]));
+ const messages = channel.getTuiState().chatMessages;
+ expect(messages.some((m) => m.tool)).toBe(false);
+ expect(messages.filter((m) => m.role === 'agent').map((m) => m.content)).toEqual(['Before. After.']);
+ });
+});
+
+describe('CLIChannel tool output expansion', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('ctrl+o appends the full output of collapsed blocks, newest first', async () => {
+ vi.spyOn(process.stdout, 'write').mockImplementation((() => true) as typeof process.stdout.write);
+ const channel = new CLIChannel();
+ channel.enterMercuryCode(process.cwd(), 'test');
+ const lines = (tag: string) => Array.from({ length: 30 }, (_, i) => `${tag} ${i}`).join('\n');
+ await channel.sendToolEvent('run_command', { command: 'first' }, 'c1');
+ channel.completeToolEvent('run_command', lines('a'), false, 5, 'c1');
+ await channel.sendToolEvent('run_command', { command: 'small' }, 'c2');
+ channel.completeToolEvent('run_command', 'tiny', false, 5, 'c2');
+ await channel.sendToolEvent('run_command', { command: 'second' }, 'c3');
+ channel.completeToolEvent('run_command', lines('b'), false, 5, 'c3');
+
+ const lastTool = () => channel.getTuiState().chatMessages.filter((m) => m.tool).at(-1)!.tool!;
+ channel.expandLastToolOutput();
+ expect(lastTool()).toMatchObject({ target: 'second', summary: 'Full output · 30 lines' });
+ expect(lastTool().body!.lines).toHaveLength(30);
+ channel.expandLastToolOutput();
+ expect(lastTool().target).toBe('first');
+ // Nothing left: a notice, not a block.
+ const toolCount = channel.getTuiState().chatMessages.filter((m) => m.tool).length;
+ channel.expandLastToolOutput();
+ expect(channel.getTuiState().chatMessages.filter((m) => m.tool)).toHaveLength(toolCount);
+ expect(channel.getTuiState().chatMessages.at(-1)?.content).toContain('Nothing to expand');
+ });
+});
diff --git a/src/channels/cli.ts b/src/channels/cli.ts
index 966cce65..1c9e163c 100644
--- a/src/channels/cli.ts
+++ b/src/channels/cli.ts
@@ -10,6 +10,7 @@ import { STEPS_PAUSED_BANNER, NO_CHANGES_BANNER } from '../core/completion-verdi
import { logger } from '../utils/logger.js';
import { formatToolStep, formatToolResult } from '../utils/tool-label.js';
import { FILE_CHANGE_TOOLS } from '../utils/file-preview.js';
+import { buildToolBlockDetail, isTranscriptTool, type ToolBlock } from '../ui/tool-block.js';
import type { ChatMessage, CompletionMeta, FileChangeSummary, ToolStep, PermissionPromptState, CurrentSessionInfo, SidebarSection, SkillInfo, SubAgentInfo, ProviderInfo, TokenInfo, SaverInfo, AppMode, WorkspaceState, WorkspaceTreeNode, WorkspaceGitFile, BackgroundTaskInfo, MercuryCodeGitState, MercuryCodeState, LiveActivityState, PlanStep } from '../ui/types.js';
import { TASK_SUMMARY_FILE_LIMIT } from '../ui/types.js';
import { TuiApp } from '../ui/App.js';
@@ -415,6 +416,18 @@ export class CLIChannel extends BaseChannel {
private pendingTurnFiles = new Map<string, string>();
private committedTurnFiles = new Set<string>();
+ // Mercury Code tool transcript: args of running steps (by step id), kept
+ // until completion builds the step's transcript block.
+ private toolArgs = new Map<string, Record<string, any>>();
+ // The agent message currently being streamed. A tool call starting
+ // mid-stream closes it (cutStreamSegment) so the tool's block lands after
+ // the text that preceded it, and later text opens a fresh message.
+ private streamSegment: { id: string; text: string; started: boolean; lastRender: number } | null = null;
+ // Full excerpts of collapsed tool blocks, newest last, for ctrl+o. Bounded:
+ // only the most recent blocks are expandable.
+ private expandableTools: Array<{ block: ToolBlock; full: { lang: string; lines: string[] } }> = [];
+ private static readonly MAX_EXPANDABLE_TOOLS = 20;
+
/** update-notice helpers, imported lazily (a static import would pull
* cli/daemon.js into an import cycle through channels/cli.ts). */
private updateNoticeApiPromise: Promise<any> | null = null;
@@ -822,6 +835,11 @@ export class CLIChannel extends BaseChannel {
else this.update({ mode: 'chat' });
return;
}
+ // View-only: handled here, never sent to the agent.
+ if (trimmed === '/code expand') {
+ this.expandLastToolOutput();
+ return;
+ }
// Instant switch back to regular chat — no exit-confirm dance. The
// confirm exists to guard the Esc-Esc path against accidental exits
// mid-task; an explicit command is deliberate by definition.
@@ -861,6 +879,7 @@ export class CLIChannel extends BaseChannel {
// 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 === 'expand') { this.expandLastToolOutput(); return; }
if (sub === 'esc-arm') {
this.exitEscArmed = true;
// Auto-disarm after 1.5s so Esc-Esc window is bounded.
@@ -1126,7 +1145,8 @@ export class CLIChannel extends BaseChannel {
* when the identical preview is already the last message (tool retries).
*/
showFileChange(content: string): void {
- if (!content) return;
+ // Mercury Code shows the change inside the tool's own transcript block.
+ if (!content || this.state.mode === 'mercury-code') return;
const last = this.state.chatMessages[this.state.chatMessages.length - 1];
if (last && last.role === 'system' && last.content === content) return;
const msg: ChatMessage = {
@@ -1248,6 +1268,10 @@ export class CLIChannel extends BaseChannel {
};
this.stepCount += 1;
this.stepStartTime = Date.now();
+ if (this.showsToolTranscript(toolName)) {
+ this.toolArgs.set(step.id, args ?? {});
+ this.cutStreamSegment();
+ }
// Cap the live step list: long coding sessions can run hundreds of
// tool calls; an unbounded array both bloats renders and memory.
const MAX_LIVE_STEPS = 60;
@@ -1258,18 +1282,57 @@ export class CLIChannel extends BaseChannel {
return Promise.resolve();
}
+ /** Mercury Code records finished tool calls as transcript blocks. */
+ private showsToolTranscript(toolName: string): boolean {
+ return this.state.mode === 'mercury-code' && isTranscriptTool(toolName);
+ }
+
+ /**
+ * Close the agent message being streamed at its current text, and start a
+ * new (not yet visible) segment for whatever streams next. Called when a
+ * tool starts: everything the model said so far precedes the tool's block.
+ */
+ private cutStreamSegment(): void {
+ const seg = this.streamSegment;
+ if (!seg) return;
+ if (seg.started) {
+ const content = this.capStreamDisplay(seg.text.trimEnd(), 'response');
+ const closed = { id: seg.id, role: 'agent' as const, content, timestamp: Date.now(), streaming: false };
+ this.update({ chatMessages: this.state.chatMessages.map((m) => (m.id === seg.id ? closed : m)) });
+ }
+ this.streamSegment = { id: CLIChannel.newMessageId(), text: '', started: false, lastRender: 0 };
+ }
+
+ private static newMessageId(): string {
+ return Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
+ }
+
+ /** Streaming display cap: the complete text still reaches the session store. */
+ private capStreamDisplay(text: string, what: 'stream' | 'response'): string {
+ if (text.length <= CLIChannel.MAX_MESSAGE_CHARS) return text;
+ const kb = Math.round(CLIChannel.MAX_MESSAGE_CHARS / 1024);
+ return text.slice(0, CLIChannel.MAX_MESSAGE_CHARS) + (what === 'stream'
+ ? `\n\n[…stream display truncated at ${kb}KB — full response in transcript]`
+ : `\n\n[…response display truncated at ${kb}KB]`);
+ }
+
/**
* Real-time tool completion: pairs with sendToolEvent via callId so the
* exact step that started flips to done — even when several tools ran.
*/
- completeToolEvent(toolName: string, result: unknown, isError: boolean, durationMs?: number): void {
+ completeToolEvent(toolName: string, result: unknown, isError: boolean, durationMs?: number, callId?: string): void {
const summary = formatToolResult(toolName, result);
let matched = false;
let matchedCallId: string | undefined;
+ let matchedStepId: string | undefined;
+ // Exact callId match first (parallel calls of the same tool), else the
+ // oldest running step of that tool.
+ const byCallId = callId != null && this.state.toolSteps.some((s) => s.status === 'running' && s.callId === callId);
const toolSteps = this.state.toolSteps.map((step) => {
- if (!matched && step.status === 'running' && step.toolName === toolName) {
+ if (!matched && step.status === 'running' && step.toolName === toolName && (!byCallId || step.callId === callId)) {
matched = true;
matchedCallId = step.callId;
+ matchedStepId = step.id;
return {
...step,
status: (isError ? 'error' : 'done') as 'done' | 'error',
@@ -1279,7 +1342,18 @@ export class CLIChannel extends BaseChannel {
}
return step;
});
- this.update({ toolSteps });
+ const args = matchedStepId ? this.toolArgs.get(matchedStepId) : undefined;
+ if (matchedStepId) this.toolArgs.delete(matchedStepId);
+ if (args && this.showsToolTranscript(toolName)) {
+ const { block, full } = buildToolBlockDetail({ toolName, args, result, isError, cwd: this.state.mercuryCode?.cwd });
+ if (full) {
+ this.expandableTools.push({ block, full });
+ if (this.expandableTools.length > CLIChannel.MAX_EXPANDABLE_TOOLS) this.expandableTools.shift();
+ }
+ this.appendToolBlock(block, { toolSteps });
+ } else {
+ this.update({ toolSteps });
+ }
// Attribution commit: a file-tool call that finished successfully actually
// mutated the tree; a failed one did not (errors surface in the step list).
if (matchedCallId) {
@@ -1289,6 +1363,42 @@ export class CLIChannel extends BaseChannel {
}
}
+ /**
+ * ctrl+o: print the full output of the most recent collapsed tool block.
+ * Scrollback can't be re-rendered, so the expansion is appended as a new
+ * block; pressing again walks back to the previous collapsed block.
+ */
+ expandLastToolOutput(): void {
+ const entry = this.expandableTools.pop();
+ if (!entry) {
+ this.sendSystemNotice('Nothing to expand — no collapsed tool output.');
+ return;
+ }
+ const { block, full } = entry;
+ this.appendToolBlock({
+ ...block,
+ summary: `Full output · ${full.lines.length} line${full.lines.length === 1 ? '' : 's'}`,
+ body: full,
+ }, {});
+ }
+
+ /** Append a finished tool call to the transcript (parked while a bot chat is open). */
+ private appendToolBlock(tool: ToolBlock, extra: Partial<TuiState>): void {
+ const msg: ChatMessage = {
+ id: `tool-${CLIChannel.newMessageId()}`,
+ role: 'system',
+ content: `${tool.title}${tool.target ? `(${tool.target})` : ''} — ${tool.summary}`,
+ timestamp: Date.now(),
+ tool,
+ };
+ if (this.activeBotId) {
+ this.mainTranscript = [...(this.mainTranscript ?? []).slice(-CLIChannel.MAX_CHAT_MESSAGES + 1), msg];
+ this.update(extra);
+ return;
+ }
+ this.trimAndSetMessages([...this.state.chatMessages, msg], extra);
+ }
+
sendCompletion(elapsedMs: number, stepCount: number, meta?: CompletionMeta, outcome?: 'complete' | 'steps-paused', verificationNote?: string): void {
this.clearHeartbeat();
this.clearLiveActivity();
@@ -1524,17 +1634,41 @@ export class CLIChannel extends BaseChannel {
];
return parked;
}
- const msgId = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
+ // The reply streams into a SEGMENT: one agent message. In Mercury Code a
+ // tool call starting mid-stream closes the segment (cutStreamSegment) and
+ // later text opens a new one, so text and tool blocks interleave in the
+ // order they happened. `full` stays the whole reply for the caller.
+ const segment = { id: CLIChannel.newMessageId(), text: '', started: false, lastRender: 0 };
+ this.streamSegment = segment;
let full = '';
- let started = false;
- let lastRender = 0;
this.clearHeartbeat();
this.setLiveActivity('Streaming response', 'generating answer');
+ const render = (seg: NonNullable<CLIChannel['streamSegment']>, now: number) => {
+ // Streaming display cap: an unbounded string re-rendered every 60ms
+ // makes each frame allocate a fresh multi-MB message object; a long
+ // code-mode task can then retain gigabytes. The complete text still
+ // reaches the session store via the final channel.send().
+ const streamedMessage = { id: seg.id, role: 'agent' as const, content: this.capStreamDisplay(seg.text, 'stream'), timestamp: now, streaming: true };
+ this.update({
+ chatMessages: seg.started
+ ? this.state.chatMessages.map((message) => message.id === seg.id ? streamedMessage : message)
+ : [...this.state.chatMessages, streamedMessage],
+ isThinking: true,
+ });
+ seg.started = true;
+ seg.lastRender = now;
+ };
+
try {
for await (const chunk of content) {
full += chunk;
+ const seg = this.streamSegment ?? segment;
+ // A segment opens on its first visible text: step separators ("\n\n")
+ // arriving right after a tool call must not open an empty message.
+ seg.text = seg.started ? seg.text + chunk : (seg.text + chunk).replace(/^\s*\n/, '');
+ if (!seg.started && seg.text.trim() === '') continue;
const now = Date.now();
// Throttle streaming re-renders to ~60ms. At 16ms the live Yoga
// tree was being recomputed on nearly every token, which — combined
@@ -1542,60 +1676,43 @@ export class CLIChannel extends BaseChannel {
// render — caused the visible "vibration"/flicker during generation.
// 60ms is fast enough to feel live while keeping each frame's layout
// stable.
- if (!started || now - lastRender >= 60) {
- // Streaming display cap: an unbounded `full` string re-rendered
- // every 60ms makes each frame allocate a fresh multi-MB message
- // object; a long code-mode task can then retain gigabytes. The
- // complete text still reaches the session store via the final
- // channel.send().
- const shown = full.length > CLIChannel.MAX_MESSAGE_CHARS
- ? full.slice(0, CLIChannel.MAX_MESSAGE_CHARS) + `\n\n[…stream display truncated at ${Math.round(CLIChannel.MAX_MESSAGE_CHARS / 1024)}KB — full response in transcript]`
- : full;
- const streamedMessage = { id: msgId, role: 'agent' as const, content: shown, timestamp: now, streaming: true };
- this.update({
- chatMessages: started
- ? this.state.chatMessages.map((message) => message.id === msgId ? streamedMessage : message)
- : [...this.state.chatMessages, streamedMessage],
- isThinking: true,
- });
- started = true;
- lastRender = now;
- }
+ if (!seg.started || now - seg.lastRender >= 60) render(seg, now);
}
} catch (err) {
+ const seg = this.streamSegment ?? segment;
+ this.streamSegment = null;
logger.warn({ err, partialLen: full.length }, 'CLI stream interrupted, saving partial text');
this.clearLiveActivity();
- if (full.length > 0) {
- const interruptedMessage = { id: msgId, role: 'agent' as const, content: full + '\n\n⚠ Stream was interrupted. Partial response shown above.', timestamp: Date.now(), streaming: false };
+ if (seg.text.trim().length > 0) {
+ const interruptedMessage = { id: seg.id, role: 'agent' as const, content: seg.text + '\n\n⚠ Stream was interrupted. Partial response shown above.', timestamp: Date.now(), streaming: false };
this.update({
- chatMessages: started
- ? this.state.chatMessages.map((message) => message.id === msgId ? interruptedMessage : message)
+ chatMessages: seg.started
+ ? this.state.chatMessages.map((message) => message.id === seg.id ? interruptedMessage : message)
: [...this.state.chatMessages, interruptedMessage],
isThinking: false,
});
} else {
this.update({
- chatMessages: [...this.state.chatMessages, { id: msgId, role: 'agent', content: '⚠ Stream was interrupted before any response was generated.', timestamp: Date.now(), streaming: false }],
+ chatMessages: [...this.state.chatMessages, { id: seg.id, role: 'agent', content: full.length > 0 ? '⚠ Stream was interrupted. Partial response shown above.' : '⚠ Stream was interrupted before any response was generated.', timestamp: Date.now(), streaming: false }],
isThinking: false,
});
}
return full;
}
- const shownFull = full.length > CLIChannel.MAX_MESSAGE_CHARS
- ? full.slice(0, CLIChannel.MAX_MESSAGE_CHARS) + `\n\n[…response display truncated at ${Math.round(CLIChannel.MAX_MESSAGE_CHARS / 1024)}KB]`
- : full;
- if (full.length > 0) {
- const finalMessage = { id: msgId, role: 'agent' as const, content: shownFull, timestamp: Date.now(), streaming: false };
+ const seg = this.streamSegment ?? segment;
+ this.streamSegment = null;
+ if (seg.text.trim().length > 0) {
+ const finalMessage = { id: seg.id, role: 'agent' as const, content: this.capStreamDisplay(seg.text, 'response'), timestamp: Date.now(), streaming: false };
this.trimAndSetMessages(
- started
- ? this.state.chatMessages.map((message) => message.id === msgId ? finalMessage : message)
+ seg.started
+ ? this.state.chatMessages.map((message) => message.id === seg.id ? finalMessage : message)
: [...this.state.chatMessages, finalMessage],
{ isThinking: false, liveActivity: null },
);
} else {
- // Zero chunks arrived (e.g. the model returned nothing): render no
- // bubble at all rather than an empty "MERCURY" header.
+ // Nothing visible arrived in this segment (the model returned nothing,
+ // or the reply ended on a tool call): render no empty message.
this.update({ isThinking: false, liveActivity: null });
}
diff --git a/src/core/agent.ts b/src/core/agent.ts
index eaaa5a80..271361d1 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -2239,7 +2239,7 @@ export class Agent {
if (status === 'running') {
void ch.sendToolEvent(toolName, argsOrResult as Record<string, any>, callId).catch(() => {});
} else {
- ch.completeToolEvent(toolName, argsOrResult, status === 'error', durationMs);
+ ch.completeToolEvent(toolName, argsOrResult, status === 'error', durationMs, callId);
}
}
@@ -7085,7 +7085,7 @@ Is this productive iteration or a stuck loop?`,
return true;
}
- await channel.send('Unknown /code command. Available: /code, /code plan, /code execute, /code build, /code init, /code diff, /code workspace, /code agent <task>, /code off, /code toggle, /code exit', channelId);
+ await channel.send('Unknown /code command. Available: /code, /code plan, /code execute, /code build, /code init, /code diff, /code expand, /code workspace, /code agent <task>, /code off, /code toggle, /code exit', channelId);
return true;
}
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index 6770667a..c80b5110 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -6,6 +6,7 @@ import type { AppMode, ChatMessage, ToolStep, SubAgentInfo, PermissionPromptStat
import type { PermissionMode } from '../channels/base.js';
import type { ProgrammingModeState } from '../core/programming-mode.js';
import { renderMarkdown } from '../utils/markdown.js';
+import { IS_LIGHT_TERMINAL } from '../utils/terminal-theme.js';
import { isDevBuild } from '../utils/dev-build.js';
import { highlightCodeBlock } from '../utils/highlight.js';
import { normalizeTerminalText, getViewportWindow } from './terminal-viewport.js';
@@ -40,16 +41,7 @@ const MERCURY_MARK = [
' │ │',
];
-const IS_LIGHT_BG = (() => {
- const fgBg = process.env.COLORFGBG;
- if (!fgBg) return false;
- const parts = fgBg.split(';');
- const bgCode = Number(parts[parts.length - 1]);
- if (Number.isNaN(bgCode)) return false;
- return bgCode >= 10;
-})();
-
-const BRAND = IS_LIGHT_BG
+const BRAND = IS_LIGHT_TERMINAL
? { logo: 'blue', title: 'blue', subtitle: 'gray', accent: 'magenta' }
: { logo: 'cyan', title: 'cyan', subtitle: 'gray', accent: 'magenta' };
@@ -350,6 +342,7 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
if (key.ctrl && (ch === 'p' || ch === 'P')) { onInput('/code plan'); return; }
if (key.ctrl && (ch === 'x' || ch === 'X')) { onInput('/code execute'); return; }
if (key.ctrl && (ch === 'g' || ch === 'G')) { onInput('/code diff'); return; }
+ if (key.ctrl && (ch === 'o' || ch === 'O' || ch === '\x0f')) { onInput('/mc expand'); return; }
// Ctrl+N newline in input
if (key.ctrl && (ch === 'n' || ch === 'N' || ch === '\x0e')) {
@@ -2158,6 +2151,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 expand', 'show full output of the last tool', 'ctrl+o'],
['/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'],
@@ -2188,7 +2182,7 @@ function PlanProgressView({ steps }: { steps: PlanStep[] }): React.ReactNode {
}
if (active) {
rows.push(
- <Box key="active"><Text color="cyan" bold>▶ </Text><Text color="cyan" bold>{active.label}</Text><Text dimColor> ← implementing</Text></Box>,
+ <Box key="active"><Text color={THEME_ACCENT} bold>▶ </Text><Text color={THEME_ACCENT} bold>{active.label}</Text><Text dimColor> ← implementing</Text></Box>,
);
}
const pendingRoom = Math.max(0, MAX_ROWS - rows.length);
@@ -2250,20 +2244,16 @@ export function streamTailRowCap(terminalRows: number): number {
* terminal cyan "MERCURY" contrasts with orange "CODE"; on a light
* background the shades deepen instead of washing out.
*/
-const WORDMARK_LIGHT_BG = (() => {
- const fgBg = process.env.COLORFGBG;
- if (!fgBg) return false;
- const parts = fgBg.split(';');
- const bgCode = Number(parts[parts.length - 1]);
- return !Number.isNaN(bgCode) && bgCode >= 10;
-})();
-
// One solid color per word, background-adaptive. "CODE" is a whitish gray
-// so the cyan "MERCURY" stays the visual anchor on any background.
-const WORDMARK_COLORS = WORDMARK_LIGHT_BG
- ? { mercury: 'blue', code: '#c9cdd1' }
+// on dark (a dark gray on light — whitish would vanish on white) so the
+// "MERCURY" accent stays the visual anchor on any background.
+const WORDMARK_COLORS = IS_LIGHT_TERMINAL
+ ? { mercury: 'blue', code: '#5f6368' }
: { mercury: 'cyanBright', code: '#c9cdd4' };
+/** Accent for the Mercury Code transcript: cyan is faint on a light background. */
+const THEME_ACCENT = IS_LIGHT_TERMINAL ? 'blue' : 'cyan';
+
/** Centered three-column hint block (command · description · key), opencode-style. */
function MercuryCodeHints({ cols }: { cols: number }): React.ReactNode {
const cmdW = Math.max(...CODE_HINTS.map((h) => h[0].length));
@@ -2274,7 +2264,7 @@ function MercuryCodeHints({ cols }: { cols: number }): React.ReactNode {
<Box flexDirection="column" alignItems="flex-start" paddingLeft={indent} marginTop={2}>
{CODE_HINTS.map(([cmd, desc, key]) => (
<Box key={cmd}>
- <Text bold color="cyan">{cmd.padEnd(cmdW)}</Text>
+ <Text bold color={THEME_ACCENT}>{cmd.padEnd(cmdW)}</Text>
<Text> </Text>
<Text dimColor>{desc.padEnd(descW)}</Text>
<Text> </Text>
@@ -2290,11 +2280,12 @@ function MercuryLiveFeedback({ state }: { state: TuiState }): React.ReactNode {
const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
const [frame, setFrame] = React.useState(0);
const [, forceTick] = React.useState(0);
+ // Finished steps are not repeated here: each one is already a block in
+ // the transcript above (tool-block.ts). Only live work shows.
const running = [...state.toolSteps].reverse().find((s) => s.status === 'running');
- const doneRecently = state.toolSteps.filter((s) => s.status === 'done').slice(-2);
const activeAgents = state.subAgents.filter((a) => a.status === 'running' || a.status === 'paused');
const activity = state.liveActivity;
- const active = Boolean(running || state.isThinking || doneRecently.length > 0 || activeAgents.length > 0 || activity);
+ const active = Boolean(running || state.isThinking || 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
@@ -2367,9 +2358,9 @@ function MercuryLiveFeedback({ state }: { state: TuiState }): React.ReactNode {
<Box flexDirection="column" paddingX={2} flexShrink={0}>
{phase && (
<Box>
- <Text color="cyan">{frames[frame]}</Text>
+ <Text color={THEME_ACCENT}>{frames[frame]}</Text>
<Text> </Text>
- <Text color="cyan" bold>{phase}</Text>
+ <Text color={THEME_ACCENT} bold>{phase}</Text>
{stepsDone > 0 && <Text dimColor> · step {stepsDone}</Text>}
<Text dimColor> · {timeStr}</Text>
{detail && <Text dimColor> — {detail}</Text>}
@@ -2384,12 +2375,6 @@ function MercuryLiveFeedback({ state }: { state: TuiState }): React.ReactNode {
{running.startedAt && <Text dimColor> ({Math.max(0, (Date.now() - running.startedAt) / 1000).toFixed(0)}s)</Text>}
</Box>
)}
- {doneRecently.map((step) => (
- <Box key={step.id} paddingLeft={2}>
- <Text color="green">✓</Text>
- <Text dimColor> {step.label}{step.elapsed != null ? ` (${step.elapsed.toFixed(1)}s)` : ''}</Text>
- </Box>
- ))}
{!running && state.thinkingPreview && (
<Box paddingLeft={2}>
<Text dimColor> “{state.thinkingPreview.slice(-120)}”</Text>
@@ -2419,7 +2404,7 @@ function MercuryLiveFeedback({ state }: { state: TuiState }): React.ReactNode {
/** Bordered input box (opencode-style) with mode-tinted prompt. */
function MercuryCodeInput({ input, cursorPos, mode, boxWidth }: { input: string; cursorPos: number; mode: ProgrammingModeState; boxWidth: number }) {
- const color = mode === 'execute' ? 'green' : mode === 'plan' ? 'yellow' : 'cyan';
+ const color = mode === 'execute' ? 'green' : mode === 'plan' ? 'yellow' : THEME_ACCENT;
const lines = input.split('\n');
let cursorLine = 0;
let cursorCol = cursorPos;
@@ -2474,13 +2459,7 @@ function MercuryCodeExitConfirm({ boxWidth }: { boxWidth: number }): React.React
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, streaming }: { line: MercuryTranscriptLine; streaming?: boolean }): React.ReactNode {
- const roleColor = line.role === 'user' ? 'yellow' : line.role === 'agent' ? 'cyan' : 'gray';
- // The `│` rule is the settled-transcript look. While a message is still
- // streaming, its live tail omits the rule — partial markdown re-parses
- // every frame there, and the rule made those glitches visible. The same
- // rows gain the rule automatically once they settle into <Static>.
- const rule = streaming ? null : <Text color={roleColor}>│ </Text>;
+function MercuryTranscriptRow({ line }: { line: MercuryTranscriptLine }): React.ReactNode {
if (line.kind === 'brand') {
// Indent is baked into the text for exact centering.
return (
@@ -2491,7 +2470,7 @@ function MercuryTranscriptRow({ line, streaming }: { line: MercuryTranscriptLine
<Text bold color={WORDMARK_COLORS.code}>{line.accent}</Text>
</>
) : (
- <Text bold color="cyan">{line.text}</Text>
+ <Text bold color={THEME_ACCENT}>{line.text}</Text>
)}
</Box>
);
@@ -2499,46 +2478,75 @@ function MercuryTranscriptRow({ line, streaming }: { line: MercuryTranscriptLine
if (line.kind === 'spacer') {
return <Box paddingX={2}><Text> </Text></Box>;
}
- if (line.kind === 'header') {
+ if (line.kind === 'system') {
+ const complete = line.text.startsWith('Task complete');
return (
<Box paddingX={2}>
- <Text bold color={roleColor}>● {line.text}</Text>
+ <Text color={complete ? 'green' : 'gray'} bold={complete}>─ {line.text || ' '}</Text>
</Box>
);
}
- if (line.kind === 'code-label') {
+ if (line.kind === 'file') {
return (
<Box paddingX={2}>
- {rule}<Text dimColor>┌─ {line.text}</Text>
+ <Text color="green"> ↳ </Text><Text>{line.text}</Text>
</Box>
);
}
- if (line.kind === 'code') {
- const highlighted = highlightCodeBlock(line.text, line.lang)[0] ?? line.text;
+ if (line.kind === 'tool-head') {
return (
<Box paddingX={2}>
- {rule}<Text>{highlighted || ' '}</Text>
+ <Text color={line.status === 'error' ? 'red' : 'green'}>● </Text>
+ <Text bold>{line.text}</Text>
+ {line.accent ? <Text>({line.accent})</Text> : null}
</Box>
);
}
- if (line.kind === 'system') {
- const complete = line.text.startsWith('Task complete');
+ if (line.kind === 'tool-out') {
+ const body = line.lang === 'plan'
+ ? line.text.startsWith('☒')
+ ? <Text color="green" dimColor>{line.text}</Text>
+ : line.text.startsWith('▶')
+ ? <Text color={THEME_ACCENT} bold>{line.text}</Text>
+ : <Text dimColor>{line.text}</Text>
+ : line.lang
+ ? <Text>{highlightCodeBlock(line.text, line.lang)[0] ?? line.text}</Text>
+ : <Text color={line.elbow && line.status === 'error' ? 'red' : undefined} dimColor={!(line.elbow && line.status === 'error')}>{line.text || ' '}</Text>;
return (
<Box paddingX={2}>
- <Text color={complete ? 'green' : 'gray'} bold={complete}>─ {line.text || ' '}</Text>
+ {/* gray, not dimColor: dim and bold share SGR reset 22, and ink's
+ style merging let the indent's dim bleed into a bold row. */}
+ <Text color="gray">{line.elbow ? ' ⎿ ' : ' '}</Text>
+ {body}
</Box>
);
}
- if (line.kind === 'file') {
+ // Two-column gutter: the role marker on a message's first row, blank
+ // otherwise. It is identical while streaming and once settled, so rows
+ // never shift sideways when they move into scrollback.
+ const gutter = line.lead === 'agent'
+ ? <Text color={THEME_ACCENT}>● </Text>
+ : line.lead === 'user'
+ ? <Text color="gray" bold>{'> '}</Text>
+ : <Text>{' '}</Text>;
+ if (line.kind === 'code-label') {
return (
<Box paddingX={2}>
- <Text color="green"> ↳ </Text><Text>{line.text}</Text>
+ {gutter}<Text dimColor>{line.text}</Text>
+ </Box>
+ );
+ }
+ if (line.kind === 'code') {
+ const highlighted = highlightCodeBlock(line.text, line.lang)[0] ?? line.text;
+ return (
+ <Box paddingX={2}>
+ {gutter}<Text>{' '}{highlighted || ' '}</Text>
</Box>
);
}
return (
<Box paddingX={2}>
- {rule}<Text>{line.text || ' '}</Text>
+ {gutter}<Text color={line.role === 'user' ? 'gray' : undefined}>{line.text || ' '}</Text>
</Box>
);
}
@@ -2648,7 +2656,8 @@ export function MercuryCodeView({
// have already joined <Static> above); the 32KB fence-aligned slice
// stays as the safety net for a huge in-progress block.
const remainderMessage = { ...streamingMessage, content: streamingMessage.content.slice(streamingChunks.remainderStart) };
- const lines = buildStreamTailLines(remainderMessage, contentWidth, STREAM_TAIL_CHARS, tailCap);
+ // Role marker only while the remainder is still the message's first block.
+ const lines = buildStreamTailLines(remainderMessage, contentWidth, STREAM_TAIL_CHARS, tailCap, { showHeader: streamingChunks.remainderStart === 0 });
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
@@ -2694,7 +2703,7 @@ export function MercuryCodeView({
const modeLabel = mode === 'execute' ? 'EXECUTE' : mode === 'plan' ? 'PLAN' : mode === 'auto' ? 'AUTO' : 'CHAT';
const git = mc.git;
const hasGit = git.branch !== 'no-git' && git.branch !== 'not-a-git-repo';
- const rightSegs: Array<{ text: string; color: string }> = [{ text: mc.dirName, color: 'cyan' }];
+ const rightSegs: Array<{ text: string; color: string }> = [{ text: mc.dirName, color: THEME_ACCENT }];
if (hasGit) {
const gitBits = [`⎇ ${git.branch}`];
if (git.ahead > 0) gitBits.push(`↑${git.ahead}`);
@@ -2702,7 +2711,7 @@ export function MercuryCodeView({
if (git.dirty > 0) gitBits.push(`±${git.dirty}`);
rightSegs.push({ text: gitBits.join(' '), color: 'blue' });
}
- rightSegs.push({ text: modeLabel, color: mode === 'execute' ? 'green' : mode === 'plan' ? 'yellow' : 'cyan' });
+ rightSegs.push({ text: modeLabel, color: mode === 'execute' ? 'green' : mode === 'plan' ? 'yellow' : THEME_ACCENT });
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).
@@ -2739,7 +2748,7 @@ export function MercuryCodeView({
</Static>
{streamTailRows.length > 0 && (
<Box flexDirection="column" flexShrink={0}>
- {streamTailRows.map((line) => <MercuryTranscriptRow key={line.key} line={line} streaming />)}
+ {streamTailRows.map((line) => <MercuryTranscriptRow key={line.key} line={line} />)}
</Box>
)}
{showHints && <MercuryCodeHints cols={cols} />}
diff --git a/src/ui/mercury-transcript.test.ts b/src/ui/mercury-transcript.test.ts
index 08cdb2af..25cfbbe2 100644
--- a/src/ui/mercury-transcript.test.ts
+++ b/src/ui/mercury-transcript.test.ts
@@ -1,4 +1,5 @@
-import { describe, expect, it } from 'vitest';
+import { beforeAll, describe, expect, it } from 'vitest';
+import chalk from 'chalk';
import type { ChatMessage } from './types.js';
import {
buildMercuryBrandLines,
@@ -7,7 +8,9 @@ import {
settledChunkEnds,
splitFinalMessage,
splitStreamingMessage,
+ stripTerminalAnsi,
wrapMercuryText,
+ wrapStyledLine,
} from './mercury-transcript.js';
function message(partial: Partial<ChatMessage> = {}): ChatMessage {
@@ -21,6 +24,9 @@ function message(partial: Partial<ChatMessage> = {}): ChatMessage {
}
describe('Mercury Code transcript formatting', () => {
+ // Test runs have no TTY, so chalk would emit no styling at all.
+ beforeAll(() => { chalk.level = 1; });
+
it('wraps long text without dropping any words', () => {
const source = 'Every part of this response remains visible even on a narrow terminal';
const wrapped = wrapMercuryText(source, 20);
@@ -30,19 +36,71 @@ describe('Mercury Code transcript formatting', () => {
expect(wrapped.every((line) => line.length <= 20)).toBe(true);
});
- it('categorizes user and agent messages with explicit headers', () => {
+ it('marks the first row of user and agent messages with the role', () => {
const user = buildMercuryMessageLines(message({ role: 'user', content: 'Please update the parser.' }), 60);
const agent = buildMercuryMessageLines(message({ id: 'msg-2', content: 'I updated the parser.' }), 60);
- expect(user[0]).toMatchObject({ kind: 'header', text: 'YOU', role: 'user' });
- expect(agent[0]).toMatchObject({ kind: 'header', text: 'MERCURY', role: 'agent' });
+ expect(user[0]).toMatchObject({ kind: 'text', text: 'Please update the parser.', lead: 'user' });
+ expect(agent[0]).toMatchObject({ kind: 'text', text: 'I updated the parser.', lead: 'agent' });
+ expect([...user, ...agent].filter((l) => l.lead)).toHaveLength(2);
+ });
+
+ it('keeps markdown styling on agent rows and leaves user input as typed', () => {
+ const agent = buildMercuryMessageLines(message({ content: 'This is **bold** and `code`.' }), 60);
+ expect(agent[0].text).toMatch(/\x1b\[/);
+ expect(stripTerminalAnsi(agent[0].text)).toBe('This is bold and code.');
+
+ const user = buildMercuryMessageLines(message({ role: 'user', content: 'keep **stars**' }), 60);
+ expect(user[0].text).toBe('keep **stars**');
+ });
+
+ it('strips escape sequences that arrive in model output', () => {
+ const lines = buildMercuryMessageLines(message({ content: 'safe\x1b]0;pwned\x07 \x1b[2Jtext' }), 60);
+ expect(lines.map((l) => stripTerminalAnsi(l.text)).join('')).not.toMatch(/pwned|\x07/);
+ expect(lines.some((l) => l.text.includes('\x1b[2J'))).toBe(false);
+ });
+
+ it('wraps styled rows by visible width with a hanging indent', () => {
+ const rows = wrapStyledLine(` \x1b[2m•\x1b[22m ${'\x1b[1mword\x1b[22m '.repeat(12)}`, 30);
+ expect(rows.length).toBeGreaterThan(1);
+ for (const row of rows) expect(stripTerminalAnsi(row).length).toBeLessThanOrEqual(30);
+ for (const row of rows.slice(1)) expect(stripTerminalAnsi(row).startsWith(' ')).toBe(true);
+ });
+
+ it('reopens styles on every row when a styled span crosses a wrap', () => {
+ const bold = `\x1b[1m${'alpha beta gamma delta epsilon zeta eta theta'}\x1b[22m tail`;
+ const rows = wrapStyledLine(bold, 20);
+ expect(rows.length).toBeGreaterThan(1);
+ for (const row of rows.slice(0, -1)) {
+ expect(row.startsWith('\x1b[1m')).toBe(true);
+ expect(row.endsWith('\x1b[0m')).toBe(true);
+ }
+ expect(rows.map(stripTerminalAnsi).join(' ')).toBe('alpha beta gamma delta epsilon zeta eta theta tail');
+ });
+
+ it('measures wide characters by terminal columns', () => {
+ const rows = wrapStyledLine('漢字'.repeat(20), 20);
+ for (const row of rows) expect(row.length * 2).toBeLessThanOrEqual(20);
+ expect(rows.join('')).toBe('漢字'.repeat(20));
+ });
+
+ it('repeats the blockquote rule on continuation rows', () => {
+ const rows = wrapStyledLine(`\x1b[2m│ \x1b[22m${'quoted words here '.repeat(4).trim()}`, 24);
+ expect(rows.length).toBeGreaterThan(1);
+ for (const row of rows) expect(stripTerminalAnsi(row).startsWith('│ ')).toBe(true);
+ });
+
+ it('starts a message at its first visible row even when it opens with a heading', () => {
+ const lines = buildMercuryMessageLines(message({ content: '# Title\n\nbody' }), 60);
+ expect(stripTerminalAnsi(lines[0].text)).toBe('Title');
+ expect(lines[0].lead).toBe('agent');
});
it('keeps fenced code structured for syntax highlighting', () => {
const lines = buildMercuryMessageLines(message({ content: 'Use this:\n```ts\nconst answer = 42;\n```' }), 60);
expect(lines).toEqual(expect.arrayContaining([
- expect.objectContaining({ kind: 'code-label', text: 'TS', lang: 'ts' }),
+ expect.objectContaining({ kind: 'code-label', text: 'ts', lang: 'ts' }),
expect.objectContaining({ kind: 'code', text: 'const answer = 42;', lang: 'ts' }),
]));
});
@@ -156,16 +214,16 @@ describe('settled-chunk splitter (progressive streaming flush)', () => {
expect(chunks[chunks.length - 1].fileChanges).toEqual(fileChanges);
});
- it('renders the role header only on chunk 0', () => {
+ it('renders the role marker only on chunk 0', () => {
const chunks = splitFinalMessage(chunkMessage(FULL));
expect(chunks.length).toBeGreaterThan(1);
- expect(buildMercuryMessageLines(chunks[0], 76).some((l) => l.kind === 'header')).toBe(true);
+ expect(buildMercuryMessageLines(chunks[0], 76).some((l) => l.lead === 'agent')).toBe(true);
for (const chunk of chunks.slice(1)) {
- expect(buildMercuryMessageLines(chunk, 76, { showHeader: false }).some((l) => l.kind === 'header')).toBe(false);
+ expect(buildMercuryMessageLines(chunk, 76, { showHeader: false }).some((l) => l.lead)).toBe(false);
}
- // Whole messages (no #c id) keep the header.
+ // Whole messages (no #c id) keep the marker.
expect(parseChunkIndex('m1')).toBeNull();
- expect(buildMercuryMessageLines(chunkMessage('hello'), 76).some((l) => l.kind === 'header')).toBe(true);
+ expect(buildMercuryMessageLines(chunkMessage('hello'), 76).some((l) => l.lead === 'agent')).toBe(true);
});
it('degenerate inputs: short and empty messages produce exactly one chunk', () => {
diff --git a/src/ui/mercury-transcript.ts b/src/ui/mercury-transcript.ts
index 600e9ad2..68e3f43e 100644
--- a/src/ui/mercury-transcript.ts
+++ b/src/ui/mercury-transcript.ts
@@ -4,8 +4,12 @@ import { normalizeTerminalText } from './terminal-viewport.js';
import { renderMarkdown } from '../utils/markdown.js';
import { devBuildLabel, isDevBuild } from '../utils/dev-build.js';
import { renderMercuryCodeParts } from './pixel-logo.js';
+import stringWidth from 'string-width';
-export type MercuryTranscriptKind = 'header' | 'text' | 'code-label' | 'code' | 'system' | 'file' | 'spacer' | 'brand';
+export type MercuryTranscriptKind = 'text' | 'code-label' | 'code' | 'system' | 'file' | 'spacer' | 'brand' | 'tool-head' | 'tool-out';
+
+/** Gutter marker on a message's first row: `●` for the agent, `>` for the user. */
+export type MercuryTranscriptLead = 'agent' | 'user';
export interface MercuryTranscriptLine {
key: string;
@@ -15,6 +19,12 @@ export interface MercuryTranscriptLine {
lang?: string;
/** Secondary colored segment for brand rows (the "CODE" wordmark part). */
accent?: string;
+ /** Set on the first row of a message: the gutter shows the role marker. */
+ lead?: MercuryTranscriptLead;
+ /** Tool rows: outcome color for the head marker and summary. */
+ status?: 'done' | 'error';
+ /** First tool-out row of a block: drawn with the ⎿ elbow. */
+ elbow?: boolean;
}
// Chalk output is useful elsewhere, but wrapping must operate on visible text.
@@ -39,9 +49,144 @@ export function wrapMercuryText(text: string, width: number): string[] {
return lines;
}
+// Control characters other than newline/tab. Model output is untrusted: raw
+// escape sequences in it must never reach the terminal — only the styling
+// renderMarkdown adds itself survives.
+const CONTROL_RE = /[\x00-\x08\x0b-\x1f\x7f-\x9f]/g;
+
+// OSC sequences (titles, hyperlinks, clipboard): ESC ] … terminated by BEL or ST.
+const OSC_RE = /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?/g;
+
+export function sanitizeTerminalText(text: string): string {
+ return stripTerminalAnsi(text.replace(OSC_RE, '')).replace(CONTROL_RE, '');
+}
+
+// Visible prefix that continuation rows of a wrapped line should hang under:
+// list bullets / numbers, blockquote rules, or plain leading indentation.
+const HANGING_PREFIX_RE = /^(\s*(?:[•\-*]|\d+\.|│)\s+|\s+)(?=\S)/;
+const SGR_RE = /\x1b\[([0-9;]*)m/g;
+// SGR open code → the code that closes it (bold and dim share 22).
+const SGR_CLOSERS: Record<string, string> = { 1: '22', 2: '22', 3: '23', 4: '24', 7: '27', 9: '29' };
+
+function sgrCloser(code: string): string | undefined {
+ const n = Number(code.split(';')[0]);
+ if ((n >= 30 && n <= 38) || (n >= 90 && n <= 97)) return '39';
+ if ((n >= 40 && n <= 48) || (n >= 100 && n <= 107)) return '49';
+ return SGR_CLOSERS[code];
+}
+
+/** Replay SGR codes onto the active-style list (open codes, oldest first). */
+function applySgr(active: string[], code: string): void {
+ if (code === '' || code === '0') {
+ active.length = 0;
+ return;
+ }
+ const closesSomething = active.some((open) => sgrCloser(open) === code);
+ if (closesSomething) {
+ for (let i = active.length - 1; i >= 0; i--) if (sgrCloser(active[i]) === code) active.splice(i, 1);
+ return;
+ }
+ active.push(code);
+}
+
+/**
+ * Greedy word-wrap over plain text: row ranges [start, end). Rows after the
+ * first get `width - indent` columns. Pure-ASCII text (the common case) skips
+ * per-character width lookups entirely.
+ */
+function wrapRanges(plain: string, width: number, indent: number): Array<[number, number]> {
+ const n = plain.length;
+ const ascii = !/[^\x20-\x7e]/.test(plain);
+ const widthAt = (i: number): number => {
+ if (ascii) return 1;
+ const code = plain.codePointAt(i)!;
+ return code < 0x300 ? 1 : stringWidth(String.fromCodePoint(code));
+ };
+ const unitAt = (i: number): number => (plain.codePointAt(i)! > 0xffff ? 2 : 1);
+ const ranges: Array<[number, number]> = [];
+ let i = 0;
+ while (i < n) {
+ const limit = ranges.length === 0 ? width : width - indent;
+ let col = 0;
+ let j = i;
+ let lastSpace = -1;
+ while (j < n) {
+ const w = widthAt(j);
+ if (col + w > limit) break;
+ if (plain[j] === ' ') lastSpace = j;
+ col += w;
+ j += unitAt(j);
+ }
+ if (j >= n) {
+ ranges.push([i, n]);
+ break;
+ }
+ // Break at a space when there is one in reach; hard-break long words.
+ let end = plain[j] === ' ' ? j : lastSpace > i ? lastSpace : j;
+ if (end === i) end = i + unitAt(i); // a single glyph wider than the row
+ let trimmed = end;
+ while (trimmed > i && plain[trimmed - 1] === ' ') trimmed--;
+ ranges.push([i, trimmed]);
+ i = end;
+ while (i < n && plain[i] === ' ') i++;
+ }
+ return ranges;
+}
+
+/**
+ * Wrap one styled (SGR) line to `width` visible columns. Breaks are computed
+ * on the plain text and mapped back onto the styled string; each row reopens
+ * the styles active at its start and resets at its end, so every row renders
+ * correctly on its own. Continuation rows hang under the line's bullet/indent
+ * (blockquotes repeat their rule). Hot path: runs per frame on the live tail.
+ */
+export function wrapStyledLine(line: string, width: number): string[] {
+ const limit = Math.max(12, width);
+ // plainPos[k] = index in `line` of plain char k; codes = SGR runs in order.
+ const plainPos: number[] = [];
+ const codes: Array<{ at: number; code: string }> = [];
+ let plain = '';
+ let last = 0;
+ SGR_RE.lastIndex = 0;
+ for (let m = SGR_RE.exec(line); m; m = SGR_RE.exec(line)) {
+ for (let k = last; k < m.index; k++) plainPos.push(k);
+ plain += line.slice(last, m.index);
+ codes.push({ at: m.index, code: m[1] });
+ last = m.index + m[0].length;
+ }
+ for (let k = last; k < line.length; k++) plainPos.push(k);
+ plain += line.slice(last);
+ if (plain.length === 0) return [''];
+
+ const prefixMatch = HANGING_PREFIX_RE.exec(plain);
+ const indent = prefixMatch && prefixMatch[1].length < limit / 2 ? prefixMatch[1].length : 0;
+ const ranges = wrapRanges(plain, limit, indent);
+ if (ranges.length === 1 && codes.length === 0) return [plain.slice(ranges[0][0], ranges[0][1])];
+
+ const active: string[] = [];
+ let codeIdx = 0;
+ const advanceTo = (pos: number) => {
+ while (codeIdx < codes.length && codes[codeIdx].at < pos) applySgr(active, codes[codeIdx++].code);
+ };
+ const reopen = () => active.map((c) => `\x1b[${c}m`).join('');
+ const slice = (a: number, b: number): string => {
+ const from = plainPos[a];
+ const to = b < plain.length ? plainPos[b] : line.length;
+ advanceTo(from);
+ const open = reopen();
+ advanceTo(to);
+ return open + line.slice(from, to) + (active.length > 0 ? '\x1b[0m' : '');
+ };
+ // Blockquotes repeat their styled rule; everything else hangs on spaces.
+ const continuation = plain.trimStart().startsWith('│') ? slice(0, indent) : ' '.repeat(indent);
+ codeIdx = 0;
+ active.length = 0;
+ return ranges.map(([a, b], i) => (i === 0 ? '' : continuation) + slice(a, b));
+}
+
function renderedTextLines(markdown: string, width: number): string[] {
- const rendered = stripTerminalAnsi(renderMarkdown(markdown));
- return rendered.split('\n').flatMap((line) => wrapMercuryText(line, width));
+ const rendered = renderMarkdown(sanitizeTerminalText(markdown));
+ return rendered.split('\n').flatMap((line) => wrapStyledLine(line, width));
}
/**
@@ -103,6 +248,7 @@ export function buildStreamTailLines(
width: number,
tailChars = 32 * 1024,
maxLines = 48,
+ options?: MessageLinesOptions,
): MercuryTranscriptLine[] {
const content = message.content;
if (content.length === 0) return [];
@@ -124,16 +270,14 @@ export function buildStreamTailLines(
if (opener >= 0) start = windowStart + 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;
+ // A sliced tail is never the start of the message: no role marker.
+ const lines = buildMercuryMessageLines(tailMessage, width, start > 0 ? { showHeader: false } : options);
+ // Newest rows win when the block outgrows the row cap.
+ return lines.length > maxLines ? lines.slice(-maxLines) : lines;
}
export interface MessageLinesOptions {
- /** Render the MERCURY/YOU role header row. False for continuation chunks. */
+ /** Mark the first row with the role marker. False for continuation chunks. */
showHeader?: boolean;
}
@@ -259,12 +403,50 @@ export function parseChunkIndex(id: string): number | null {
return match ? parseInt(match[1], 10) : null;
}
+/** Columns taken by the ⎿ elbow / continuation indent of tool output rows. */
+export const TOOL_OUT_INDENT = 5;
+
+function truncateColumns(text: string, width: number): string {
+ if (stringWidth(text) <= width) return text;
+ let out = '';
+ for (const ch of text) {
+ if (stringWidth(out + ch) > width - 1) break;
+ out += ch;
+ }
+ return `${out}…`;
+}
+
+/** Rows of a finished tool call: `● Title(target)`, the ⎿ summary, then the
+ * excerpt. Output rows are truncated, not wrapped — a block stays compact. */
+function buildToolLines(message: ChatMessage, width: number): MercuryTranscriptLine[] {
+ const tool = message.tool!;
+ const lines: MercuryTranscriptLine[] = [];
+ let index = 0;
+ const push = (line: Omit<MercuryTranscriptLine, 'key' | 'role'>) => {
+ lines.push({ key: `${message.id}:${index++}`, role: message.role, ...line });
+ };
+ const target = sanitizeTerminalText(tool.target);
+ const headWidth = Math.max(12, width - 2 - stringWidth(tool.title) - 2);
+ push({ kind: 'tool-head', text: tool.title, accent: target ? truncateColumns(target, headWidth) : '', status: tool.status });
+ const outWidth = Math.max(12, width - TOOL_OUT_INDENT);
+ push({ kind: 'tool-out', text: truncateColumns(sanitizeTerminalText(tool.summary), outWidth), status: tool.status, elbow: true });
+ for (const row of tool.body?.lines ?? []) {
+ const clean = sanitizeTerminalText(row).replace(/\t/g, ' ');
+ // "… +N lines" markers are prose, not code — never highlight them.
+ const marker = /^… /.test(clean);
+ push({ kind: 'tool-out', text: truncateColumns(clean, outWidth), lang: marker ? undefined : tool.body!.lang || undefined, status: tool.status });
+ }
+ push({ kind: 'spacer', text: '' });
+ return lines;
+}
+
export function buildMercuryMessageLines(
message: ChatMessage,
width: number,
options?: MessageLinesOptions,
): MercuryTranscriptLine[] {
if (message.id.startsWith('heartbeat-')) return [];
+ if (message.tool) return buildToolLines(message, Math.max(12, width - 4));
const contentWidth = Math.max(12, width - 4);
const lines: MercuryTranscriptLine[] = [];
let index = 0;
@@ -297,12 +479,12 @@ export function buildMercuryMessageLines(
flushProse();
inCode = true;
language = fence[1] || 'text';
- push('code-label', language.toUpperCase(), language);
+ push('code-label', language, language);
}
continue;
}
if (inCode) {
- const chunks = wrapMercuryText(sourceLine, contentWidth);
+ const chunks = wrapMercuryText(sanitizeTerminalText(sourceLine), contentWidth);
for (const chunk of chunks) push('code', chunk, language);
} else {
prose.push(sourceLine);
@@ -310,7 +492,6 @@ export function buildMercuryMessageLines(
}
flushProse();
} else {
- if (options?.showHeader !== false) push('header', message.role === 'user' ? 'YOU' : 'MERCURY');
const source = normalizeTerminalText(message.content).split('\n');
let prose: string[] = [];
let inCode = false;
@@ -319,23 +500,36 @@ export function buildMercuryMessageLines(
let codeRowsEmitted = 0;
let codeCollapsed = false;
+ // One blank row between a fenced block and the prose around it.
+ const gap = () => {
+ const last = lines[lines.length - 1];
+ if (last && !(last.kind === 'text' && stripTerminalAnsi(last.text).trim() === '')) push('text', '');
+ };
+
const flushProse = () => {
if (prose.length === 0) return;
- for (const line of renderedTextLines(prose.join('\n'), contentWidth)) push('text', line);
+ const last = lines[lines.length - 1];
+ if (last && last.kind !== 'text') gap();
+ // User input is shown as typed; agent prose renders as markdown.
+ const rows = message.role === 'user'
+ ? prose.flatMap((line) => wrapMercuryText(sanitizeTerminalText(line), contentWidth))
+ : renderedTextLines(prose.join('\n'), contentWidth);
+ for (const line of rows) push('text', line);
prose = [];
};
for (const sourceLine of source) {
const fence = /^```\s*([^\s`]*)/.exec(sourceLine);
- if (fence) {
+ if (fence && message.role !== 'user') {
if (inCode) {
inCode = false;
language = '';
} else {
flushProse();
+ gap();
inCode = true;
language = fence[1] || 'text';
- push('code-label', language.toUpperCase(), language);
+ push('code-label', language, language);
}
continue;
}
@@ -344,7 +538,7 @@ export function buildMercuryMessageLines(
// not push the conversation out of the transcript. The full content
// is on disk / in the session store.
if (codeRowsEmitted < CODE_BLOCK_VISIBLE_ROWS) {
- const chunks = wrapMercuryText(sourceLine, contentWidth);
+ const chunks = wrapMercuryText(sanitizeTerminalText(sourceLine), contentWidth);
for (const chunk of chunks) push('code', chunk, language);
codeRowsEmitted += chunks.length;
} else if (!codeCollapsed) {
@@ -356,6 +550,10 @@ export function buildMercuryMessageLines(
}
}
flushProse();
+ // Headings render with a blank row above them; at the top of a message
+ // that row would push the role marker off the first visible line.
+ while (lines.length > 0 && lines[0].kind === 'text' && stripTerminalAnsi(lines[0].text).trim() === '') lines.shift();
+ if (options?.showHeader !== false && lines.length > 0) lines[0].lead = message.role === 'user' ? 'user' : 'agent';
}
if (message.fileChanges?.length) {
diff --git a/src/ui/stream-tail.test.ts b/src/ui/stream-tail.test.ts
index 7bdb4171..2a966bd7 100644
--- a/src/ui/stream-tail.test.ts
+++ b/src/ui/stream-tail.test.ts
@@ -4,6 +4,7 @@ import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import type { ChatMessage } from './types.js';
+import chalk from 'chalk';
const src = (p: string) => readFileSync(join(dirname(fileURLToPath(import.meta.url)), p), 'utf8');
@@ -58,16 +59,15 @@ describe('streaming tail projection bounds', () => {
expect(rows.length).toBeLessThanOrEqual(STREAM_TAIL_MAX_LINES);
});
- it('renders markdown live (header rows, code blocks)', () => {
+ it('renders markdown live (role marker, 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.
+ // The fenced block gets a code-label + code rows, not plain text, and
+ // the message's first row carries the agent marker.
expect(kinds).toContain('code-label');
expect(kinds).toContain('code');
- expect(kinds).toContain('header');
- expect(lines[0].kind).toBe('header');
+ expect(lines[0].lead).toBe('agent');
});
it('renders a complete code block whose opener sits inside the tail window', () => {
@@ -109,6 +109,31 @@ describe('streaming tail projection bounds', () => {
expect(elapsed).toBeLessThan(30);
});
+ it('recompute cost is bounded on a full 32KB prose-heavy buffer', () => {
+ // Prose rows keep their markdown styling, so wrapping is SGR-aware —
+ // it must stay as cheap as plain wrapping (a generic ANSI wrapper
+ // measured ~100ms here).
+ const para = 'Some **bold words**, `inline code`, and a [link](https://x.dev) to fill the line. ';
+ let content = '';
+ while (content.length < 32 * 1024) content += `- ${para.repeat(3)}\n${para.repeat(4)}\n`;
+ const message: ChatMessage = { id: 'live_3', role: 'agent', content, timestamp: 1, streaming: true };
+ const level = chalk.level;
+ chalk.level = 1; // no TTY in tests — force the styled path being measured
+ // Steady-state cost (what runs per frame): warm up once, best of 5, so a
+ // loaded parallel test run doesn't fail on JIT warm-up or CPU contention.
+ let lines = buildStreamTailLines(message, WIDTH, STREAM_TAIL_CHARS, STREAM_TAIL_MAX_LINES);
+ let elapsed = Infinity;
+ for (let i = 0; i < 5; i++) {
+ const t0 = performance.now();
+ lines = buildStreamTailLines(message, WIDTH, STREAM_TAIL_CHARS, STREAM_TAIL_MAX_LINES);
+ elapsed = Math.min(elapsed, performance.now() - t0);
+ }
+ chalk.level = level;
+ expect(lines.some((l) => l.text.includes('\x1b['))).toBe(true);
+ expect(lines.length).toBeLessThanOrEqual(STREAM_TAIL_MAX_LINES);
+ 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
diff --git a/src/ui/tool-block.test.ts b/src/ui/tool-block.test.ts
new file mode 100644
index 00000000..c002a074
--- /dev/null
+++ b/src/ui/tool-block.test.ts
@@ -0,0 +1,140 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildToolBlock,
+ buildToolBlockDetail,
+ displayPath,
+ editDiffLines,
+ isTranscriptTool,
+ TOOL_DIFF_MAX_LINES,
+ TOOL_OUTPUT_MAX_LINES,
+ TOOL_WRITE_MAX_LINES,
+} from './tool-block.js';
+import { buildMercuryMessageLines } from './mercury-transcript.js';
+
+const cwd = '/work/proj';
+
+describe('tool blocks', () => {
+ it('summarizes a read by line count, path relative to the project', () => {
+ const block = buildToolBlock({ toolName: 'read_file', args: { path: '/work/proj/src/a.ts' }, result: 'one\ntwo\nthree\n', isError: false, cwd });
+ expect(block).toMatchObject({ title: 'Read', target: 'src/a.ts', status: 'done', summary: 'Read 3 lines' });
+ expect(block.body).toBeUndefined();
+ });
+
+ it('does not treat file content mentioning errors as a failed read', () => {
+ const block = buildToolBlock({ toolName: 'read_file', args: { path: 'a.ts' }, result: '// throws error: when empty\nfoo()', isError: false });
+ expect(block.status).toBe('done');
+ });
+
+ it('shows an edit as a trimmed line diff with one line of context', () => {
+ const oldStr = ['function f() {', ' const ttl = 3600;', ' return ttl;', '}'].join('\n');
+ const newStr = ['function f() {', ' const ttl = config.ttl ?? 3600;', ' return ttl;', '}'].join('\n');
+ const block = buildToolBlock({ toolName: 'edit_file', args: { path: 'src/s.ts', old_string: oldStr, new_string: newStr }, result: 'Edited src/s.ts', isError: false });
+ expect(block.title).toBe('Update');
+ expect(block.summary).toBe('1 addition, 1 removal');
+ expect(block.body).toEqual({
+ lang: 'diff',
+ lines: [' function f() {', '- const ttl = 3600;', '+ const ttl = config.ttl ?? 3600;', ' return ttl;'],
+ });
+ });
+
+ it('caps long diffs', () => {
+ const diff = editDiffLines('', Array.from({ length: 50 }, (_, i) => `line ${i}`).join('\n'));
+ expect(diff.added).toBe(50);
+ const block = buildToolBlock({ toolName: 'edit_file', args: { path: 'x', old_string: '', new_string: diff.lines.map((l) => l.slice(1)).join('\n') }, result: 'ok', isError: false });
+ expect(block.body!.lines).toHaveLength(TOOL_DIFF_MAX_LINES + 1);
+ expect(block.body!.lines.at(-1)).toBe(`… +${50 - TOOL_DIFF_MAX_LINES} lines (ctrl+o to expand)`);
+ });
+
+ it('shows the head of a created file in its language', () => {
+ const content = Array.from({ length: 30 }, (_, i) => `print(${i})`).join('\n');
+ const block = buildToolBlock({ toolName: 'create_file', args: { path: 'app.py', content }, result: 'Created app.py', isError: false });
+ expect(block.summary).toBe('Created 30 lines');
+ expect(block.body!.lang).toBe('python');
+ expect(block.body!.lines).toHaveLength(TOOL_WRITE_MAX_LINES + 1);
+ });
+
+ it('shows the tail of command output; non-zero exit is an error', () => {
+ const output = Array.from({ length: 20 }, (_, i) => `out ${i}`).join('\n');
+ const ok = buildToolBlock({ toolName: 'run_command', args: { command: 'npm test' }, result: output, isError: false });
+ expect(ok).toMatchObject({ title: 'Bash', target: 'npm test', status: 'done', summary: '20 lines' });
+ expect(ok.body!.lines[0]).toBe(`… ${20 - TOOL_OUTPUT_MAX_LINES} earlier lines (ctrl+o to expand)`);
+ expect(ok.body!.lines.at(-1)).toBe('out 19');
+
+ const failed = buildToolBlock({ toolName: 'run_command', args: { command: 'npm test' }, result: 'Command exited with code 1\nOutput: 2 failed\nError: boom', isError: false });
+ expect(failed).toMatchObject({ status: 'error', summary: 'Exit code 1' });
+ expect(failed.body!.lines).toEqual(['2 failed', 'boom']);
+
+ const quiet = buildToolBlock({ toolName: 'run_command', args: { command: 'true' }, result: '(no output)', isError: false });
+ expect(quiet.summary).toBe('(no output)');
+ expect(quiet.body).toBeUndefined();
+ });
+
+ it('reports failures by the first line of the error', () => {
+ const block = buildToolBlock({ toolName: 'edit_file', args: { path: 'a.ts', old_string: 'x', new_string: 'y' }, result: 'Error: old_string not found in a.ts. Make sure…\nmore', isError: false });
+ expect(block).toMatchObject({ status: 'error', summary: 'Error: old_string not found in a.ts. Make sure…' });
+ expect(block.body).toBeUndefined();
+ const thrown = buildToolBlock({ toolName: 'fetch_url', args: { url: 'https://x.dev' }, result: new Error('timeout'), isError: true });
+ expect(thrown).toMatchObject({ status: 'error', summary: 'Error: timeout' });
+ });
+
+ it('skips tools that already have their own UI', () => {
+ expect(isTranscriptTool('ask_user')).toBe(false);
+ expect(isTranscriptTool('update_plan')).toBe(true);
+ expect(isTranscriptTool('read_file')).toBe(true);
+ });
+
+ it('shows paths relative to the project root only when inside it', () => {
+ expect(displayPath('/work/proj/a/b.ts', cwd)).toBe('a/b.ts');
+ expect(displayPath('/work/proj', cwd)).toBe('.');
+ expect(displayPath('/work/project2/x', cwd)).toBe('/work/project2/x');
+ });
+
+ it('renders as head, elbow summary, then excerpt rows', () => {
+ const tool = buildToolBlock({ toolName: 'edit_file', args: { path: 'a.ts', old_string: 'a', new_string: 'b' }, result: 'ok', isError: false });
+ const lines = buildMercuryMessageLines({ id: 't1', role: 'system', content: '', timestamp: 1, tool }, 80);
+ expect(lines.map((l) => [l.kind, l.text, l.elbow ?? false])).toEqual([
+ ['tool-head', 'Update', false],
+ ['tool-out', '1 addition, 1 removal', true],
+ ['tool-out', '-a', false],
+ ['tool-out', '+b', false],
+ ['spacer', '', false],
+ ]);
+ expect(lines[0].accent).toBe('a.ts');
+ expect(lines[2].lang).toBe('diff');
+ });
+
+ it('truncates long output rows instead of wrapping and strips escapes', () => {
+ const tool = buildToolBlock({ toolName: 'run_command', args: { command: 'cat x' }, result: `\x1b]0;title\x07${'y'.repeat(300)}`, isError: false });
+ const lines = buildMercuryMessageLines({ id: 't2', role: 'system', content: '', timestamp: 1, tool }, 60);
+ const out = lines.filter((l) => l.kind === 'tool-out' && !l.elbow);
+ expect(out).toHaveLength(1);
+ expect(out[0].text.endsWith('…')).toBe(true);
+ expect(out[0].text).not.toContain('title');
+ expect(out[0].text.length).toBeLessThanOrEqual(60);
+ });
+
+ it('shows plan updates as a checklist', () => {
+ const block = buildToolBlock({ toolName: 'update_plan', args: { steps: [
+ { label: 'Read auth module', status: 'done' },
+ { label: 'Fix TTL', status: 'active' },
+ { label: 'Run tests', status: 'pending' },
+ ] }, result: 'Plan updated', isError: false });
+ expect(block).toMatchObject({ title: 'Plan', target: '', summary: '1/3 done' });
+ expect(block.body).toEqual({ lang: 'plan', lines: ['☒ Read auth module', '▶ Fix TTL', '☐ Run tests'] });
+ });
+
+ it('keeps the full excerpt only for collapsed blocks, on the side the excerpt shows', () => {
+ const output = Array.from({ length: 20 }, (_, i) => `out ${i}`).join('\n');
+ const cmd = buildToolBlockDetail({ toolName: 'run_command', args: { command: 'x' }, result: output, isError: false });
+ expect(cmd.full).toEqual({ lang: '', lines: output.split('\n') });
+
+ const small = buildToolBlockDetail({ toolName: 'run_command', args: { command: 'x' }, result: 'one', isError: false });
+ expect(small.full).toBeUndefined();
+
+ const huge = Array.from({ length: 3000 }, (_, i) => `l${i}`).join('\n');
+ const write = buildToolBlockDetail({ toolName: 'write_file', args: { path: 'a.txt', content: huge }, result: 'ok', isError: false });
+ expect(write.full!.lines[0]).toBe('l0');
+ const tail = buildToolBlockDetail({ toolName: 'run_command', args: { command: 'x' }, result: huge, isError: false });
+ expect(tail.full!.lines.at(-1)).toBe('l2999');
+ });
+});
diff --git a/src/ui/tool-block.ts b/src/ui/tool-block.ts
new file mode 100644
index 00000000..303ddc68
--- /dev/null
+++ b/src/ui/tool-block.ts
@@ -0,0 +1,299 @@
+/**
+ * Tool blocks for the Mercury Code transcript.
+ *
+ * Every finished tool call leaves one persistent block in scrollback, so the
+ * transcript reads as what the agent actually did, in order:
+ *
+ * ● Update(src/auth/session.ts)
+ * ⎿ 1 addition, 1 removal
+ * - const ttl = 3600;
+ * + const ttl = config.sessionTtl ?? 3600;
+ *
+ * This module only builds the data (pure, testable); mercury-transcript.ts
+ * turns it into rows and App.tsx styles them.
+ */
+import { fenceLangForPath } from '../utils/file-preview.js';
+import { formatToolResult } from '../utils/tool-label.js';
+
+export interface ToolBlock {
+ /** Raw tool name (read_file, run_command, …). */
+ name: string;
+ /** Verb shown in bold: Read, Update, Bash, … */
+ title: string;
+ /** Argument shown in parentheses: a path, a command, a URL. */
+ target: string;
+ status: 'done' | 'error';
+ /** One-line outcome shown after the ⎿ elbow. */
+ summary: string;
+ /** Optional excerpt under the summary: a diff, file head, or command output. */
+ body?: { lang: string; lines: string[] };
+}
+
+/** Tools whose work is already shown elsewhere in the TUI (choice prompt,
+ * permission prompt) — no transcript block. */
+const HIDDEN_TOOLS: ReadonlySet<string> = new Set([
+ 'ask_user', 'approve_scope', 'approve_command',
+]);
+
+export function isTranscriptTool(toolName: string): boolean {
+ return !HIDDEN_TOOLS.has(toolName);
+}
+
+/** Diff rows shown for an edit before collapsing to "… +N lines". */
+export const TOOL_DIFF_MAX_LINES = 20;
+/** Head rows of a written/created file. */
+export const TOOL_WRITE_MAX_LINES = 8;
+/** Tail rows of command output (errors and test summaries live at the end). */
+export const TOOL_OUTPUT_MAX_LINES = 6;
+/** Rows kept for an expanded (ctrl+o) block. */
+export const TOOL_EXPAND_MAX_LINES = 2000;
+/** Hint on collapsed excerpts: the expand key. */
+export const EXPAND_HINT = 'ctrl+o to expand';
+
+const TITLES: Record<string, string> = {
+ read_file: 'Read',
+ write_file: 'Write',
+ create_file: 'Create',
+ edit_file: 'Update',
+ delete_file: 'Delete',
+ list_dir: 'List',
+ run_command: 'Bash',
+ cd: 'Cd',
+ fetch_url: 'Fetch',
+ delegate_task: 'Agent',
+ use_skill: 'Skill',
+ search_memory: 'Recall',
+ save_memory: 'Remember',
+ update_plan: 'Plan',
+};
+
+function titleFor(toolName: string): string {
+ if (TITLES[toolName]) return TITLES[toolName];
+ if (toolName.startsWith('git_')) return 'Git';
+ // github_api → Github api, create_pr → Create pr
+ const words = toolName.replace(/_/g, ' ');
+ return words.charAt(0).toUpperCase() + words.slice(1);
+}
+
+/** Show paths relative to the project root; anything else as given. */
+export function displayPath(path: string, cwd?: string): string {
+ const p = path.replace(/\\/g, '/');
+ if (cwd) {
+ const root = cwd.replace(/\\/g, '/').replace(/\/$/, '');
+ if (p === root) return '.';
+ if (p.startsWith(`${root}/`)) return p.slice(root.length + 1);
+ }
+ return p;
+}
+
+function oneLine(text: string, max = 80): string {
+ const line = text.replace(/\s+/g, ' ').trim();
+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;
+}
+
+function targetFor(toolName: string, args: Record<string, any>, cwd?: string): string {
+ if (typeof args.path === 'string' && args.path) return displayPath(args.path, cwd);
+ if (toolName === 'run_command' && typeof args.command === 'string') return oneLine(args.command);
+ if (typeof args.url === 'string') return oneLine(args.url);
+ if (typeof args.task === 'string') return oneLine(args.task, 60);
+ if (typeof args.name === 'string') return oneLine(args.name);
+ if (typeof args.query === 'string') return oneLine(args.query, 60);
+ if (toolName.startsWith('git_')) return toolName.slice(4);
+ return '';
+}
+
+function resultText(result: unknown): string {
+ if (result == null) return '';
+ if (typeof result === 'string') return result;
+ if (result instanceof Error) return `Error: ${result.message}`;
+ const r = result as any;
+ if (typeof r.result === 'string') return r.result;
+ if (typeof r.message === 'string' && r.name) return `Error: ${r.message}`;
+ try {
+ return JSON.stringify(result);
+ } catch {
+ return String(result);
+ }
+}
+
+function lineCount(text: string): number {
+ if (text.length === 0) return 0;
+ return text.replace(/\n$/, '').split('\n').length;
+}
+
+function plural(n: number, word: string): string {
+ return `${n} ${word}${n === 1 ? '' : 's'}`;
+}
+
+/**
+ * Line diff of an edit: common leading/trailing lines are trimmed down to
+ * one line of context each side, so an edit touching one line inside a
+ * 20-line `old_string` shows as one -/+ pair instead of 20 of each.
+ */
+export function editDiffLines(oldStr: string, newStr: string): { lines: string[]; added: number; removed: number } {
+ const a = oldStr.length > 0 ? oldStr.split('\n') : [];
+ const b = newStr.length > 0 ? newStr.split('\n') : [];
+ let pre = 0;
+ while (pre < a.length && pre < b.length && a[pre] === b[pre]) pre++;
+ let suf = 0;
+ while (suf < a.length - pre && suf < b.length - pre && a[a.length - 1 - suf] === b[b.length - 1 - suf]) suf++;
+ const removed = a.slice(pre, a.length - suf);
+ const added = b.slice(pre, b.length - suf);
+ const lines: string[] = [];
+ if (pre > 0) lines.push(` ${a[pre - 1]}`);
+ for (const l of removed) lines.push(`-${l}`);
+ for (const l of added) lines.push(`+${l}`);
+ if (suf > 0) lines.push(` ${a[a.length - suf]}`);
+ return { lines, added: added.length, removed: removed.length };
+}
+
+function capHead(lines: string[], max: number): string[] {
+ if (lines.length <= max) return lines;
+ return [...lines.slice(0, max), `… +${lines.length - max} lines (${EXPAND_HINT})`];
+}
+
+function capTail(lines: string[], max: number): string[] {
+ if (lines.length <= max) return lines;
+ return [`… ${lines.length - max} earlier lines (${EXPAND_HINT})`, ...lines.slice(-max)];
+}
+
+/** Plan checklist rows: ☒ done, ▶ active, ☐ pending. */
+function planRows(steps: unknown): string[] {
+ if (!Array.isArray(steps)) return [];
+ const mark: Record<string, string> = { done: '☒', active: '▶', pending: '☐' };
+ return steps
+ .filter((st: any) => typeof st?.label === 'string' && mark[st?.status])
+ .slice(0, 20)
+ .map((st: any) => `${mark[st.status]} ${oneLine(st.label, 100)}`);
+}
+
+/** Split run_command's result text into exit code + output lines. */
+function parseCommandResult(text: string): { exitCode: number | null; output: string[] } {
+ const exit = /^Command exited with code (\d+)/.exec(text);
+ let body = text;
+ let exitCode: number | null = null;
+ if (exit) {
+ exitCode = Number(exit[1]);
+ body = text.slice(exit[0].length).replace(/^\nOutput: /, '').replace(/\nError: /, '\n');
+ }
+ const output = body.trim() === '(no output)' ? [] : body.replace(/\s+$/, '').split('\n').filter((l, i, all) => l.trim() !== '' || (i > 0 && i < all.length - 1));
+ return { exitCode, output };
+}
+
+/**
+ * Tool failures follow one convention: the result STARTS with the marker.
+ * (execute-guard's isFailedToolResult matches anywhere in the head, which is
+ * right for its job but would paint a read of any file mentioning "error:"
+ * as failed.)
+ */
+const FAILED_PREFIX_RE = /^(error\b|⚠|command failed|command exited with code)/i;
+
+export interface ToolBlockInput {
+ toolName: string;
+ args: Record<string, any>;
+ result: unknown;
+ /** The SDK reported the call as failed (threw). */
+ isError: boolean;
+ /** Project root, to show paths relative to it. */
+ cwd?: string;
+}
+
+export interface ToolBlockDetail {
+ block: ToolBlock;
+ /** The uncollapsed excerpt, when `block.body` had to collapse it. */
+ full?: { lang: string; lines: string[] };
+}
+
+export function buildToolBlock(input: ToolBlockInput): ToolBlock {
+ return buildToolBlockDetail(input).block;
+}
+
+export function buildToolBlockDetail(input: ToolBlockInput): ToolBlockDetail {
+ let full: ToolBlockDetail['full'];
+ // Collapse `lines` into the block body; keep the whole thing for ctrl+o.
+ const body = (lang: string, lines: string[], cap: (l: string[], max: number) => string[], max: number) => {
+ if (lines.length > max) {
+ // Heads keep the start, tails keep the end — same side the excerpt shows.
+ const kept = cap === capTail ? lines.slice(-TOOL_EXPAND_MAX_LINES) : lines.slice(0, TOOL_EXPAND_MAX_LINES);
+ full = { lang, lines: kept };
+ }
+ return { lang, lines: cap(lines, max) };
+ };
+ const block = buildBlock(input, body);
+ return full ? { block, full } : { block };
+}
+
+type BodyFn = (lang: string, lines: string[], cap: (l: string[], max: number) => string[], max: number) => { lang: string; lines: string[] };
+
+function buildBlock(input: ToolBlockInput, body: BodyFn): ToolBlock {
+ const { toolName, cwd } = input;
+ const args = input.args ?? {};
+ const text = resultText(input.result);
+ const failed = input.isError || FAILED_PREFIX_RE.test(text.trimStart());
+ const block: ToolBlock = {
+ name: toolName,
+ title: titleFor(toolName),
+ target: targetFor(toolName, args, cwd),
+ status: failed ? 'error' : 'done',
+ summary: '',
+ };
+
+ if (toolName === 'run_command') {
+ const { exitCode, output } = parseCommandResult(text);
+ if (exitCode != null) block.status = 'error';
+ const timedOut = text.startsWith('⏱');
+ if (failed && exitCode == null && !timedOut) {
+ block.summary = oneLine(text.split('\n')[0], 120);
+ return block;
+ }
+ block.summary = timedOut
+ ? oneLine(text.split('\n')[0], 120)
+ : exitCode != null
+ ? `Exit code ${exitCode}`
+ : output.length === 0 ? '(no output)' : plural(output.length, 'line');
+ if (output.length > 0 && !timedOut) block.body = body('', output, capTail, TOOL_OUTPUT_MAX_LINES);
+ return block;
+ }
+
+ // Failures: the first line of the error is the whole story.
+ if (failed) {
+ block.summary = oneLine(text.split('\n')[0] || 'failed', 120);
+ return block;
+ }
+
+ switch (toolName) {
+ case 'read_file':
+ block.summary = `Read ${plural(lineCount(text), 'line')}`;
+ break;
+ case 'edit_file': {
+ const diff = editDiffLines(String(args.old_string ?? ''), String(args.new_string ?? ''));
+ block.summary = `${plural(diff.added, 'addition')}, ${plural(diff.removed, 'removal')}`;
+ if (diff.lines.length > 0) block.body = body('diff', diff.lines, capHead, TOOL_DIFF_MAX_LINES);
+ break;
+ }
+ case 'write_file':
+ case 'create_file': {
+ const content = typeof args.content === 'string' ? args.content : '';
+ const n = lineCount(content);
+ block.summary = `${toolName === 'create_file' ? 'Created' : 'Wrote'} ${plural(n, 'line')}`;
+ if (n > 0) {
+ const lang = typeof args.path === 'string' ? fenceLangForPath(args.path) : '';
+ block.body = body(lang || 'text', content.replace(/\n$/, '').split('\n'), capHead, TOOL_WRITE_MAX_LINES);
+ }
+ break;
+ }
+ case 'delete_file':
+ block.summary = 'Deleted';
+ break;
+ case 'update_plan': {
+ const rows = planRows(args.steps);
+ const done = rows.filter((r) => r.startsWith('☒')).length;
+ block.summary = `${done}/${rows.length} done`;
+ if (rows.length > 0) block.body = { lang: 'plan', lines: rows };
+ break;
+ }
+ default:
+ block.summary = formatToolResult(toolName, text) || 'Done';
+ }
+ return block;
+}
diff --git a/src/ui/types.ts b/src/ui/types.ts
index bc2e9168..b19cd4a0 100644
--- a/src/ui/types.ts
+++ b/src/ui/types.ts
@@ -2,6 +2,7 @@ import type { ProgrammingModeState } from '../core/programming-mode.js';
import type { SaverModeState } from '../core/saver-mode.js';
import type { SubAgentStatus } from '../types/agent.js';
import type { PermissionMode } from '../channels/base.js';
+import type { ToolBlock } from './tool-block.js';
export type AppMode = 'splash' | 'chat' | 'coding' | 'workspace' | 'spotify' | 'menu' | 'mercury-code';
@@ -78,6 +79,8 @@ export interface ChatMessage {
streaming?: boolean;
completionMeta?: CompletionMeta;
fileChanges?: FileChangeSummary[];
+ /** A finished tool call (Mercury Code transcript block); content holds a plain-text fallback. */
+ tool?: ToolBlock;
}
export interface FileChangeSummary {
diff --git a/src/utils/file-preview.test.ts b/src/utils/file-preview.test.ts
index 346365ab..f3c679f1 100644
--- a/src/utils/file-preview.test.ts
+++ b/src/utils/file-preview.test.ts
@@ -87,12 +87,12 @@ describe('transcript renders previews with highlighting metadata', () => {
timestamp: 1,
};
const lines = buildMercuryMessageLines(msg as any, 80);
- // No header row for system messages, but the fence IS parsed: a
- // code-label row for DIFF followed by code rows carrying the lang.
- expect(lines.some((l) => l.kind === 'code-label' && l.text === 'DIFF')).toBe(true);
+ // No role marker for system messages, but the fence IS parsed: a
+ // code-label row for diff followed by code rows carrying the lang.
+ expect(lines.some((l) => l.kind === 'code-label' && l.text === 'diff')).toBe(true);
const codeRows = lines.filter((l) => l.kind === 'code' && l.lang === 'diff');
expect(codeRows.map((r) => r.text)).toEqual(['-const x = 1;', '+const x = 2;']);
- expect(lines.some((l) => l.kind === 'header')).toBe(false);
+ expect(lines.some((l) => l.lead)).toBe(false);
});
it('system prose still renders without fences', () => {
diff --git a/src/utils/highlight.ts b/src/utils/highlight.ts
index 663e772b..fb75e445 100644
--- a/src/utils/highlight.ts
+++ b/src/utils/highlight.ts
@@ -4,6 +4,13 @@
*/
import chalk from 'chalk';
+import { IS_LIGHT_TERMINAL } from './terminal-theme.js';
+
+// Token palette. Yellow keywords and cyan calls vanish on a white
+// background, so light terminals get magenta/blue/red instead.
+const C = IS_LIGHT_TERMINAL
+ ? { keyword: chalk.magenta, call: chalk.blue, type: chalk.blue, number: chalk.red }
+ : { keyword: chalk.yellow, call: chalk.cyan, type: chalk.blue, number: chalk.magenta };
const CONTROL = /[\x00-\x08\x0b\x0c\x0e-\x1f]/g;
@@ -25,11 +32,11 @@ const C_FAMILY: Rule[] = [
{ re: /^`(?:\\.|[^`\\])*`?/, color: (s) => chalk.green(s) },
{ re: /^'(?:\\.|[^'\\\n])*'?/, color: (s) => chalk.green(s) },
{ re: /^"(?:\\.|[^"\\\n])*"?/, color: (s) => chalk.green(s) },
- { re: /^-?\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?/, color: (s) => chalk.magenta(s) },
- { re: /^(?:abstract|as|break|case|catch|class|const|continue|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|is|keyof|let|namespace|new|of|private|protected|public|readonly|return|satisfies|set|static|super|switch|this|throw|try|type|typeof|var|void|while|yield|async|await)\b/, color: (s) => chalk.yellow(s) },
- { re: /^(?:true|false|null|unique|undefined|NaN|Infinity)\b/, color: (s) => chalk.blue(s) },
- { re: /^[A-Za-z_$][\w$]*(?=\s*\()/, color: (s) => chalk.cyan(s) },
- { re: /^[A-Z][\w$]*/, color: (s) => chalk.blue(s) },
+ { re: /^-?\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?/, color: (s) => C.number(s) },
+ { re: /^(?:abstract|as|break|case|catch|class|const|continue|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|is|keyof|let|namespace|new|of|private|protected|public|readonly|return|satisfies|set|static|super|switch|this|throw|try|type|typeof|var|void|while|yield|async|await)\b/, color: (s) => C.keyword(s) },
+ { re: /^(?:true|false|null|unique|undefined|NaN|Infinity)\b/, color: (s) => C.type(s) },
+ { re: /^[A-Za-z_$][\w$]*(?=\s*\()/, color: (s) => C.call(s) },
+ { re: /^[A-Z][\w$]*/, color: (s) => C.type(s) },
];
const PY_RULES: Rule[] = [
@@ -38,40 +45,40 @@ const PY_RULES: Rule[] = [
{ re: /^'''[\s\S]*?('''|$)/, color: (s) => chalk.gray(s) },
{ re: /^f?"(?:\\.|[^"\\\n])*"?/, color: (s) => chalk.green(s) },
{ re: /^f?'(?:\\.|[^'\\\n])*'?/, color: (s) => chalk.green(s) },
- { re: /^\d[\d_]*(?:\.\d+)?/, color: (s) => chalk.magenta(s) },
- { re: /^(?:def|class|import|from|return|if|elif|else|for|while|try|except|finally|with|as|lambda|yield|raise|pass|break|continue|global|nonlocal|assert|async|await|not|and|or|in|is|del)\b/, color: (s) => chalk.yellow(s) },
- { re: /^(?:True|False|None|self|cls)\b/, color: (s) => chalk.blue(s) },
- { re: /^[A-Za-z_]\w*(?=\s*\()/, color: (s) => chalk.cyan(s) },
- { re: /^[A-Z][\w]*/, color: (s) => chalk.blue(s) },
+ { re: /^\d[\d_]*(?:\.\d+)?/, color: (s) => C.number(s) },
+ { re: /^(?:def|class|import|from|return|if|elif|else|for|while|try|except|finally|with|as|lambda|yield|raise|pass|break|continue|global|nonlocal|assert|async|await|not|and|or|in|is|del)\b/, color: (s) => C.keyword(s) },
+ { re: /^(?:True|False|None|self|cls)\b/, color: (s) => C.type(s) },
+ { re: /^[A-Za-z_]\w*(?=\s*\()/, color: (s) => C.call(s) },
+ { re: /^[A-Z][\w]*/, color: (s) => C.type(s) },
{ re: /^@\w[\w.]*/, color: (s) => chalk.green(s) },
];
const SHELL_RULES: Rule[] = [
{ re: /^#[^\n]*/, color: (s) => chalk.gray(s) },
- { re: /^(?:if|then|else|elif|fi|for|while|do|done|case|esac|function|return|export|local|source|set|unset|cd|exit)\b/, color: (s) => chalk.yellow(s) },
- { re: /^\$\{[^}]*\}?\$?/, color: (s) => chalk.magenta(s) },
- { re: /^\$\w*/, color: (s) => chalk.magenta(s) },
+ { re: /^(?:if|then|else|elif|fi|for|while|do|done|case|esac|function|return|export|local|source|set|unset|cd|exit)\b/, color: (s) => C.keyword(s) },
+ { re: /^\$\{[^}]*\}?\$?/, color: (s) => C.number(s) },
+ { re: /^\$\w*/, color: (s) => C.number(s) },
{ re: /^"(?:\\.|[^"\\])*"?/, color: (s) => chalk.green(s) },
{ re: /^'(?:[^'\\])*'?/, color: (s) => chalk.green(s) },
- { re: /^\d+/, color: (s) =>chalk.magenta(s) },
- { re: /^(?:npm|pnpm|yarn|node|npx|git|curl|wget|python|python3|pip|cargo|go|make|brew|ls|cat|echo|mkdir|rm|mv|cp|cd|chmod|docker|kubectl)\b/, color: (s) => chalk.cyan(s) },
+ { re: /^\d+/, color: (s) =>C.number(s) },
+ { re: /^(?:npm|pnpm|yarn|node|npx|git|curl|wget|python|python3|pip|cargo|go|make|brew|ls|cat|echo|mkdir|rm|mv|cp|cd|chmod|docker|kubectl)\b/, color: (s) => C.call(s) },
];
const JSON_RULES: Rule[] = [
- { re: /^"(?:\\.|[^"\\])*"(?=\s*:)/, color: (s) => chalk.blue(s) },
+ { re: /^"(?:\\.|[^"\\])*"(?=\s*:)/, color: (s) => C.type(s) },
{ re: /^"(?:\\.|[^"\\])*"?/, color: (s) => chalk.green(s) },
- { re: /^-?\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?/, color: (s) => chalk.magenta(s) },
- { re: /^(?:true|false|null)\b/, color: (s) => chalk.blue(s) },
+ { re: /^-?\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?/, color: (s) => C.number(s) },
+ { re: /^(?:true|false|null)\b/, color: (s) => C.type(s) },
];
const CSS_RULES: Rule[] = [
{ re: /^\/\*[\s\S]*?\*\//, color: (s) => chalk.gray(s) },
- { re: /^@[\w-]+/, color: (s) => chalk.yellow(s) },
- { re: /^[.#]?[\w-]+(?=\s*\{)/, color: (s) => chalk.cyan(s) },
- { re: /^[\w-]+(?=\s*:)/, color: (s) => chalk.blue(s) },
+ { re: /^@[\w-]+/, color: (s) => C.keyword(s) },
+ { re: /^[.#]?[\w-]+(?=\s*\{)/, color: (s) => C.call(s) },
+ { re: /^[\w-]+(?=\s*:)/, color: (s) => C.type(s) },
{ re: /^"(?:\\.|[^"\\\n])*"?/, color: (s) => chalk.green(s) },
{ re: /^'(?:[^'\\\n])*'?/, color: (s) => chalk.green(s) },
- { re: /^-?\d[\d.]*(?:px|em|rem|%|vh|vw|s|ms|fr)?/, color: (s) => chalk.magenta(s) },
+ { re: /^-?\d[\d.]*(?:px|em|rem|%|vh|vw|s|ms|fr)?/, color: (s) => C.number(s) },
];
const GO_RULES: Rule[] = [
@@ -79,22 +86,22 @@ const GO_RULES: Rule[] = [
{ re: /^\/\*[\s\S]*?\*\//, color: (s) => chalk.gray(s) },
{ re: /^"(?:\\.|[^"\\\n])*"?/, color: (s) => chalk.green(s) },
{ re: /^`(?:\\.|[^`\\])*`?/, color: (s) => chalk.green(s) },
- { re: /^\d[\d_]*(?:\.\d+)?/, color: (s) => chalk.magenta(s) },
- { re: /^(?:package|import|func|return|if|else|for|range|switch|case|default|type|struct|interface|map|chan|go|defer|var|const|select|break|continue|fallthrough)\b/, color: (s) => chalk.yellow(s) },
- { re: /^[A-Za-z_]\w*(?=\s*\()/, color: (s) => chalk.cyan(s) },
- { re: /^[A-Z][\w]*/, color: (s) => chalk.blue(s) },
+ { re: /^\d[\d_]*(?:\.\d+)?/, color: (s) => C.number(s) },
+ { re: /^(?:package|import|func|return|if|else|for|range|switch|case|default|type|struct|interface|map|chan|go|defer|var|const|select|break|continue|fallthrough)\b/, color: (s) => C.keyword(s) },
+ { re: /^[A-Za-z_]\w*(?=\s*\()/, color: (s) => C.call(s) },
+ { re: /^[A-Z][\w]*/, color: (s) => C.type(s) },
];
const RUST_RULES: Rule[] = [
{ re: /^\/\/[^\n]*/, color: (s) => chalk.gray(s) },
{ re: /^\/\*[\s\S]*?\*\//, color: (s) => chalk.gray(s) },
{ re: /^"(?:\\.|[^"\\\n])*"?/, color: (s) => chalk.green(s) },
- { re: /^\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?/, color: (s) => chalk.magenta(s) },
- { re: /^(?:as|break|const|continue|crate|dyn|else|enum|extern|false|fn|for|if|impl|in|let|loop|match|mod|move|mut|pub|ref|return|self|Self|static|struct|super|trait|true|type|unsafe|use|where|while|async|await)\b/, color: (s) => chalk.yellow(s) },
- { re: /^&['\u2019]?\w*\b/, color: (s) => chalk.cyan(s) },
- { re: /^\w+!/, color: (s) => chalk.cyan(s) },
- { re: /^[A-Za-z_]\w*(?=\s*[<(])/ , color: (s) => chalk.cyan(s) },
- { re: /^[A-Z][\w]*/, color: (s) => chalk.blue(s) },
+ { re: /^\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?/, color: (s) => C.number(s) },
+ { re: /^(?:as|break|const|continue|crate|dyn|else|enum|extern|false|fn|for|if|impl|in|let|loop|match|mod|move|mut|pub|ref|return|self|Self|static|struct|super|trait|true|type|unsafe|use|where|while|async|await)\b/, color: (s) => C.keyword(s) },
+ { re: /^&['\u2019]?\w*\b/, color: (s) => C.call(s) },
+ { re: /^\w+!/, color: (s) => C.call(s) },
+ { re: /^[A-Za-z_]\w*(?=\s*[<(])/ , color: (s) => C.call(s) },
+ { re: /^[A-Z][\w]*/, color: (s) => C.type(s) },
];
const RULESETS: Record<string, Rule[]> = {
@@ -162,10 +169,10 @@ export function highlightLine(line: string, lang: string, opts?: HighlightOption
/** Whole-line uniform diff renderer: - red, + green, header gray/blue. */
export function highlightDiffLine(line: string): string {
- if (line.startsWith('+++') || line.startsWith('---')) return chalk.blue(line);
- if (line.startsWith('+++') || line.startsWith('---')) return chalk.blue(line);
+ if (line.startsWith('+++') || line.startsWith('---')) return C.type(line);
+ if (line.startsWith('+++') || line.startsWith('---')) return C.type(line);
if (line.startsWith('diff ')) return chalk.bold.blue(line);
- if (line.startsWith('@@')) return chalk.cyan(line);
+ if (line.startsWith('@@')) return C.call(line);
if (line.startsWith('+')) return chalk.green(line);
if (line.startsWith('-')) return chalk.red(line);
return line;
diff --git a/src/utils/markdown.ts b/src/utils/markdown.ts
index 0d45e316..6f50bf93 100644
--- a/src/utils/markdown.ts
+++ b/src/utils/markdown.ts
@@ -1,5 +1,10 @@
import { Marked } from 'marked';
import chalk from 'chalk';
+import stringWidth from 'string-width';
+import { IS_LIGHT_TERMINAL } from './terminal-theme.js';
+
+/** Inline `code` color: yellow is unreadable on a light background. */
+const codespan = (text: string) => (IS_LIGHT_TERMINAL ? chalk.magenta(text) : chalk.yellow(text));
import { highlightCodeBlock } from './highlight.js';
const lexer = new Marked();
@@ -59,7 +64,7 @@ function renderToken(t: any): string {
case 'del':
return chalk.dim.strikethrough(renderInline(t.tokens));
case 'codespan':
- return chalk.yellow(t.text);
+ return codespan(t.text);
case 'code':
return renderCodeBlock(t);
case 'list':
@@ -69,7 +74,7 @@ function renderToken(t: any): string {
case 'hr':
return chalk.dim('─'.repeat(50)) + '\n\n';
case 'link':
- return `${chalk.blue.underline(renderInline(t.tokens))} ${chalk.dim(`(${t.href})`)}`;
+ return renderLink(t);
case 'image':
return chalk.blue(`🖼 ${t.title || t.href}`);
case 'table':
@@ -88,9 +93,17 @@ function renderToken(t: any): string {
function renderHeading(t: any): string {
const text = renderInline(t.tokens);
- if (t.depth === 1) return `\n${chalk.bold.cyan(text)}\n\n`;
- if (t.depth === 2) return `\n${chalk.bold.cyan(` ■ ${text}`)}\n\n`;
- return `\n${chalk.bold(` ■ ${text}`)}\n\n`;
+ // Plain bold headings, flush left — no glyphs or indents, so a heading
+ // reads as a heading instead of as another list level.
+ if (t.depth === 1) return `\n${chalk.bold.underline(text)}\n\n`;
+ return `\n${chalk.bold(text)}\n\n`;
+}
+
+/** Link text, with the URL appended only when it adds information. */
+function renderLink(t: any): string {
+ const text = renderInline(t.tokens);
+ const label = chalk.blue.underline(text);
+ return text === t.href || `mailto:${text}` === t.href ? label : `${label} ${chalk.dim(`(${t.href})`)}`;
}
function renderInline(tokens: any[] | undefined): string {
@@ -100,8 +113,8 @@ function renderInline(tokens: any[] | undefined): string {
if (t.type === 'strong') return chalk.bold(renderInline(t.tokens));
if (t.type === 'em') return chalk.italic(renderInline(t.tokens));
if (t.type === 'del') return chalk.dim.strikethrough(renderInline(t.tokens));
- if (t.type === 'codespan') return chalk.yellow(t.text);
- if (t.type === 'link') return `${chalk.blue.underline(renderInline(t.tokens))} ${chalk.dim(`(${t.href})`)}`;
+ if (t.type === 'codespan') return codespan(t.text);
+ if (t.type === 'link') return renderLink(t);
if (t.type === 'image') return chalk.blue(`🖼 ${t.title || t.href}`);
if (t.type === 'text') {
return t.tokens ? renderInline(t.tokens) : (t.text || '');
@@ -136,8 +149,12 @@ function renderList(t: any): string {
.map((l: string) => ` ${l}`)
.join('\n');
lines.push(subLines);
- } else if (sub.type === 'text') {
- lines.push(` ${chalk.dim('•')} ${renderInline(sub.tokens)}`);
+ } else if (sub.type === 'text' || sub.type === 'paragraph') {
+ // Continuation paragraph of the same item (loose lists): indented
+ // under the item text, not a new bullet.
+ lines.push(` ${renderInline(sub.tokens)}`);
+ } else if (sub.type === 'code') {
+ lines.push(renderCodeBlock(sub).split('\n').filter(Boolean).map((l: string) => ` ${l}`).join('\n'));
}
}
});
@@ -154,28 +171,24 @@ function renderBlockquote(t: any): string {
return `\n${lines}\n\n`;
}
-function renderTable(t: any): string {
- const headers = (t.header || []).map((h: any) => chalk.bold(renderInline(h.tokens)));
- const colWidths = (t.header || []).map((h: any, i: number) => {
- const hLen = (h.text || '').length;
- const rowLens = (t.rows || []).map((row: any) => {
- const cell = row[i];
- return cell?.text?.length ?? 0;
- });
- return Math.max(hLen, ...rowLens) + 2;
- });
-
- const headerLine = headers.map((h: string, i: number) => h.padEnd(colWidths[i])).join(chalk.dim(' │ '));
- const separator = colWidths.map((w: number) => '─'.repeat(w)).join(chalk.dim('─┼─'));
-
- const dataLines = (t.rows || []).map((row: any) =>
- row.map((cell: any, i: number) => {
- const text = renderInline(cell.tokens) || cell.text || '';
- return text.padEnd(colWidths[i]);
- }).join(chalk.dim(' │ '))
- );
+/** Pad to a visible column width — `padEnd` counts ANSI codes and wide chars. */
+function padVisible(text: string, width: number): string {
+ return text + ' '.repeat(Math.max(0, width - stringWidth(text)));
+}
- return `\n${headerLine}\n${chalk.dim(separator)}\n${dataLines.join('\n')}\n\n`;
+function renderTable(t: any): string {
+ const headers: string[] = (t.header || []).map((h: any) => chalk.bold(renderInline(h.tokens) || h.text || ''));
+ const rows: string[][] = (t.rows || []).map((row: any) =>
+ row.map((cell: any) => renderInline(cell.tokens) || cell.text || ''));
+ const colWidths = headers.map((h, i) =>
+ Math.max(stringWidth(h), ...rows.map((row) => stringWidth(row[i] ?? ''))));
+
+ const sep = chalk.dim(' │ ');
+ const headerLine = headers.map((h, i) => padVisible(h, colWidths[i])).join(sep);
+ const separator = chalk.dim(colWidths.map((w) => '─'.repeat(w)).join('─┼─'));
+ const dataLines = rows.map((row) => row.map((cell, i) => padVisible(cell, colWidths[i])).join(sep));
+
+ return `\n${headerLine}\n${separator}\n${dataLines.join('\n')}\n\n`;
}
function escapeHtml(text: string): string {
diff --git a/src/utils/terminal-theme.test.ts b/src/utils/terminal-theme.test.ts
new file mode 100644
index 00000000..fb274389
--- /dev/null
+++ b/src/utils/terminal-theme.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+import { detectTerminalTheme } from './terminal-theme.js';
+
+describe('terminal theme detection', () => {
+ it('reads the background from COLORFGBG', () => {
+ expect(detectTerminalTheme({ COLORFGBG: '15;0' })).toBe('dark');
+ expect(detectTerminalTheme({ COLORFGBG: '0;15' })).toBe('light');
+ expect(detectTerminalTheme({ COLORFGBG: '0;7' })).toBe('light');
+ expect(detectTerminalTheme({ COLORFGBG: '0;default;15' })).toBe('light');
+ expect(detectTerminalTheme({ COLORFGBG: '7;8' })).toBe('dark');
+ });
+
+ it('defaults to dark when the terminal says nothing', () => {
+ expect(detectTerminalTheme({})).toBe('dark');
+ expect(detectTerminalTheme({ COLORFGBG: 'garbage' })).toBe('dark');
+ });
+
+ it('lets MERCURY_THEME override detection', () => {
+ expect(detectTerminalTheme({ MERCURY_THEME: 'light' })).toBe('light');
+ expect(detectTerminalTheme({ MERCURY_THEME: 'Dark', COLORFGBG: '0;15' })).toBe('dark');
+ expect(detectTerminalTheme({ MERCURY_THEME: 'auto', COLORFGBG: '0;15' })).toBe('light');
+ });
+});
diff --git a/src/utils/terminal-theme.ts b/src/utils/terminal-theme.ts
new file mode 100644
index 00000000..f1c26d5b
--- /dev/null
+++ b/src/utils/terminal-theme.ts
@@ -0,0 +1,24 @@
+/**
+ * Terminal background detection, so TUI colors stay readable on light
+ * terminals (yellow and bright cyan nearly vanish on white).
+ *
+ * `MERCURY_THEME=light|dark` wins; otherwise COLORFGBG ("fg;bg", set by
+ * iTerm2, Konsole, rxvt, …) decides: background 7 (light gray) or 10–15
+ * (bright colors, 15 = white) is light. Terminals that set neither — e.g.
+ * macOS Terminal.app — are assumed dark; light users set MERCURY_THEME.
+ */
+export type TerminalTheme = 'light' | 'dark';
+
+export function detectTerminalTheme(env: NodeJS.ProcessEnv = process.env): TerminalTheme {
+ const forced = env.MERCURY_THEME?.trim().toLowerCase();
+ if (forced === 'light' || forced === 'dark') return forced;
+ const fgBg = env.COLORFGBG;
+ if (!fgBg) return 'dark';
+ const parts = fgBg.split(';');
+ const bg = Number(parts[parts.length - 1]);
+ if (Number.isNaN(bg)) return 'dark';
+ return bg === 7 || (bg >= 10 && bg <= 15) ? 'light' : 'dark';
+}
+
+/** Resolved once per process: the terminal doesn't change under us. */
+export const IS_LIGHT_TERMINAL = detectTerminalTheme() === 'light';