xonecas.io
64875
Mc

mini-coder / commit 47490f0

feat: add UI audit baseline tests and shared test helpers

- Add src/cli/test-helpers.ts with captureStdout, getCapturedStdout,
  restoreStdout, stripAnsi, simulateTerminal, withTerminalColumns
- Add src/cli/ui-audit.test.ts with 24 tests covering:
  - Output hierarchy (user messages, tool calls, tool results, errors)
  - Full turn scenarios (reasoning→text, tool→reply, multi-tool, etc.)
  - Spinner leak prevention
  - Consistent indentation depths across all tool types
- Refactor existing test files to use shared helpers
- Add UI-AUDIT-PROMPT.md for task resumption

xonecas2026-03-16 47490f0b5329993c59d6c055f3d364e3770b9e36 parent 5d64e3a

8 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

TODO.md+1−1
@@ -2,7 +2,7 @@
22
33 ## Bugs:
44
5-- ~~Session history break~~ Fixed: removed `@anthropic-ai/sdk` bypass (`turn-anthropic-oauth.ts`). The raw SDK path manually converted thinking blocks after Vercel AI SDK pruning, producing invalid blocks. Now all Anthropic OAuth requests flow through `@ai-sdk/anthropic` which handles thinking blocks natively.
5+- None
66
77 ---
88
UI-AUDIT-PROMPT.md+35−0
@@ -0,0 +1,35 @@
1+# UI Audit Refactor
2+
3+We're on branch `refactor/ui-audit` doing the UI Audit from TODO.md.
4+
5+## Goals
6+
7+- Revise all console output for consistency, **performance**, and correctness.
8+- Ensure clear styled output with proper hierarchy — different output types (user, assistant, reasoning, tool calls, tool results, errors) must be clearly distinguishable via styles and whitespace.
9+- Ensure proper spinner functionality — follow-up messages don't render inline, nothing breaks.
10+- Ensure conversation log is logical — user, assistant, reasoning, tools/tool calls/results are clearly labelled and associated for readability.
11+
12+## Key rendering files
13+
14+- `src/cli/output.ts` — Glyphs (`G`), banner, error rendering, `CliReporter`
15+- `src/cli/tool-render.ts` — Tool call lines + tool result dispatch
16+- `src/cli/tool-result-renderers.ts` — Per-tool result formatting (shell, subagent, skills, web, MCP)
17+- `src/cli/stream-render.ts` — Main turn event loop — orchestrates text, reasoning, tools, spinner
18+- `src/cli/stream-render-content.ts` — Text/reasoning delta accumulation + markdown highlighting
19+- `src/cli/live-reasoning.ts` — Streamed reasoning block display
20+- `src/cli/spinner.ts` — Braille spinner on stderr
21+- `src/cli/status-bar.ts` — Model/session/token info bar
22+
23+## Testing approach
24+
25+- Use `simulateTerminal()` + captured stdout for "user perspective" tests (handles cursor rewrites).
26+- Test with `stripAnsi()` for structure, `hasAnsi()` for styling assertions.
27+- Test realistic multi-event sequences through `renderTurn()` to catch spacing/hierarchy issues.
28+- Verify indentation levels, blank line separators, glyph prefixes, spinner clears.
29+
30+## Status
31+
32+- [ ] Baseline tests for current output
33+- [ ] Identify inconsistencies and issues
34+- [ ] Refactor rendering for consistency
35+- [ ] Verify all tests pass
src/cli/live-reasoning.test.ts+14−22
@@ -1,39 +1,29 @@
11 import { afterEach, describe, expect, test } from "bun:test";
22 import { LiveReasoningBlock } from "./live-reasoning.ts";
3-import { terminal } from "./terminal-io.ts";
4-
5-let stdout = "";
6-const originalStdoutWrite = terminal.stdoutWrite.bind(terminal);
3+import {
4+ captureStdout,
5+ getCapturedStdout,
6+ restoreStdout,
7+ stripAnsi,
8+} from "./test-helpers.ts";
79
810 afterEach(() => {
9- stdout = "";
10- terminal.stdoutWrite = originalStdoutWrite;
11+ restoreStdout();
1112 });
1213
13-function captureStdout(): void {
14- terminal.stdoutWrite = (text: string) => {
15- stdout += text;
16- };
17-}
18-
19-function stripAnsi(text: string): string {
20- const esc = String.fromCharCode(0x1b);
21- return text.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "");
22-}
23-
2414 describe("LiveReasoningBlock", () => {
2515 test("streams partial reasoning immediately instead of waiting for finish", () => {
2616 captureStdout();
2717 const block = new LiveReasoningBlock();
2818
2919 block.append("think");
30- expect(stripAnsi(stdout)).toBe("· reasoning\n think");
20+ expect(stripAnsi(getCapturedStdout())).toBe("· reasoning\n think");
3121
3222 block.append("ing");
33- expect(stripAnsi(stdout)).toBe("· reasoning\n thinking");
23+ expect(stripAnsi(getCapturedStdout())).toBe("· reasoning\n thinking");
3424
3525 block.finish();
36- expect(stripAnsi(stdout)).toBe("· reasoning\n thinking\n");
26+ expect(stripAnsi(getCapturedStdout())).toBe("· reasoning\n thinking\n");
3727 });
3828
3929 test("preserves blank reasoning lines and italic styling", () => {
@@ -43,7 +33,9 @@ describe("LiveReasoningBlock", () => {
4333 block.append("line 1\n\nline 3");
4434 block.finish();
4535
46- expect(stripAnsi(stdout)).toBe("· reasoning\n line 1\n \n line 3\n");
47- expect(stdout.includes("\x1b[3m")).toBe(true);
36+ expect(stripAnsi(getCapturedStdout())).toBe(
37+ "· reasoning\n line 1\n \n line 3\n",
38+ );
39+ expect(getCapturedStdout().includes("\x1b[3m")).toBe(true);
4840 });
4941 });
src/cli/output.test.ts+14−20
@@ -1,33 +1,23 @@
11 import { afterEach, describe, expect, test } from "bun:test";
22 import { renderBanner, renderUserMessage } from "./output.ts";
3-import { terminal } from "./terminal-io.ts";
4-
5-let stdout = "";
6-const originalStdoutWrite = terminal.stdoutWrite.bind(terminal);
3+import {
4+ captureStdout,
5+ getCapturedStdout,
6+ restoreStdout,
7+ stripAnsi,
8+} from "./test-helpers.ts";
79
810 afterEach(() => {
9- stdout = "";
10- terminal.stdoutWrite = originalStdoutWrite;
11+ restoreStdout();
1112 });
1213
13-function captureStdout(): void {
14- terminal.stdoutWrite = (text: string) => {
15- stdout += text;
16- };
17-}
18-
19-function stripAnsi(text: string): string {
20- const esc = String.fromCharCode(0x1b);
21- return text.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "");
22-}
23-
2414 describe("renderUserMessage", () => {
2515 test("renders a compact single-line prompt entry", () => {
2616 captureStdout();
2717
2818 renderUserMessage("ship it");
2919
30- expect(stripAnsi(stdout)).toBe("› ship it\n");
20+ expect(stripAnsi(getCapturedStdout())).toBe("› ship it\n");
3121 });
3222
3323 test("preserves multiline prompts as an indented history block", () => {
@@ -35,7 +25,9 @@ describe("renderUserMessage", () => {
3525
3626 renderUserMessage("plan\nstep 1\n\nstep 2");
3727
38- expect(stripAnsi(stdout)).toBe("› plan\n step 1\n \n step 2\n");
28+ expect(stripAnsi(getCapturedStdout())).toBe(
29+ "› plan\n step 1\n \n step 2\n",
30+ );
3931 });
4032 });
4133
@@ -45,6 +37,8 @@ describe("renderBanner", () => {
4537
4638 renderBanner("zen/gpt-5.4", `${process.env.HOME}/src/mini-coder`);
4739
48- expect(stripAnsi(stdout)).toContain("zen/gpt-5.4 · ~/src/mini-coder");
40+ expect(stripAnsi(getCapturedStdout())).toContain(
41+ "zen/gpt-5.4 · ~/src/mini-coder",
42+ );
4943 });
5044 });
src/cli/stream-render.test.ts+38−99
@@ -3,22 +3,18 @@ import type { CoreMessage } from "../llm-api/turn.ts";
33 import type { TurnEvent } from "../llm-api/types.ts";
44 import { Spinner } from "./spinner.ts";
55 import { renderTurn } from "./stream-render.ts";
6-import { terminal } from "./terminal-io.ts";
7-
8-let stdout = "";
9-const originalStdoutWrite = terminal.stdoutWrite.bind(terminal);
6+import {
7+ captureStdout,
8+ getCapturedStdout,
9+ restoreStdout,
10+ simulateTerminal,
11+ stripAnsi,
12+} from "./test-helpers.ts";
1013
1114 afterEach(() => {
12- stdout = "";
13- terminal.stdoutWrite = originalStdoutWrite;
15+ restoreStdout();
1416 });
1517
16-function captureStdout(): void {
17- terminal.doStdoutWrite = (text: string) => {
18- stdout += text;
19- };
20-}
21-
2218 function eventsFrom(events: TurnEvent[]): AsyncIterable<TurnEvent> {
2319 return (async function* () {
2420 for (const event of events) {
@@ -37,71 +33,6 @@ function done(messages: CoreMessage[] = []): TurnEvent {
3733 };
3834 }
3935
40-function strip(s: string): string {
41- const esc = String.fromCharCode(0x1b);
42- return s.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "");
43-}
44-
45-/**
46- * Simulate terminal rendering for key cursor-control sequences used by the
47- * stream renderer: `\r`, `\n`, `\x1b[2K` (erase line), and `\x1b[1A` (cursor up).
48- */
49-function simulateTerminal(raw: string): string {
50- const esc = String.fromCharCode(0x1b);
51- // Strip ANSI SGR color/style codes first so we can compare plain text.
52- const noColor = raw.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "");
53- const lines: string[] = [""];
54- let row = 0;
55- let col = 0;
56- let i = 0;
57-
58- const ensureRow = (idx: number): void => {
59- while (lines.length <= idx) lines.push("");
60- };
61-
62- while (i < noColor.length) {
63- const ch = noColor[i];
64- if (ch === "\n") {
65- row++;
66- ensureRow(row);
67- col = 0;
68- i++;
69- continue;
70- }
71- if (ch === "\r") {
72- col = 0;
73- i++;
74- continue;
75- }
76- if (ch === esc && noColor[i + 1] === "[") {
77- if (noColor[i + 2] === "2" && noColor[i + 3] === "K") {
78- lines[row] = "";
79- col = 0;
80- i += 4;
81- continue;
82- }
83- if (noColor[i + 2] === "1" && noColor[i + 3] === "A") {
84- row = Math.max(0, row - 1);
85- col = Math.min(col, lines[row]?.length ?? 0);
86- i += 4;
87- continue;
88- }
89- }
90-
91- ensureRow(row);
92- const line = lines[row] ?? "";
93- if (col >= line.length) {
94- lines[row] = line + ch;
95- } else {
96- lines[row] = `${line.slice(0, col)}${ch}${line.slice(col + 1)}`;
97- }
98- col++;
99- i++;
100- }
101-
102- return lines.join("\n");
103-}
104-
10536 function hasAnsi(s: string, code: string): boolean {
10637 return s.includes(`${String.fromCharCode(0x1b)}${code}`);
10738 }
@@ -123,7 +54,9 @@ describe("renderTurn", () => {
12354 new Spinner(),
12455 );
12556
126- expect(simulateTerminal(stdout)).toBe("◆ first line\nsecond line\n");
57+ expect(simulateTerminal(getCapturedStdout())).toBe(
58+ "◆ first line\nsecond line\n",
59+ );
12760 expect(result).toEqual({
12861 inputTokens: 1,
12962 outputTokens: 2,
@@ -141,8 +74,8 @@ describe("renderTurn", () => {
14174 new Spinner(),
14275 );
14376
144- expect(stdout.includes("\r\x1b[2K")).toBe(false);
145- expect(simulateTerminal(stdout)).toBe("◆ plain text\n");
77+ expect(getCapturedStdout().includes("\r\x1b[2K")).toBe(false);
78+ expect(simulateTerminal(getCapturedStdout())).toBe("◆ plain text\n");
14679 });
14780
14881 test("preserves reply glyph on partial-line overwrite after a complete line in same delta", async () => {
@@ -156,7 +89,7 @@ describe("renderTurn", () => {
15689 // "hello\n" is flushed as a complete line. "world" is streamed as a
15790 // partial then overwritten on turn-end. The ◆ prefix appears only on
15891 // the first line; continuation lines have no prefix.
159- expect(simulateTerminal(stdout)).toBe("◆ hello\nworld\n");
92+ expect(simulateTerminal(getCapturedStdout())).toBe("◆ hello\nworld\n");
16093 });
16194
16295 test("renders buffered markdown correctly and preserves emoji across deltas", async () => {
@@ -173,7 +106,7 @@ describe("renderTurn", () => {
173106
174107 // Streaming now prioritizes immediate output stability over end-of-line markdown
175108 // rewrite, so raw markdown markers are preserved in partial lines.
176- expect(simulateTerminal(stdout)).toBe("◆ **bold** 👩🏽‍💻\n");
109+ expect(simulateTerminal(getCapturedStdout())).toBe("◆ **bold** 👩🏽‍💻\n");
177110 });
178111
179112 test("leaves fenced markdown plain across streamed lines", async () => {
@@ -188,7 +121,9 @@ describe("renderTurn", () => {
188121 new Spinner(),
189122 );
190123
191- expect(strip(stdout)).toBe("◆ ```ts\nconst emoji = '👩🏽‍💻';\n```\n\n");
124+ expect(stripAnsi(getCapturedStdout())).toBe(
125+ "◆ ```ts\nconst emoji = '👩🏽‍💻';\n```\n\n",
126+ );
192127 });
193128 test("can hide reasoning output while still accumulating reasoning text", async () => {
194129 captureStdout();
@@ -203,7 +138,7 @@ describe("renderTurn", () => {
203138 { showReasoning: false },
204139 );
205140
206- expect(simulateTerminal(stdout)).toBe("◆ final\n");
141+ expect(simulateTerminal(getCapturedStdout())).toBe("◆ final\n");
207142 expect(result.reasoningText).toBe("step 1\nstep 2");
208143 });
209144
@@ -233,9 +168,11 @@ describe("renderTurn", () => {
233168 new Spinner(),
234169 );
235170
236- expect(simulateTerminal(stdout)).toBe("· reasoning\n thinking\n");
237- expect(hasAnsi(stdout, "[2m")).toBe(true);
238- expect(hasAnsi(stdout, "[3m")).toBe(true);
171+ expect(simulateTerminal(getCapturedStdout())).toBe(
172+ "· reasoning\n thinking\n",
173+ );
174+ expect(hasAnsi(getCapturedStdout(), "[2m")).toBe(true);
175+ expect(hasAnsi(getCapturedStdout(), "[3m")).toBe(true);
239176 expect(result.reasoningText).toBe("thinking");
240177 });
241178
@@ -251,7 +188,7 @@ describe("renderTurn", () => {
251188 new Spinner(),
252189 );
253190
254- expect(simulateTerminal(stdout)).toBe(
191+ expect(simulateTerminal(getCapturedStdout())).toBe(
255192 "· reasoning\n **Planning**\n **Confirming**\n",
256193 );
257194 expect(result.reasoningText).toBe("**Planning**\n**Confirming**");
@@ -269,7 +206,9 @@ describe("renderTurn", () => {
269206 new Spinner(),
270207 );
271208
272- expect(simulateTerminal(stdout)).toBe("· reasoning\n step\n\n◆ answer\n");
209+ expect(simulateTerminal(getCapturedStdout())).toBe(
210+ "· reasoning\n step\n\n◆ answer\n",
211+ );
273212 });
274213
275214 test("starts a new reasoning block after tool activity", async () => {
@@ -303,7 +242,7 @@ describe("renderTurn", () => {
303242 new Spinner(),
304243 );
305244
306- const plain = strip(stdout);
245+ const plain = stripAnsi(getCapturedStdout());
307246 expect(countOccurrences(plain, "· reasoning")).toBe(2);
308247 expect(plain).toContain("plan");
309248 expect(plain).toContain("$ echo hi");
@@ -327,7 +266,7 @@ describe("renderTurn", () => {
327266 spinner,
328267 );
329268
330- expect(strip(stdout)).toBe("◆ line 1\nline 2\n\n");
269+ expect(stripAnsi(getCapturedStdout())).toBe("◆ line 1\nline 2\n\n");
331270 expect(stopCalls).toBeGreaterThanOrEqual(2);
332271 });
333272
@@ -351,7 +290,7 @@ describe("renderTurn", () => {
351290 new Spinner(),
352291 );
353292
354- expect(strip(stdout)).toContain(
293+ expect(stripAnsi(getCapturedStdout())).toContain(
355294 "· context pruned balanced –30 messages –14.6 KB",
356295 );
357296 });
@@ -385,7 +324,7 @@ describe("renderTurn", () => {
385324 new Spinner(),
386325 );
387326
388- const plain = strip(stdout);
327+ const plain = stripAnsi(getCapturedStdout());
389328 expect(plain).toContain("· skill deploy · local · Deploy app");
390329 });
391330
@@ -410,9 +349,9 @@ describe("renderTurn", () => {
410349 }
411350
412351 // No erase-line or carriage-return sequences in output
413- expect(stdout.includes("\x1b[2K")).toBe(false);
414- expect(stdout.includes("\r")).toBe(false);
415- expect(strip(stdout)).toBe("◆ hello world\n");
352+ expect(getCapturedStdout().includes("\x1b[2K")).toBe(false);
353+ expect(getCapturedStdout().includes("\r")).toBe(false);
354+ expect(stripAnsi(getCapturedStdout())).toBe("◆ hello world\n");
416355 });
417356
418357 test("strips leading whitespace from the first text delta", async () => {
@@ -423,7 +362,7 @@ describe("renderTurn", () => {
423362 new Spinner(),
424363 );
425364
426- expect(simulateTerminal(stdout)).toBe("◆ hello\n");
365+ expect(simulateTerminal(getCapturedStdout())).toBe("◆ hello\n");
427366 });
428367
429368 test("skips whitespace-only deltas before actual text content", async () => {
@@ -439,7 +378,7 @@ describe("renderTurn", () => {
439378 new Spinner(),
440379 );
441380
442- expect(simulateTerminal(stdout)).toBe("◆ hello\n");
381+ expect(simulateTerminal(getCapturedStdout())).toBe("◆ hello\n");
443382 });
444383
445384 test("deduplicates repeated tool-call-start events for the same toolCallId", async () => {
@@ -477,7 +416,7 @@ describe("renderTurn", () => {
477416 new Spinner(),
478417 );
479418
480- const plain = strip(stdout);
419+ const plain = stripAnsi(getCapturedStdout());
481420 expect(countOccurrences(plain, "$ printf ok")).toBe(1);
482421 });
483422 });
src/cli/test-helpers.ts+87−0
@@ -1,3 +1,5 @@
1+import { terminal } from "./terminal-io.ts";
2+
13 /** Temporarily set process.stdout.columns for terminal tests. */
24 export async function withTerminalColumns(
35 cols: number,
@@ -24,3 +26,88 @@ export async function withTerminalColumns(
2426 }
2527 }
2628 }
29+
30+let _capturedStdout = "";
31+
32+const _originalDoStdoutWrite = terminal.doStdoutWrite.bind(terminal);
33+
34+export function captureStdout(): void {
35+ _capturedStdout = "";
36+ terminal.doStdoutWrite = (text: string) => {
37+ _capturedStdout += text;
38+ };
39+}
40+
41+export function getCapturedStdout(): string {
42+ return _capturedStdout;
43+}
44+
45+export function restoreStdout(): void {
46+ _capturedStdout = "";
47+ terminal.doStdoutWrite = _originalDoStdoutWrite;
48+}
49+
50+export function stripAnsi(text: string): string {
51+ const esc = String.fromCharCode(0x1b);
52+ return text.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "");
53+}
54+
55+/**
56+ * Simulate terminal rendering for cursor-control sequences:
57+ * `\r`, `\n`, `\x1b[2K` (erase line), `\x1b[1A` (cursor up).
58+ * Strips ANSI SGR codes so the result is plain text.
59+ */
60+export function simulateTerminal(raw: string): string {
61+ const esc = String.fromCharCode(0x1b);
62+ const noColor = raw.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "");
63+ const lines: string[] = [""];
64+ let row = 0;
65+ let col = 0;
66+ let i = 0;
67+
68+ const ensureRow = (idx: number): void => {
69+ while (lines.length <= idx) lines.push("");
70+ };
71+
72+ while (i < noColor.length) {
73+ const ch = noColor[i];
74+ if (ch === "\n") {
75+ row++;
76+ ensureRow(row);
77+ col = 0;
78+ i++;
79+ continue;
80+ }
81+ if (ch === "\r") {
82+ col = 0;
83+ i++;
84+ continue;
85+ }
86+ if (ch === esc && noColor[i + 1] === "[") {
87+ if (noColor[i + 2] === "2" && noColor[i + 3] === "K") {
88+ lines[row] = "";
89+ col = 0;
90+ i += 4;
91+ continue;
92+ }
93+ if (noColor[i + 2] === "1" && noColor[i + 3] === "A") {
94+ row = Math.max(0, row - 1);
95+ col = Math.min(col, lines[row]?.length ?? 0);
96+ i += 4;
97+ continue;
98+ }
99+ }
100+
101+ ensureRow(row);
102+ const line = lines[row] ?? "";
103+ if (col >= line.length) {
104+ lines[row] = line + ch;
105+ } else {
106+ lines[row] = `${line.slice(0, col)}${ch}${line.slice(col + 1)}`;
107+ }
108+ col++;
109+ i++;
110+ }
111+
112+ return lines.join("\n");
113+}
src/cli/tool-render.test.ts+12−22
@@ -1,26 +1,16 @@
11 import { afterEach, describe, expect, test } from "bun:test";
2-import { terminal } from "./terminal-io.ts";
2+import {
3+ captureStdout,
4+ getCapturedStdout,
5+ restoreStdout,
6+ stripAnsi,
7+} from "./test-helpers.ts";
38 import { buildToolCallLine, renderToolResult } from "./tool-render.ts";
49
5-let stdout = "";
6-const originalStdoutWrite = terminal.stdoutWrite.bind(terminal);
7-
810 afterEach(() => {
9- stdout = "";
10- terminal.stdoutWrite = originalStdoutWrite;
11+ restoreStdout();
1112 });
1213
13-function captureStdout(): void {
14- terminal.stdoutWrite = (text: string) => {
15- stdout += text;
16- };
17-}
18-
19-function stripAnsi(text: string): string {
20- const esc = String.fromCharCode(0x1b);
21- return text.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "");
22-}
23-
2414 describe("buildToolCallLine", () => {
2515 test("formats shell calls with truncated command previews", () => {
2616 const line = buildToolCallLine("shell", {
@@ -69,7 +59,7 @@ describe("renderToolResult", () => {
6959 false,
7060 );
7161
72- const plain = stripAnsi(stdout);
62+ const plain = stripAnsi(getCapturedStdout());
7363 expect(plain).toContain("error exit 1 · stderr 1L");
7464 expect(plain).toContain("│ boom");
7565 });
@@ -89,7 +79,7 @@ describe("renderToolResult", () => {
8979 false,
9080 );
9181
92- const plain = stripAnsi(stdout);
82+ const plain = stripAnsi(getCapturedStdout());
9383 expect(plain).toContain("done exit 0 · stdout 2L");
9484 expect(plain).toContain("stdout (2 lines)");
9585 expect(plain).toContain("│ hello");
@@ -115,7 +105,7 @@ describe("renderToolResult", () => {
115105 false,
116106 );
117107
118- const plain = stripAnsi(stdout);
108+ const plain = stripAnsi(getCapturedStdout());
119109 expect(plain).toContain("│ line-1");
120110 expect(plain).toContain("│ line-10");
121111 expect(plain).toContain("… +10 lines");
@@ -143,7 +133,7 @@ describe("renderToolResult", () => {
143133 { verboseOutput: true },
144134 );
145135
146- const plain = stripAnsi(stdout);
136+ const plain = stripAnsi(getCapturedStdout());
147137 expect(plain).toContain("│ line-1");
148138 expect(plain).toContain("│ line-8");
149139 expect(plain).not.toContain("… +");
@@ -163,7 +153,7 @@ describe("renderToolResult", () => {
163153 false,
164154 );
165155
166- const plain = stripAnsi(stdout);
156+ const plain = stripAnsi(getCapturedStdout());
167157 expect(plain).toContain("deploy · local · Deploy safely");
168158 expect(plain).toContain("release · global · Ship releases");
169159 });
src/cli/ui-audit.test.ts+498−0
@@ -0,0 +1,498 @@
1+import { afterEach, describe, expect, test } from "bun:test";
2+import type { TurnEvent } from "../llm-api/types.ts";
3+import { renderError, renderUserMessage } from "./output.ts";
4+import { Spinner } from "./spinner.ts";
5+import { renderTurn } from "./stream-render.ts";
6+import {
7+ captureStdout,
8+ getCapturedStdout,
9+ restoreStdout,
10+ simulateTerminal,
11+ stripAnsi,
12+} from "./test-helpers.ts";
13+import { renderToolCall, renderToolResult } from "./tool-render.ts";
14+
15+afterEach(() => {
16+ restoreStdout();
17+});
18+
19+function eventsFrom(events: TurnEvent[]): AsyncIterable<TurnEvent> {
20+ return (async function* () {
21+ for (const event of events) {
22+ yield event;
23+ }
24+ })();
25+}
26+
27+function done(): TurnEvent {
28+ return {
29+ type: "turn-complete",
30+ inputTokens: 10,
31+ outputTokens: 20,
32+ contextTokens: 100,
33+ messages: [],
34+ };
35+}
36+
37+function shellResult(opts: {
38+ stdout?: string;
39+ stderr?: string;
40+ exitCode?: number;
41+ success?: boolean;
42+}) {
43+ return {
44+ stdout: opts.stdout ?? "",
45+ stderr: opts.stderr ?? "",
46+ exitCode: opts.exitCode ?? 0,
47+ success: opts.success ?? true,
48+ timedOut: false,
49+ };
50+}
51+
52+// ─── Visual hierarchy documentation ───────────────────────────────────────────
53+//
54+// The output hierarchy from the user's perspective should be:
55+//
56+// [0-indent] › user message (green ›)
57+// [0-indent] · reasoning (dim · header)
58+// [2-space] reasoning body text (dim italic)
59+// [0-indent] ◆ assistant reply (cyan ◆)
60+// [2-space] $ shell command (dim $, tool call)
61+// [2-space] ⇢ subagent prompt (cyan ⇢, tool call)
62+// [4-space] done exit 0 · ... (tool result badge)
63+// [4-space] stderr (N lines) (tool result preview label)
64+// [4-space] │ preview line (tool result preview content)
65+// [0-indent] · info message (dim ·)
66+// [0-indent] ✖ error message (red ✖)
67+// [2-space] hint text (dim hint)
68+// [0-indent] · context pruned ... (dim ·)
69+//
70+// Between blocks (reasoning→text, text→tool, tool→reasoning, etc.):
71+// A single blank line separates visually distinct blocks.
72+
73+describe("UI audit: output hierarchy", () => {
74+ describe("user message rendering", () => {
75+ test("single-line message has › prefix at column 0", () => {
76+ captureStdout();
77+ renderUserMessage("hello world");
78+ expect(stripAnsi(getCapturedStdout())).toBe("› hello world\n");
79+ });
80+
81+ test("multi-line message indents continuations with 2 spaces", () => {
82+ captureStdout();
83+ renderUserMessage("line 1\nline 2\nline 3");
84+ expect(stripAnsi(getCapturedStdout())).toBe(
85+ "› line 1\n line 2\n line 3\n",
86+ );
87+ });
88+ });
89+
90+ describe("tool call rendering", () => {
91+ test("shell call is indented 2 spaces with $ glyph", () => {
92+ captureStdout();
93+ renderToolCall("shell", { command: "echo hi" });
94+ expect(stripAnsi(getCapturedStdout())).toBe(" $ echo hi\n");
95+ });
96+
97+ test("subagent call is indented 2 spaces with ⇢ glyph", () => {
98+ captureStdout();
99+ renderToolCall("subagent", {
100+ prompt: "Review code",
101+ agentName: "reviewer",
102+ });
103+ const plain = stripAnsi(getCapturedStdout());
104+ expect(plain).toStartWith(" ⇢");
105+ expect(plain).toContain("[@reviewer]");
106+ expect(plain).toContain("Review code");
107+ });
108+
109+ test("readSkill call is indented 2 spaces with ← glyph", () => {
110+ captureStdout();
111+ renderToolCall("readSkill", { name: "deploy" });
112+ const plain = stripAnsi(getCapturedStdout());
113+ expect(plain).toStartWith(" ←");
114+ expect(plain).toContain("read skill");
115+ expect(plain).toContain("deploy");
116+ });
117+
118+ test("MCP tool call is indented 2 spaces with ⚙ glyph", () => {
119+ captureStdout();
120+ renderToolCall("mcp_myserver_do_thing", { arg: "val" });
121+ const plain = stripAnsi(getCapturedStdout());
122+ expect(plain).toStartWith(" ⚙");
123+ });
124+ });
125+
126+ describe("tool result rendering", () => {
127+ test("successful shell result badge is indented 4 spaces", () => {
128+ captureStdout();
129+ renderToolResult("shell", shellResult({ stdout: "ok" }), false);
130+ const plain = stripAnsi(getCapturedStdout());
131+ expect(plain).toMatch(/^ {4}done/m);
132+ });
133+
134+ test("failed shell result badge is indented 4 spaces", () => {
135+ captureStdout();
136+ renderToolResult(
137+ "shell",
138+ shellResult({ stderr: "fail", exitCode: 1, success: false }),
139+ false,
140+ );
141+ const plain = stripAnsi(getCapturedStdout());
142+ expect(plain).toMatch(/^ {4}error/m);
143+ });
144+
145+ test("shell stderr preview lines are indented 4 spaces with │", () => {
146+ captureStdout();
147+ renderToolResult(
148+ "shell",
149+ shellResult({ stderr: "bad\nstuff", exitCode: 1, success: false }),
150+ false,
151+ );
152+ const plain = stripAnsi(getCapturedStdout());
153+ expect(plain).toContain(" │ bad");
154+ expect(plain).toContain(" │ stuff");
155+ });
156+
157+ test("shell stdout preview lines are indented 4 spaces with │", () => {
158+ captureStdout();
159+ renderToolResult("shell", shellResult({ stdout: "line1\nline2" }), false);
160+ const plain = stripAnsi(getCapturedStdout());
161+ expect(plain).toContain(" │ line1");
162+ expect(plain).toContain(" │ line2");
163+ });
164+
165+ test("tool error badge is indented 4 spaces", () => {
166+ captureStdout();
167+ renderToolResult("shell", "something broke", true);
168+ const plain = stripAnsi(getCapturedStdout());
169+ expect(plain).toMatch(/^ {4}✖/m);
170+ });
171+
172+ test("subagent result is indented 4 spaces", () => {
173+ captureStdout();
174+ renderToolResult(
175+ "subagent",
176+ { inputTokens: 100, outputTokens: 50, agentName: "reviewer" },
177+ false,
178+ );
179+ const plain = stripAnsi(getCapturedStdout());
180+ expect(plain).toMatch(/^ {4}⇢/m);
181+ });
182+ });
183+
184+ describe("error rendering", () => {
185+ test("error headline is at column 0 with ✖ glyph", () => {
186+ captureStdout();
187+ renderError("something went wrong");
188+ const plain = stripAnsi(getCapturedStdout());
189+ expect(plain).toMatch(/^✖ something went wrong/m);
190+ });
191+ });
192+});
193+
194+describe("UI audit: full turn scenarios", () => {
195+ test("simple text reply: reasoning → reply with blank line separator", async () => {
196+ captureStdout();
197+
198+ await renderTurn(
199+ eventsFrom([
200+ { type: "reasoning-delta", delta: "Let me think" },
201+ { type: "text-delta", delta: "Here is the answer." },
202+ done(),
203+ ]),
204+ new Spinner(),
205+ );
206+
207+ const plain = simulateTerminal(getCapturedStdout());
208+ expect(plain).toBe(
209+ "· reasoning\n Let me think\n\n◆ Here is the answer.\n",
210+ );
211+ });
212+
213+ test("tool use: tool-call → tool-result → reply", async () => {
214+ captureStdout();
215+
216+ await renderTurn(
217+ eventsFrom([
218+ {
219+ type: "tool-call-start",
220+ toolName: "shell",
221+ toolCallId: "t1",
222+ args: { command: "ls" },
223+ },
224+ {
225+ type: "tool-result",
226+ toolName: "shell",
227+ toolCallId: "t1",
228+ isError: false,
229+ result: shellResult({ stdout: "file.txt" }),
230+ },
231+ { type: "text-delta", delta: "Found file.txt" },
232+ done(),
233+ ]),
234+ new Spinner(),
235+ );
236+
237+ const plain = simulateTerminal(getCapturedStdout());
238+ // Tool call at 2-space indent
239+ expect(plain).toContain(" $ ls");
240+ // Tool result at 4-space indent
241+ expect(plain).toMatch(/^ {4}done/m);
242+ // Reply at 0-indent with blank line before
243+ expect(plain).toContain("\n\n◆ Found file.txt");
244+ });
245+
246+ test("multiple tools: each tool-call/result pair is visually grouped", async () => {
247+ captureStdout();
248+
249+ await renderTurn(
250+ eventsFrom([
251+ {
252+ type: "tool-call-start",
253+ toolName: "shell",
254+ toolCallId: "t1",
255+ args: { command: "cat a.txt" },
256+ },
257+ {
258+ type: "tool-result",
259+ toolName: "shell",
260+ toolCallId: "t1",
261+ isError: false,
262+ result: shellResult({ stdout: "hello" }),
263+ },
264+ {
265+ type: "tool-call-start",
266+ toolName: "shell",
267+ toolCallId: "t2",
268+ args: { command: "cat b.txt" },
269+ },
270+ {
271+ type: "tool-result",
272+ toolName: "shell",
273+ toolCallId: "t2",
274+ isError: false,
275+ result: shellResult({ stdout: "world" }),
276+ },
277+ done(),
278+ ]),
279+ new Spinner(),
280+ );
281+
282+ const plain = simulateTerminal(getCapturedStdout());
283+ // Both tool calls present
284+ expect(plain).toContain(" $ cat a.txt");
285+ expect(plain).toContain(" $ cat b.txt");
286+ // Blank line between first result and second call
287+ const lines = plain.split("\n");
288+ const firstResultIdx = lines.findIndex((l) =>
289+ l.match(/^ {4}done.*out: hello/),
290+ );
291+ const secondCallIdx = lines.findIndex((l) => l.includes("$ cat b.txt"));
292+ expect(firstResultIdx).toBeGreaterThan(-1);
293+ expect(secondCallIdx).toBeGreaterThan(firstResultIdx);
294+ // There should be a blank line between the first result and second tool call
295+ const between = lines.slice(firstResultIdx + 1, secondCallIdx);
296+ expect(between.some((l) => l.trim() === "")).toBe(true);
297+ });
298+
299+ test("reasoning → tool → reasoning → reply: two reasoning blocks", async () => {
300+ captureStdout();
301+
302+ await renderTurn(
303+ eventsFrom([
304+ { type: "reasoning-delta", delta: "plan A" },
305+ {
306+ type: "tool-call-start",
307+ toolName: "shell",
308+ toolCallId: "t1",
309+ args: { command: "echo test" },
310+ },
311+ {
312+ type: "tool-result",
313+ toolName: "shell",
314+ toolCallId: "t1",
315+ isError: false,
316+ result: shellResult({ stdout: "test" }),
317+ },
318+ { type: "reasoning-delta", delta: "plan B" },
319+ { type: "text-delta", delta: "done" },
320+ done(),
321+ ]),
322+ new Spinner(),
323+ );
324+
325+ const plain = simulateTerminal(getCapturedStdout());
326+ // Two separate reasoning blocks
327+ const reasoningCount = (plain.match(/· reasoning/g) ?? []).length;
328+ expect(reasoningCount).toBe(2);
329+ expect(plain).toContain("plan A");
330+ expect(plain).toContain("plan B");
331+ });
332+
333+ test("context-pruned event renders at 0-indent with · glyph", async () => {
334+ captureStdout();
335+
336+ await renderTurn(
337+ eventsFrom([
338+ {
339+ type: "context-pruned",
340+ mode: "balanced",
341+ beforeMessageCount: 100,
342+ afterMessageCount: 80,
343+ removedMessageCount: 20,
344+ beforeTotalBytes: 30000,
345+ afterTotalBytes: 20000,
346+ removedBytes: 10000,
347+ },
348+ { type: "text-delta", delta: "continuing" },
349+ done(),
350+ ]),
351+ new Spinner(),
352+ );
353+
354+ const plain = simulateTerminal(getCapturedStdout());
355+ expect(plain).toContain("· context pruned");
356+ expect(plain).toContain("balanced");
357+ expect(plain).toContain("–20 messages");
358+ });
359+
360+ test("text reply with no reasoning: just ◆ prefix", async () => {
361+ captureStdout();
362+
363+ await renderTurn(
364+ eventsFrom([{ type: "text-delta", delta: "Hello!" }, done()]),
365+ new Spinner(),
366+ );
367+
368+ const plain = simulateTerminal(getCapturedStdout());
369+ expect(plain).toBe("◆ Hello!\n");
370+ });
371+
372+ test("tool error shows ✖ at 4-space indent", async () => {
373+ captureStdout();
374+
375+ await renderTurn(
376+ eventsFrom([
377+ {
378+ type: "tool-call-start",
379+ toolName: "shell",
380+ toolCallId: "t1",
381+ args: { command: "bad-cmd" },
Cut short: this commit's diff is over 1000 lines.