xonecas.io
64875
Mc

mini-coder / commit a1ea883

feat(ui): align conversation log rendering with spec

xonecas2026-04-09 a1ea8836cb7c6c77ca2bcecd9d89c500a282beab parent db0be01

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+5−3
@@ -1,19 +1,21 @@
11 # TODO
22
33 Keep this always updated so work can continue across sessions.
4-Don't keep completed items bloating the file.
4+Don't keep completed items bloating the file, remove them before committing.
55 Keep the file structured and minimal.
66 The spec.md and code are the sources of truth, not this file, don't assume anything because it's documented here.
77
8+## In progress
9+
10+- None right now.
11+
812 ## Open items
913
1014 - None right now.
1115
1216 ## Low priority (deffered until further notice)
1317
14-- [ ] **Reduce duplicate edit rendering in the conversation log** (`ui/conversation.ts`) — large edits currently appear twice in a row (tool-call preview and tool-result diff), which adds a lot of vertical noise.
1518 - [ ] **Prevent `/session` from switching sessions mid-run** (`ui/commands.ts`, `ui/agent.ts`) — selecting a session while a turn is active can desync UI state from the session the loop is still writing to.
16-- [ ] **Compact reasoning-heavy turns a bit better when `/reasoning` is on** (`ui/conversation.ts`) — for trivial prompts, visible reasoning can dominate the screen and bury the actual answer.
1719 - [ ] **XML-escape generated skill catalog fields** (`skills.ts`) — skill names, descriptions, and paths containing XML metacharacters can break the `<available_skills>` prompt block.
1820
1921 ## Plugin related (documented only, no plugin related work is planned right now)
spec.md+172−17
@@ -54,7 +54,6 @@ This replaces: `yoctocolors`, `yoctomarkdown`, `yoctoselect`, and all our custom
5454
5555 - **Runtime**: Bun — for runtime, bundling, testing, and `bun:sqlite`.
5656 - **Schema validation**: TypeBox (re-exported from pi-ai) for tool schemas.
57-- **Diffing**: `diff` (jsdiff) — `structuredPatch` for line-level unified diffs in edit tool output.
5857
5958 ## Tools
6059
@@ -267,7 +266,7 @@ You are mini-coder, a coding agent running in the user's terminal.
267266
268267 # Role
269268
270-You are an autonomous, senior-level coding assistant. When the user gives a direction, proactively gather context, plan, implement, and verify without waiting for additional prompts at each step. Bias toward action: make reasonable assumptions and deliver working code rather than asking clarifying questions, unless you are genuinely blocked.
269+You are an autonomous, senior-level coding assistant. When the user gives a direction, proactively gather context, plan with the user, implement, and verify. Bias toward action: use planning first to clear any assumptions with the user, then implement the plan. Deliver working code, unless you are genuinely blocked.
271270
272271 # Tools
273272
@@ -373,7 +372,7 @@ Key decisions informed by the Codex prompting guide and Claude prompting best pr
373372 - **Autonomy and persistence**: both guides emphasize that coding agents should bias toward action, persist through errors, and complete work end-to-end. The prompt explicitly states this.
374373 - **Inspect → mutate → verify**: the Codex guide's recommended workflow. Makes the two-tool surface sufficient.
375374 - **Batch reads**: both guides stress parallel tool calling. The prompt instructs the model to think first and batch.
376-- **No plan dumping**: the Codex guide notes that prompting for upfront plans can cause models to stop prematurely. We ask for action, not plans.
375+- **Brief planning, not plan dumping**: the Codex guide notes that prompting for large upfront plans can cause models to stop prematurely. The prompt now asks the agent to plan with the user just enough to clear assumptions, then continue into implementation.
377376 - **Edit discipline**: derived from Codex's editing constraints (don't revert others' changes, no destructive git, ASCII default).
378377 - **Concise communication**: both guides recommend against verbose summaries. The prompt asks for brief explanations focused on what changed.
379378 - **Model-agnostic**: no provider-specific instructions. Works across Anthropic, OpenAI, Google, and others. Uses XML tags for structure (well-understood by all major models).
@@ -393,14 +392,18 @@ Three zones, top to bottom:
393392 │ │
394393 │ I'll check the test suite first. │ agent: default bg
395394 │ │
396-│ │ $ bun test │ tool: left border
395+│ │ [shell ->] bun test │ tool call
396+│ │ [shell <-] │ tool result
397397 │ │ 3 passed, 1 failed │ dimmed text
398398 │ │ FAIL src/agent.test.ts > handles error │
399399 │ │ exit 1 │
400400 │ │ │
401-│ │ ~ src/agent.ts │ edit: path + diff
402-│ │ - expect(result).toBe("stop"); │ red removed
403-│ │ + expect(result).toBe("error"); │ green added
401+│ │ [edit ->] │ edit preview
402+│ │ src/agent.ts │
403+│ │ expect(result).toBe("error"); │
404+│ │ │
405+│ │ [edit <-] │ compact result
406+│ │ ~ src/agent.ts │
404407 │ │ │
405408 │ Fixed the assertion. Tests pass now. │
406409 │ │
@@ -455,9 +458,6 @@ interface Theme {
455458 /** Tool output left border and text. */
456459 toolBorder: Color | undefined;
457460 toolText: Color | undefined;
458- /** Diff colors in edit tool output. */
459- diffAdded: Color | undefined;
460- diffRemoved: Color | undefined;
461461 /** Divider line color (idle state). */
462462 divider: Color | undefined;
463463 /** Divider scanning pulse highlight color (active state). */
@@ -512,18 +512,30 @@ One line, two-sided, rendered as compact padded pills rather than a full-width f
512512
513513 Token counts use human-friendly units (1.2k, 45k, 1.2M). Context usage is estimated from the current model-visible conversation, not just the last assistant message. Use the most recent valid assistant `usage` as an anchor (`totalTokens` when present, otherwise `input + output + cacheRead + cacheWrite`) and add heuristic estimates for any later messages. If no assistant `usage` exists yet, estimate the full current model-visible history heuristically. UI-only messages are excluded from this esti …
514514
515+#### Status bar sketches
516+
517+```text
518+[ anthropic/sonnet-4 · med ] [ ~/src/mini-coder ] [ main +3 ~1 ▲ 2 ] [ in:1.2k out:0.8k · 42.0%/200k · $0.03 ]
519+[ openai/gpt-5-mini · low ] [ ~/src/mini-coder ] [ in:220 out:90 · 8.0%/200k · $0.00 ]
520+[ openrouter/qwen3-coder · xhigh ] [ …/mini-coder ] [ feat/ui ~4 ?2 ▲ 7 ] [ in:180k out:24k · 93.0%/200k · $2.10 ]
521+```
522+
523+The outer-left pill tone changes with effort, the outer-right pill tone changes with context pressure, and the inner pills stay neutral.
524+
515525 ### Conversation log
516526
517527 Scrollable area that shows the full conversation history. Stick-to-bottom by default (new content auto-scrolls), user can scroll up to review, scrolling back to bottom re-enables auto-scroll. Conversation updates are streamed into this log as they happen; the UI should not wait for a completed turn before showing progress.
518528
519529 Message types and their rendering:
520530
531+Tool blocks share a common frame: a left border (`│`) plus a compact header pill naming the tool and direction (`[tool ->]` for assistant tool calls, `[tool <-]` for tool results). The body renders tool-specific content rather than raw JSON.
532+
521533 - **User messages**: displayed as plain text with a subtle background color to distinguish them from agent responses. No prefix or role indicator.
522534 - **Assistant messages**: streamed markdown rendered via cel-tui's `Markdown` component on the default background. Thinking/reasoning content is collapsible (shown or hidden according to the user's persisted `/reasoning` preference; defaults to shown when no setting exists).
523-- **Tool calls — shell**: rendered with a left border (`│`) and dimmed foreground. The assistant tool call streams the arguments as they arrive. The command preview and shell tool result body use [verbose tool rendering](#verbose-tool-rendering). The shell tool result is rendered as the tool output (not the raw json, the content), with no extra header or placeholder lines.
524-- **Tool calls — edit**: rendered with a left border (`│`) and dimmed foreground. Shows the arguments streamed in, preserving whitespace (the content of the arguments, not JSON). The in-progress tool-call preview uses [verbose tool rendering](#verbose-tool-rendering). Successful results then show a unified diff of the change (added lines in green, removed in red) in full. Uses the `diff` package (`structuredPatch`) for line-level unified diffs.
525-- **Tool calls — readImage**: rendered with a left border (`│`) and dimmed foreground. The assistant tool call streams the arguments as they arrive (the path, not the JSON). Successful tool results display the text `Read image.` instead of rendering the image itself.
526-- **Tool calls — plugin tools**: rendered with a left border, prefixed with plugin/tool name.
535+- **Tool calls — shell**: rendered in the shared tool frame. The assistant tool call streams the command as it arrives. The command preview and shell tool result body use [verbose tool rendering](#verbose-tool-rendering). Shell tool results render the tool output content below a `[shell <-]` header.
536+- **Tool calls — edit**: rendered in the shared tool frame. The in-progress tool-call preview shows the target path plus the streamed replacement content, preserving whitespace. The preview body uses [verbose tool rendering](#verbose-tool-rendering). Successful results render a compact confirmation block (`[edit <-]` plus the file path); errors render the returned error text.
537+- **Tool calls — readImage**: rendered in the shared tool frame. The assistant tool call streams the path as it arrives. Successful results render a compact result block (`[read image <-]` plus the file path) rather than rendering the image itself.
538+- **Tool calls — plugin tools**: rendered in the shared tool frame, prefixed with plugin/tool name when available.
527539 - **UI messages**: internal app messages such as `/help` output, OAuth progress, and other session-local notices. They are rendered in the conversation log, persisted with the session, excluded from model context, and do not participate in conversational turn numbering.
528540 - **Errors**: one-line summary, styled distinctly.
529541
@@ -531,15 +543,141 @@ Message types and their rendering:
531543
532544 `/verbose` controls a single persisted UI preference for how tool-call previews and selected tool-result bodies are displayed in the conversation log.
533545
534-- Scope: shell tool-call bodies, shell tool-result bodies, edit tool-call preview bodies, and edit error results only. Successful edit results render as a unified diff, and that diff is always shown in full.
546+- Scope: shell tool-call bodies, shell tool-result bodies, edit tool-call preview bodies, and edit error results only. Successful edit results stay compact in both modes.
535547 - Default: off when no saved setting exists.
536-- Off: show the last 8 lines followed by `And X lines more` when additional lines exist.
548+- Off: show as many trailing logical lines as fit within a fixed rendered-height preview, followed by `And X lines more` when earlier lines are hidden. The preview height stays stable for a given block, so wrapped long lines do not make the log jump while content streams.
537549 - On: show the full stored tool result or preview body.
538550 - Persistence: the new on/off state is saved immediately and restored on launch.
539551 - This is a UI-only display choice over streamed tool-call previews and stored tool results; it does not affect tool execution or the shell tool's own safety truncation for pathological output.
540552
553+#### Conversation log sketches
554+
555+Representative entry shapes:
556+
557+**User**
558+
559+```text
560+ ┌─────────────────────────────────────────────┐
561+ │ fix the failing session tests │
562+ └─────────────────────────────────────────────┘
563+```
564+
565+**Assistant (`/reasoning` on)**
566+
567+```text
568+ I should run the focused session tests first and inspect turn assignment.
569+ Then report any issues to the user.
570+ That is good reasoning for my next steps.
571+
572+ I'll run the session tests first.
573+```
574+
575+**Assistant (`/reasoning` off)**
576+
577+```text
578+ Thinking... 3 lines.
579+
580+ I'll run the session tests first.
581+```
582+
583+**Shell tool call**
584+
585+```text
586+ │ [shell ->] bun test src/session.test.ts
587+```
588+
589+**Shell tool result (`/verbose` off)**
590+
591+```text
592+ │ [shell <-]
593+ │ src/session.test.ts:
594+ │ ✓ loads persisted turns
595+ │ ✓ undoes the latest turn
596+ │ ✗ keeps ui messages out of model context
597+ │
598+ │ 1 failed, 2 passed
599+ │ exit 1
600+ │ And 14 lines more
601+```
602+
603+**Shell tool result (`/verbose` on)**
604+
605+```text
606+ │ [shell <-]
607+ │ src/session.test.ts:
608+ │ ✓ loads persisted turns
609+ │ ✓ undoes the latest turn
610+ │ ✗ keeps ui messages out of model context
611+ │
612+ │ AssertionError: expected 2 to be 1
613+ │ at <anonymous> (src/session.test.ts:84:23)
614+ │ exit 1
615+```
616+
617+**Edit tool call preview (`/verbose` off)**
618+
619+```text
620+ │ [edit ->]
621+ │ src/session.ts
622+ │ const turn = getCurrentTurn(sessionId);
623+ │ saveMessage(sessionId, turn, message);
624+ │ And 9 lines more
625+```
626+
627+**Edit tool call preview (`/verbose` on)**
628+
629+```text
630+ │ [edit ->]
631+ │ src/session.ts
632+ │ const turn = getNextTurn(sessionId);
633+ │ saveMessage(sessionId, turn, message);
634+ │ return turn;
635+```
636+
637+**Edit tool result**
638+
639+```text
640+ │ [edit <-]
641+ │ ~ src/session.ts
642+```
643+
644+**ReadImage tool**
645+
646+```text
647+ │ [read image <-]
648+ │ screenshots/failing-layout.png
649+```
650+
651+**Plugin tool**
652+
653+```text
654+ │ [mcp/search <-]
655+ │ session persistence sqlite turn numbering
656+```
657+
658+**UI message**
659+
660+```text
661+ Loaded 3 skills from ~/.agents/skills
662+```
663+
664+**Error**
665+
666+```text
667+ Error: command exited with code 2
668+```
669+
541670 While the agent is working, the top divider (above the input area) animates with a scanning pulse — a bright and colored (be creative) segment sweeping across the dimmed divider line. The animation starts when a turn begins and stops when the turn ends (done, error, or aborted). No per-activity state tracking.
542671
672+#### Divider sketches
673+
674+```text
675+idle: ────────────────────────────────────────────────────────────
676+frame1: ────══════──────────────────────────────────────────────────
677+frame2: ─────────────══════─────────────────────────────────────────
678+frame3: ────────────────────────══════──────────────────────────────
679+```
680+
543681 ### Input area
544682
545683 Multi-line text input with no prompt prefix — the blinking cursor is the affordance. Intrinsic height starts at 2 lines when empty (`minHeight: 2`), grows with content up to `maxHeight: 10`, then scrolls internally. Enter submits, Shift+Enter adds newlines (via cel-tui's `TextInput` `onKeyPress` pattern).
@@ -552,6 +690,23 @@ Supports:
552690 - `/skill:skill-name` prefix to inject a skill's body into the user message. The `/skill:name` prefix is stripped from the input and the skill's `SKILL.md` body is prepended to the user message content. The rest of the input becomes the user's instruction. Example: `/skill:code-review check the auth module` sends the code-review skill body + "check the auth module" as the user message.
553691 - Image embedding: if we autocomplete a file path ending in `.png`, `.jpg`, `.jpeg`, `.gif`, or `.webp`, and the file exists, it is embedded as `ImageContent` in the user message (base64-encoded). Only when the current model supports image input (`Model.input` includes `"image"`). If the model doesn't support images, or the file doesn't exist, or the input contains other text, the path is sent as plain text. This is intentionally simple — no inline detection within sentences.
554692
693+#### Input area sketches
694+
695+Empty input still reserves 2 lines of height; examples below only show visible text.
696+
697+```text
698+fix the remaining lint warnings_
699+
700+fix the remaining lint warnings
701+in the utils file too_
702+
703+summarize the issue
704+compare the current flow
705+explain the regression
706+...
707+add tests for undo_
708+```
709+
555710 ### Key bindings
556711
557712 | Key | Context | Action |
@@ -576,7 +731,7 @@ Supports:
576731 | `/fork` | Fork the current conversation into a new session. Copies the full message history, continues from here independently. The original session is preserved. |
577732 | `/undo` | Remove the last conversational turn from history: the most recent user message and all assistant/tool messages that followed in that turn. Persisted UI messages are not part of turns and are not removed by `/undo`. Context-only — does not revert filesystem changes. |
578733 | `/reasoning` | Toggle display of model thinking/reasoning content in the log. The new on/off state is persisted immediately and restored on launch. When no setting exists yet, reasoning defaults to shown. |
579-| `/verbose` | Toggle [verbose tool rendering](#verbose-tool-rendering) for shell previews/results, edit previews, and edit errors. Successful edit diffs always render in full. |
734+| `/verbose` | Toggle [verbose tool rendering](#verbose-tool-rendering) for shell previews/results, edit previews, and edit errors. Successful edit results stay compact regardless of this setting. |
580735 | `/login` | Interactive OAuth login. Shows a selector with available OAuth providers and their login status (logged in / not logged in). Selecting a provider starts the browser-based OAuth flow. Uses pi-ai's OAuth registry. Credentials are persisted to the app data directory and used for provider discovery on subsequent launches. |
581736 | `/logout` | Interactive OAuth logout. Shows a selector with logged-in OAuth providers. Selecting one clears its saved credentials. |
582737 | `/effort` | Interactive effort selector. Shows the four reasoning levels (`low`, `medium`, `high`, `xhigh`) with the current level highlighted. Updates the status bar immediately, and the selected effort is persisted immediately as the user's global default. The session record's `effort` field is not updated (it reflects the initial choice, like `/model`). |
src/prompt.ts+1−1
@@ -185,7 +185,7 @@ const BASE_INSTRUCTIONS = `You are mini-coder, a coding agent running in the use
185185
186186 # Role
187187
188-You are an autonomous, senior-level coding assistant. When the user gives a direction, proactively gather context, plan, implement, and verify without waiting for additional prompts at each step. Bias toward action: make reasonable assumptions and deliver working code rather than asking clarifying questions, unless you are genuinely blocked.
188+You are an autonomous, senior-level coding assistant. When the user gives a direction, proactively gather context, plan with the user, implement, and verify. Bias toward action: use planning first to clear any assumptions with the user, then implement the plan. Deliver working code, unless you are genuinely blocked.
189189
190190 # Tools
191191
src/theme.ts+2−2
@@ -48,9 +48,9 @@ export interface Theme {
4848 toolBorder: ThemeColor;
4949 /** Tool output text. */
5050 toolText: ThemeColor;
51- /** Diff added line color (green). */
51+ /** Added/replacement edit preview text. */
5252 diffAdded: ThemeColor;
53- /** Diff removed line color (red). */
53+ /** Removed/original edit preview text. */
5454 diffRemoved: ThemeColor;
5555 /** Divider line color (idle state). */
5656 divider: ThemeColor;
src/ui.test.ts+19−7
@@ -27,7 +27,10 @@ import {
2727 } from "./session.ts";
2828 import { DEFAULT_SHOW_REASONING, DEFAULT_VERBOSE } from "./settings.ts";
2929 import { DEFAULT_THEME } from "./theme.ts";
30-import { buildConversationLogNodes } from "./ui/conversation.ts";
30+import {
31+ buildConversationLogNodes,
32+ CONVERSATION_GAP,
33+} from "./ui/conversation.ts";
3134 import {
3235 buildConversationLog,
3336 createInputController,
@@ -113,7 +116,7 @@ function measureConversationHeight(
113116 ): number {
114117 return measureContentHeight(
115118 VStack(
116- {},
119+ { gap: CONVERSATION_GAP },
117120 buildConversationLogNodes(
118121 state,
119122 {
@@ -122,6 +125,7 @@ function measureConversationHeight(
122125 pendingToolResults: [],
123126 },
124127 startIndex,
128+ width,
125129 ),
126130 ),
127131 { width },
@@ -1037,7 +1041,8 @@ describe("ui rendering", () => {
10371041 });
10381042 return (
10391043 state.running &&
1040- logText.includes("$ echo tool-output; sleep 0.2") &&
1044+ logText.includes("[shell ->]") &&
1045+ logText.includes("echo tool-output; sleep 0.2") &&
10411046 logText.includes("tool-output")
10421047 );
10431048 });
@@ -1049,8 +1054,9 @@ describe("ui rendering", () => {
10491054 });
10501055
10511056 expect(logText).toContain("I'll inspect the command output first.");
1057+ expect(logText.filter((line) => line === "[shell ->]")).toHaveLength(1);
10521058 expect(
1053- logText.filter((line) => line === "$ echo tool-output; sleep 0.2"),
1059+ logText.filter((line) => line === "echo tool-output; sleep 0.2"),
10541060 ).toHaveLength(1);
10551061 expect(logText).toContain("tool-output");
10561062 expect(logText).not.toContain("Exit code: 0");
@@ -1255,7 +1261,11 @@ describe("ui rendering", () => {
12551261 props: {},
12561262 children: buildConversationLog(state),
12571263 });
1258- return state.running && logText.includes("$ echo staged-command");
1264+ return (
1265+ state.running &&
1266+ logText.includes("[shell ->]") &&
1267+ logText.includes("echo staged-command")
1268+ );
12591269 });
12601270
12611271 const logText = collectText({
@@ -1264,8 +1274,9 @@ describe("ui rendering", () => {
12641274 children: buildConversationLog(state),
12651275 });
12661276
1277+ expect(logText.filter((line) => line === "[shell ->]")).toHaveLength(1);
12671278 expect(
1268- logText.filter((line) => line === "$ echo staged-command"),
1279+ logText.filter((line) => line === "echo staged-command"),
12691280 ).toHaveLength(1);
12701281 expect(logText).not.toContain("Preparing...");
12711282
@@ -1420,8 +1431,9 @@ describe("ui rendering", () => {
14201431 children: buildConversationLog(state),
14211432 });
14221433
1434+ expect(logText.filter((line) => line === "[shell ->]")).toHaveLength(1);
14231435 expect(
1424- logText.filter((line) => line === "$ echo tool-output"),
1436+ logText.filter((line) => line === "echo tool-output"),
14251437 ).toHaveLength(1);
14261438 expect(logText).toContain("tool-output");
14271439 expect(logText).toContain("Done streaming");
src/ui.ts+10−3
@@ -31,6 +31,7 @@ import {
3131 import { createCommandController } from "./ui/commands.ts";
3232 import {
3333 buildConversationLogNodes,
34+ CONVERSATION_GAP,
3435 resetConversationRenderCache,
3536 } from "./ui/conversation.ts";
3637 import type { InputController } from "./ui/input.ts";
@@ -195,11 +196,15 @@ function getVisibleConversationStart(messageCount: number): number {
195196 }
196197
197198 /** Build the full conversation log as an array of nodes. */
198-export function buildConversationLog(state: AppState): Node[] {
199+export function buildConversationLog(
200+ state: AppState,
201+ width = Number.POSITIVE_INFINITY,
202+): Node[] {
199203 return buildConversationLogNodes(
200204 state,
201205 getStreamingConversationState(),
202206 getVisibleConversationStart(state.messages.length),
207+ width,
203208 );
204209 }
205210
@@ -210,11 +215,12 @@ function measureConversationHeight(
210215 ): number {
211216 return measureContentHeight(
212217 VStack(
213- {},
218+ { gap: CONVERSATION_GAP },
214219 buildConversationLogNodes(
215220 state,
216221 getStreamingConversationState(),
217222 startIndex,
223+ width,
218224 ),
219225 ),
220226 { width: Math.max(1, width) },
@@ -481,6 +487,7 @@ function renderConversationLog(state: AppState, width: number): Node {
481487 return VStack(
482488 {
483489 flex: 1,
490+ gap: CONVERSATION_GAP,
484491 overflow: "scroll",
485492 scrollbar: true,
486493 scrollOffset: stickToBottom ? Infinity : scrollOffset,
@@ -503,7 +510,7 @@ function renderConversationLog(state: AppState, width: number): Node {
503510 cel.render();
504511 },
505512 },
506- buildConversationLog(state),
513+ buildConversationLog(state, width),
507514 );
508515 }
509516
src/ui/conversation.test.ts+555−252
@@ -1,4 +1,11 @@
11 import { afterEach, describe, expect, test } from "bun:test";
2+import {
3+ cel,
4+ MockTerminal,
5+ measureContentHeight,
6+ Text,
7+ VStack,
8+} from "@cel-tui/core";
29 import type { Node } from "@cel-tui/types";
310 import {
411 fauxAssistantMessage,
@@ -10,17 +17,17 @@ import { DEFAULT_THEME } from "../theme.ts";
1017 import {
1118 buildConversationLogNodes,
1219 type PendingToolResult,
13- previewToolRenderLines,
1420 renderAssistantMessage,
1521 renderToolResult,
1622 resetConversationRenderCache,
17- type ToolRenderLine,
1823 } from "./conversation.ts";
1924
25+const PREVIEW_WIDTH = 32;
2026 const RENDER_OPTS = {
2127 showReasoning: false,
2228 verbose: false,
2329 theme: DEFAULT_THEME,
30+ previewWidth: PREVIEW_WIDTH,
2431 };
2532
2633 function collectText(node: Node | null): string[] {
@@ -36,28 +43,98 @@ function collectText(node: Node | null): string[] {
3643 return node.children.flatMap((child) => collectText(child));
3744 }
3845
46+function measureRenderedHeight(node: Node | null, width: number): number {
47+ if (!node) {
48+ return 0;
49+ }
50+ return measureContentHeight(VStack({}, [node]), { width });
51+}
52+
53+async function waitForCelRender(): Promise<void> {
54+ await new Promise((resolve) => setTimeout(resolve, 10));
55+}
56+
57+async function renderBufferRows(
58+ node: Node | null,
59+ cols = PREVIEW_WIDTH,
60+ rows = 24,
61+): Promise<Array<{ text: string; fgColors: Array<string | null> }>> {
62+ if (!node) {
63+ return [];
64+ }
65+
66+ const terminal = new MockTerminal(cols, rows);
67+ cel.init(terminal);
68+ cel.viewport(() => VStack({ width: cols, height: rows }, [node]));
69+ await waitForCelRender();
70+
71+ const buffer = cel._getBuffer();
72+ if (!buffer) {
73+ throw new Error("Expected cel-tui to produce a render buffer");
74+ }
75+
76+ const snapshot: Array<{ text: string; fgColors: Array<string | null> }> = [];
77+ for (let y = 0; y < rows; y++) {
78+ let text = "";
79+ const fgColors: Array<string | null> = [];
80+ for (let x = 0; x < cols; x++) {
81+ const cell = buffer.get(x, y);
82+ text += cell.char;
83+ fgColors.push(cell.fgColor);
84+ }
85+ snapshot.push({ text, fgColors });
86+ }
87+
88+ cel.stop();
89+ return snapshot;
90+}
91+
92+async function renderVisibleText(
93+ node: Node | null,
94+ cols = PREVIEW_WIDTH,
95+ rows = 24,
96+): Promise<string[]> {
97+ const snapshot = await renderBufferRows(node, cols, rows);
98+ const lines: string[] = [];
99+
100+ for (const row of snapshot) {
101+ const normalized = row.text.trim().replace(/^│\s*/, "");
102+ if (normalized !== "") {
103+ lines.push(normalized);
104+ }
105+ }
106+
107+ return lines;
108+}
109+
39110 afterEach(() => {
40111 resetConversationRenderCache();
112+ cel.stop();
41113 });
42114
43115 describe("ui/conversation", () => {
44116 test("renderAssistantMessage preserves visible paragraph order in streamed markdown", () => {
117+ // Arrange
45118 const message = fauxAssistantMessage("First paragraph\n\nSecond paragraph");
46119
120+ // Act
47121 const text = collectText(renderAssistantMessage(message, RENDER_OPTS));
48122 const firstParagraphIndex = text.indexOf("First paragraph");
49123 const secondParagraphIndex = text.indexOf("Second paragraph");
50124
125+ // Assert
51126 expect(firstParagraphIndex).toBeGreaterThanOrEqual(0);
52127 expect(secondParagraphIndex).toBeGreaterThan(firstParagraphIndex);
53128 });
54129
55- test("renderAssistantMessage shows thinking blocks when reasoning is enabled", () => {
130+ test("renderAssistantMessage with reasoning enabled shows thinking blocks", () => {
131+ // Arrange
56132 const message = fauxAssistantMessage([
57133 fauxThinking("I should inspect the tests first."),
58134 fauxText("Done."),
59135 ]);
60136
137+ // Act
61138 const text = collectText(
62139 renderAssistantMessage(message, {
63140 ...RENDER_OPTS,
@@ -65,29 +142,70 @@ describe("ui/conversation", () => {
65142 }),
66143 );
67144
145+ // Assert
68146 expect(text).toContain("I should inspect the tests first.");
69147 expect(text).toContain("Done.");
70148 });
71149
72- test("renderAssistantMessage shows a thinking line-count placeholder when reasoning is hidden", () => {
150+ test("renderAssistantMessage with reasoning hidden shows a thinking line-count placeholder", () => {
151+ // Arrange
73152 const message = fauxAssistantMessage([
74153 fauxThinking("line one\nline two\nline three"),
75154 fauxText("Done."),
76155 ]);
77156
78- const node = renderAssistantMessage(message, {
79- ...RENDER_OPTS,
80- showReasoning: false,
81- });
82- const text = collectText(node);
157+ // Act
158+ const text = collectText(
159+ renderAssistantMessage(message, {
160+ ...RENDER_OPTS,
161+ showReasoning: false,
162+ }),
163+ );
83164
165+ // Assert
84166 expect(text).toContain("Thinking... 3 lines.");
85167 expect(text).toContain("Done.");
86168 expect(text).not.toContain("line one");
87169 expect(text).not.toContain("line two");
88170 });
89171
90- test("buildConversationLogNodes keeps tool call args and streamed shell output append-only", () => {
172+ test("renderAssistantMessage with mixed top-level blocks keeps a single blank line between sections", () => {
173+ // Arrange
174+ const message = fauxAssistantMessage([
175+ fauxThinking("Plan first."),
176+ fauxText("Done."),
177+ fauxToolCall("shell", { command: "echo hi" }, { id: "tool-1" }),
178+ ]);
179+
180+ // Act
181+ const height = measureRenderedHeight(
182+ renderAssistantMessage(message, {
183+ ...RENDER_OPTS,
184+ showReasoning: true,
185+ }),
186+ PREVIEW_WIDTH,
187+ );
188+
189+ // Assert
190+ expect(height).toBe(6);
191+ });
192+
193+ test("renderAssistantMessage keeps markdown paragraph spacing inside a single text block", () => {
194+ // Arrange
195+ const message = fauxAssistantMessage("First paragraph\n\nSecond paragraph");
196+
197+ // Act
198+ const height = measureRenderedHeight(
199+ renderAssistantMessage(message, RENDER_OPTS),
200+ PREVIEW_WIDTH,
201+ );
202+
203+ // Assert
204+ expect(height).toBe(3);
205+ });
206+
207+ test("buildConversationLogNodes with a pending shell result keeps the streamed call and result append-only", () => {
208+ // Arrange
91209 const pendingToolResults: PendingToolResult[] = [
92210 {
93211 toolCallId: "tool-1",
@@ -97,6 +215,7 @@ describe("ui/conversation", () => {
97215 },
98216 ];
99217
218+ // Act
100219 const nodes = buildConversationLogNodes(
101220 {
102221 messages: [
@@ -114,6 +233,8 @@ describe("ui/conversation", () => {
114233 content: [],
115234 pendingToolResults,
116235 },
236+ 0,
237+ PREVIEW_WIDTH,
117238 );
118239 const text = collectText({
119240 type: "vstack",
@@ -121,13 +242,17 @@ describe("ui/conversation", () => {
121242 children: nodes,
122243 });
123244
245+ // Assert
124246 expect(text).toContain("Working...");
125- expect(text.filter((line) => line === "$ echo hi")).toHaveLength(1);
247+ expect(text.filter((line) => line === "[shell ->]")).toHaveLength(1);
248+ expect(text).toContain("echo hi");
249+ expect(text).toContain("[shell <-]");
126250 expect(text).toContain("partial output");
127251 expect(text).not.toContain("Exit code: 0");
128252 });
129253
130- test("buildConversationLogNodes keeps hidden tool call args available when rendering a sliced window", () => {
254+ test("buildConversationLogNodes with a sliced window keeps hidden tool-call args available for compact edit results", () => {
255+ // Arrange
131256 const nodes = buildConversationLogNodes(
132257 {
133258 messages: [
@@ -146,7 +271,7 @@ describe("ui/conversation", () => {
146271 role: "toolResult" as const,
147272 toolCallId: "tool-1",
148273 toolName: "edit",
149- content: [{ type: "text" as const, text: "Updated src/app.ts" }],
274+ content: [{ type: "text" as const, text: "Edited src/app.ts" }],
150275 isError: false,
151276 timestamp: Date.now(),
152277 },
@@ -161,6 +286,7 @@ describe("ui/conversation", () => {
161286 pendingToolResults: [],
162287 },
163288 1,
289+ PREVIEW_WIDTH,
164290 );
165291 const text = collectText({
166292 type: "vstack",
@@ -168,12 +294,15 @@ describe("ui/conversation", () => {
168294 children: nodes,
169295 });
170296
171- expect(text).toContain("@@ -1,1 +1,1 @@");
172- expect(text).toContain("-before");
173- expect(text).toContain("+after");
297+ // Assert
298+ expect(text).toContain("[edit <-]");
299+ expect(text).toContain("~ src/app.ts");
300+ expect(text).not.toContain("before");
301+ expect(text).not.toContain("after");
174302 });
175303
176- test("buildConversationLogNodes reuses cached committed nodes when the log is unchanged", () => {
304+ test("buildConversationLogNodes with unchanged state reuses cached committed nodes", () => {
305+ // Arrange
177306 const state = {
178307 messages: [fauxAssistantMessage("Committed response")],
179308 showReasoning: false,
@@ -186,13 +315,21 @@ describe("ui/conversation", () => {
186315 pendingToolResults: [],
187316 };
188317
189- const first = buildConversationLogNodes(state, streaming);
190- const second = buildConversationLogNodes(state, streaming);
318+ // Act
319+ const first = buildConversationLogNodes(state, streaming, 0, PREVIEW_WIDTH);
320+ const second = buildConversationLogNodes(
321+ state,
322+ streaming,
323+ 0,
324+ PREVIEW_WIDTH,
325+ );
191326
327+ // Assert
192328 expect(second).toBe(first);
193329 });
194330
195- test("buildConversationLogNodes reuses the committed prefix when only the streaming tail changes", () => {
331+ test("buildConversationLogNodes with only a new streaming tail reuses the committed prefix", () => {
332+ // Arrange
196333 const state = {
197334 messages: [fauxAssistantMessage("Committed response")],
198335 showReasoning: false,
@@ -200,28 +337,41 @@ describe("ui/conversation", () => {
200337 theme: DEFAULT_THEME,
201338 };
202339
203- const committed = buildConversationLogNodes(state, {
204- isStreaming: false,
205- content: [],
206- pendingToolResults: [],
207- });
208- const withStreamingTail = buildConversationLogNodes(state, {
209- isStreaming: true,
210- content: [fauxText("Streaming tail")],
211- pendingToolResults: [],
212- });
340+ // Act
341+ const committed = buildConversationLogNodes(
342+ state,
343+ {
344+ isStreaming: false,
345+ content: [],
346+ pendingToolResults: [],
347+ },
348+ 0,
349+ PREVIEW_WIDTH,
350+ );
351+ const withStreamingTail = buildConversationLogNodes(
352+ state,
353+ {
354+ isStreaming: true,
355+ content: [fauxText("Streaming tail")],
356+ pendingToolResults: [],
357+ },
358+ 0,
359+ PREVIEW_WIDTH,
360+ );
213361 const text = collectText({
214362 type: "vstack",
215363 props: {},
216364 children: withStreamingTail,
217365 });
218366
367+ // Assert
219368 expect(withStreamingTail[0]).toBe(committed[0]);
220369 expect(text).toContain("Committed response");
221370 expect(text).toContain("Streaming tail");
222371 });
223372
224- test("buildConversationLogNodes rebuilds cached tool nodes when verbose mode changes", () => {
373+ test("buildConversationLogNodes when verbose mode changes rebuilds cached tool nodes", async () => {
374+ // Arrange
225375 const output = Array.from({ length: 25 }, (_, i) => `line ${i + 1}`).join(
226376 "\n",
227377 );
@@ -244,16 +394,22 @@ describe("ui/conversation", () => {
244394 theme: DEFAULT_THEME,
245395 };
246396
247- const previewNodes = buildConversationLogNodes(state, {
248- isStreaming: false,
249- content: [],
250- pendingToolResults: [],
251- });
252- const previewText = collectText({
253- type: "vstack",
254- props: {},
255- children: previewNodes,
256- });
397+ // Act
398+ const previewNodes = buildConversationLogNodes(
399+ state,
400+ {
401+ isStreaming: false,
402+ content: [],
403+ pendingToolResults: [],
404+ },
405+ 0,
406+ PREVIEW_WIDTH,
407+ );
408+ const previewText = await renderVisibleText(
409+ VStack({}, previewNodes),
410+ PREVIEW_WIDTH,
411+ 24,
412+ );
257413
258414 const verboseNodes = buildConversationLogNodes(
259415 { ...state, verbose: true },
@@ -262,13 +418,16 @@ describe("ui/conversation", () => {
262418 content: [],
263419 pendingToolResults: [],
264420 },
421+ 0,
422+ PREVIEW_WIDTH,
423+ );
424+ const verboseText = await renderVisibleText(
425+ VStack({}, verboseNodes),
426+ PREVIEW_WIDTH,
427+ 40,
265428 );
266- const verboseText = collectText({
267- type: "vstack",
268- props: {},
269- children: verboseNodes,
270- });
271429
430+ // Assert
272431 expect(previewNodes).not.toBe(verboseNodes);
273432 expect(previewText).toContain("line 18");
274433 expect(previewText).toContain("line 25");
@@ -276,314 +435,458 @@ describe("ui/conversation", () => {
276435 expect(previewText).not.toContain("line 17");
277436 expect(verboseText).toContain("line 17");
278437 expect(verboseText).toContain("line 25");
438+ expect(verboseText).not.toContain("And 17 lines more");
279439 });
280440
281- test("renderAssistantMessage shows in-progress thinking when reasoning is enabled", () => {
282- const node = renderAssistantMessage(
283- {
284- content: [fauxThinking("Reasoning in progress")],
285- },
286- {
441+ test("buildConversationLogNodes when preview width changes rebuilds cached tool nodes", () => {
442+ // Arrange
443+ const state = {
444+ messages: [
445+ fauxAssistantMessage([
446+ fauxToolCall(
447+ "shell",
448+ {
449+ command:
450+ "printf 'this is a very long wrapped line that depends on width'",
451+ },
452+ { id: "tool-1" },
453+ ),
454+ ]),
455+ ],
456+ showReasoning: false,
457+ verbose: false,
458+ theme: DEFAULT_THEME,
459+ };
460+ const streaming = {
461+ isStreaming: false,
462+ content: [],
463+ pendingToolResults: [],
464+ };
465+
466+ // Act
467+ const wide = buildConversationLogNodes(state, streaming, 0, 40);
468+ const narrow = buildConversationLogNodes(state, streaming, 0, 20);
469+
470+ // Assert
471+ expect(narrow).not.toBe(wide);
472+ });
473+
474+ test("renderAssistantMessage with in-progress reasoning visible shows thinking text", () => {
475+ // Arrange
476+ const assistant = {
477+ content: [fauxThinking("Reasoning in progress")],
478+ };
479+
480+ // Act
481+ const text = collectText(
482+ renderAssistantMessage(assistant, {
287483 ...RENDER_OPTS,
288484 showReasoning: true,
289- },
485+ }),
290486 );
291- const text = collectText(node);
292487
488+ // Assert
293489 expect(text).toContain("Reasoning in progress");
294490 });
295491
296- test("renderAssistantMessage shows a 1-line thinking placeholder for in-progress content", () => {
297- const node = renderAssistantMessage(
298- {
299- content: [fauxThinking("some thinking")],
300- },
301- {
492+ test("renderAssistantMessage with in-progress reasoning hidden shows a one-line placeholder", () => {
493+ // Arrange
494+ const assistant = {
495+ content: [fauxThinking("some thinking")],
496+ };
497+
498+ // Act
499+ const text = collectText(
500+ renderAssistantMessage(assistant, {
302501 ...RENDER_OPTS,
303502 showReasoning: false,
304- },
503+ }),
305504 );
306- const text = collectText(node);
307505
506+ // Assert
308507 expect(text).toContain("Thinking... 1 line.");
309508 });
310509
311- test("renderAssistantMessage shows streamed shell arguments semantically", () => {
312- const node = renderAssistantMessage(
313- {
314- content: [
315- fauxToolCall("shell", { command: "echo hi" }, { id: "tool-1" }),
316- ],
317- },
318- RENDER_OPTS,
319- );
320- const text = collectText(node);
510+ test("renderAssistantMessage for a shell tool call shows the command under the new header pill", () => {
511+ // Arrange
512+ const assistant = {
513+ content: [
514+ fauxToolCall("shell", { command: "echo hi" }, { id: "tool-1" }),
515+ ],
516+ };
321517
322- expect(text).toContain("$ echo hi");
518+ // Act
519+ const text = collectText(renderAssistantMessage(assistant, RENDER_OPTS));
520+
521+ // Assert
522+ expect(text).toContain("[shell ->]");
523+ expect(text).toContain("echo hi");
323524 expect(text).not.toContain('"command": "echo hi"');
324- expect(text).not.toContain("Preparing...");
325525 });
326526
327- test("renderAssistantMessage shows the last 8 lines of multi-line shell commands when verbose mode is off", () => {
328- const command = Array.from({ length: 10 }, (_, i) => `echo ${i + 1}`).join(
329- "\n",
330- );
Cut short: this commit's diff is over 1000 lines.
src/ui/conversation.ts+353−417
Cut short: this commit's diff is over 1000 lines.