xonecas.io
64875
Mc

mini-coder / commit df9e5a6

fix: restore incremental ui streaming

xonecas2026-04-06 df9e5a6ccf419cfa2301e981e90323cc0fc33d32 parent 6104776

3 files changed

TODO.md+25−160
@@ -1,177 +1,42 @@
1-# Implementation plan
1+# TODO
22
3-## Phase 1 — Foundation (no UI, no LLM)
3+## Bugs — from code review
44
5-- [x] `session.ts` — SQLite schema, CRUD, turn numbering, undo, fork, cumulative stats
6-- [x] `session.test.ts` — 20 tests against real in-memory bun:sqlite
7-- [x] `tools.ts` — `edit` (exact-text replace, new file creation) and `shell` (exec, output truncation)
8-- [x] `tools.test.ts` — 27 tests: edit (13), shell (8), truncateOutput (6)
9-- [x] `git.ts` — branch, dirty counts, ahead/behind, repo root detection (10 tests)
5+### BREAKING MUST FIX
106
11-### Notes from Phase 1
7+- [x] **No streaming feel** — fixed in `src/ui.ts` by rendering completed and in-progress assistant content inside stable top-level containers, with regression coverage in `src/ui.test.ts`.
8+- [ ] **UI Themeing is broken on non-dark background terminals** This is on us, Cel-tui explicit handles the terminal bg and fg, we are just retarded and hardcoded colors, with no tought on what the theme feels or looks like. Aweful work.
129
13-- `session.ts` exports: `openDatabase`, `createSession`, `getSession`, `listSessions`, `deleteSession`, `appendMessage`, `loadMessages`, `undoLastTurn`, `forkSession`, `computeStats`.
14-- Internal row types (`SessionRow`, `MaxTurnRow`, `DataRow`) and a `SQL` constants object keep queries centralized and avoid formatter conflicts.
15-- `@mariozechner/pi-ai` is the only runtime dependency so far. Its `Message`, `AssistantMessage`, `UserMessage`, `ToolResultMessage` types are used for session persistence.
16-- `tools.ts` exports: `ToolExecResult`, `EditArgs`, `executeEdit`, `ShellArgs`, `ShellOpts`, `executeShell`, `truncateOutput`, `editTool`, `shellTool`, `ReadImageArgs`, `executeReadImage`, `readImageTool`. All execute functions return `ToolExecResult` (`{ content: (TextContent | ImageContent)[], isError }`). pi-ai `Tool` definitions use TypeBox schemas.
17-- `git.ts` exports: `getGitState` → `GitState | null`. Runs 4 git commands in parallel. Internal `parseStatus` parses porcelain v1 format (uses `trim=false` to preserve leading-space column).
18-- biome `noNonNullAssertion` rule disabled globally — non-null assertions after explicit null checks are idiomatic in tests.
19-- 57 tests total across 3 files (session: 20, tools: 27, git: 10).
20-- `diff` package added as dependency for unified diffs in edit tool output (Phase 4 UI).
10+### High
2111
22-## Phase 2 — Context assembly
12+- [ ] **Uncaught tool handler exceptions** (`agent.ts`) — if a plugin handler (or a built-in on a filesystem error like EPERM) throws, the agent loop crashes. The exception propagates through `submitMessage` (try/finally, no catch) to a `.catch(console.error)` in `handleInput` — invisible in the TUI. The conversation is left inconsistent: `tool_start` emitted but `tool_end` never fires, tool result message never appended. Fix: wrap the `handler()` call in try/catch, produce an error `ToolExe …
13+- [ ] **`/undo` race condition** (`ui.ts`) — `/undo` aborts the agent loop then immediately calls `undoLastTurn`, but `abort()` is asynchronous. The agent loop may still write an `AssistantMessage` (stopReason "aborted") to the same turn after `undoLastTurn` has deleted it, leaving orphaned messages in the DB. Fix: store the agent loop promise as module state; in `handleUndoCommand`, await it (via `.finally()`) before calling `undoLastTurn`.
14+- [ ] **Invisible submit errors** (`ui.ts`) — `submitMessage` errors only go to `console.error`, invisible in TUI mode. Network errors, malformed responses, or tool handler crashes cause the agent to silently stop. Fix: replace `console.error` with `appendInfoMessage` so the error surfaces in the conversation log.
2315
24-- [x] `skills.ts` — SKILL.md discovery, frontmatter parsing, catalog generation, name collision resolution
25-- [x] `skills.test.ts` — 14 tests: single/multi path discovery, name collision, missing dirs, frontmatter (none, missing fields, multi-line, quoted), catalog XML
26-- [x] `prompt.ts` — AGENTS.md discovery, system prompt construction (base + AGENTS.md + skills + plugins + git footer)
27-- [x] `prompt.test.ts` — 21 tests: AGENTS.md walk (5), git line formatting (6), system prompt assembly (10)
16+### Medium
2817
29-### Notes from Phase 2
18+- [ ] **`readImage` missing try/catch** (`tools.ts`) — `executeReadImage` doesn't catch `readFileSync` exceptions. A permission error (EACCES) after the `existsSync` check throws an uncaught exception. Fix: wrap in try/catch, return text error result.
19+- [ ] **Fragile `tool_end` matching** (`ui.ts`/`agent.ts`) — `tool_end` events match pending tool calls by name + null resultText. Two calls to the same tool in one response (e.g., two `shell` calls) rely on sequential execution order. Fix: add `toolCallId` to `tool_start`/`tool_end` `AgentEvent` types, emit from `agent.ts`, match by id in `ui.ts`.
20+- [ ] **Stale plugin `AgentContext.messages`** (`index.ts`) — `AgentContext.messages` is the same array ref as `state.messages`, which gets reassigned on `/new`, `/session`, `/fork`, `/undo`. Plugins holding the original reference see stale data. Fix: use a getter (`get messages() { return state.messages; }`).
21+- [ ] **OAuth credential reference comparison** (`index.ts`) — `result.newCredentials !== oauthCredentials[oauthProvider.id]` compares by reference, not value. Causes unnecessary disk writes on every startup if `getOAuthApiKey` returns a new object. Fix: unconditionally assign when result is present, or compare serialized form.
3022
31-- `skills.ts` exports: `Skill` interface, `discoverSkills(scanPaths)`, `buildSkillCatalog(skills)`. Minimal YAML frontmatter parser (no dependency) handles `name`, `description`, folded scalars (`>`), quoted values. Falls back to directory name when frontmatter `name` is absent.
32-- `prompt.ts` exports: `AgentsMdFile` interface, `BuildSystemPromptOpts` interface, `discoverAgentsMd(cwd, scanRoot, globalAgentsDir?)`, `formatGitLine(state)`, `buildSystemPrompt(opts)`. Both `discoverSkills` and `discoverAgentsMd` take paths as parameters — the actual scan paths (spec §"Agent Skills" discovery, §"AGENTS.md" scan root priority) are determined by the caller (`index.ts` in Phase 4).
33-- Base instructions in `prompt.ts` match spec.md §"Base instructions" verbatim.
34-- `readImage` is intentionally absent from base instructions per spec — conditionally registered via tool definitions only.
35-- 92 tests total across 5 files (session: 20, tools: 27, git: 10, skills: 14, prompt: 21).
23+### Low (deferred from earlier phases)
3624
37-## Phase 3 — Agent loop
25+- [ ] **Shell output missing exit code** — spec says "Shows the command, head + tail truncated output with a visual marker, and exit code". `ToolExecResult` carries `isError` but not the numeric exit code.
26+- [ ] **CWD truncation on narrow terminals** — spec says truncate from left (`…/mini-coder`). Currently shows the full abbreviated path.
27+- [ ] **`Ctrl+Z` suspend/background** — spec lists it in key bindings but it's not implemented.
28+- [ ] **`/session` delete** — spec says "list, resume, delete" but Select component doesn't expose highlighted item for secondary actions.
3829
39-- [x] `readImage` tool in `tools.ts` — base64 encoding, mime detection, path resolution
40-- [x] `tools.test.ts` — 9 new readImage tests (36 total: edit 13, shell 8, truncateOutput 6, readImage 9)
41-- [x] `agent.ts` — core loop: stream → handle events → execute tools → loop. Interrupt handling.
42-- [x] `agent.test.ts` — 12 tests with faux provider: text response, tool execution, multi-tool, chaining, turn numbering, events, interrupt, error, unknown tool, length stop
43-- [x] `plugins.ts` — plugin types, config loading, init/destroy lifecycle
44-- [x] `plugins.test.ts` — 10 tests with real plugin modules in temp dirs: config loading, init, config passthrough, error handling, tool collection, destroy lifecycle
30+## Phase 4d — Polish
4531
46-### Notes from Phase 3
47-
48-- `readImage` in `tools.ts`: `ReadImageArgs`, `executeReadImage`, `readImageTool`. Returns `ImageContent` on success (base64 + mimeType) or text error, both via `ToolExecResult`.
49-- `agent.ts` exports: `ToolHandler` (function type), `ToolExecResult` (re-exported from `tools.ts`), `AgentEvent`, `RunAgentOpts`, `AgentLoopResult`, `runAgentLoop`. `RunAgentOpts` takes `tools: Tool[]` (definitions for the model) and `toolHandlers: Map<string, ToolHandler>` (dispatch map). The loop streams via `streamSimple`, dispatches tool calls through the handler map, appends all messages to DB with the same turn number, and emits events for UI updates. Unknown tools produce error results s …
50-- `plugins.ts` exports: `AgentContext`, `PluginResult`, `Plugin`, `PluginEntry`, `LoadedPlugin`, `loadPluginConfig`, `initPlugins`, `destroyPlugins`. `PluginResult.tools` is `Tool[]` (pi-ai definitions), `PluginResult.toolHandlers` is `Map<string, ToolHandler>` (optional). Plugins are real modules loaded via dynamic `import()` — tested with actual `.ts` files in temp dirs (no mocks).
51-- Context limit compaction is deferred — the spec notes "the specifics will be refined during development." The agent loop structure supports adding it as a pre-stream check.
52-- Conditional `readImage` registration (only for vision-capable models) will be handled by the caller (`index.ts`) checking `Model.input.includes("image")`.
53-- `cel-tui` (`@cel-tui/core`, `@cel-tui/components`) added as dependencies for the TUI.
54-- 123 tests total across 7 files.
55-
56-## Phase 4 — UI
57-
58-### 4a — Input parsing (TDD, no UI)
59-
60-- [x] `input.ts` — pure logic for parsing user input:
61- - `/command` detection and routing (extract command name + args)
62- - `/skill:name rest of message` → skill body + user text
63- - Image path detection (entire input is an existing image path with valid extension)
64-- [x] `input.test.ts` — 30 tests: command detection (6), skill references (6), image paths (12), plain text (4), priority (2)
65-
66-### Notes from Phase 4a
67-
68-- `input.ts` exports: `COMMANDS` (const tuple), `Command` type, `ParsedInput` discriminated union, `ParseInputOpts`, `parseInput(raw, opts?)`. Pure logic — no IO beyond `existsSync` for image path validation.
69-- `theme.ts` (also implemented here): `Theme` interface, `DEFAULT_THEME`, `mergeThemes(base, ...overrides)`. Uses terminal palette colors (`color01`–`color08`) for automatic light/dark adaptation. 5 tests in `theme.test.ts`.
70-- 158 tests total across 9 files (session: 20, tools: 36, git: 10, skills: 14, prompt: 21, agent: 12, plugins: 10, input: 30, theme: 5).
71-
72-### Notes from Phase 4b
73-
74-- `index.ts` exports: `AppState` (all mutable app state), `init()`, `buildPrompt(state)`, `buildToolList(state)`, `shutdown(state)`. Also re-exports OAuth helpers (`loadOAuthCredentials`, `saveOAuthCredentials`, `DATA_DIR`, `AUTH_PATH`) for `/login` and `/logout` commands.
75-- Provider discovery checks env-based API keys first, then saved OAuth tokens (`~/.config/mini-coder/auth.json`). Refreshes expired tokens and persists updates.
76-- Model selection picks the first model from the first provider with models, or `null` if none. No `process.exit` — the TUI starts regardless so the user can `/login`.
77-- Tool wiring: `buildTools` returns `{ tools: Tool[], toolHandlers: Map<string, ToolHandler> }`. Built-in handlers are a plain record. Plugin tools and handlers are merged from `PluginResult`.
78-- `ToolExecResult` is now the single result type in `tools.ts`. `ToolResult` and `ReadImageResult` were removed. All execute functions return `ToolExecResult` directly.
79-- `AgentTool` wrapper type removed from `agent.ts`. The agent loop takes `tools: Tool[]` + `toolHandlers: Map<string, ToolHandler>` separately.
80-- 158 tests still pass across 9 files.
81-
82-### 4b — App shell (running app, no commands)
83-
84-- [x] `index.ts` — entry point: provider discovery (env + OAuth), model selection (first available, null if none), startup sequence, `main()` wires init → startUI
85-- [x] `ui.ts` — cel-tui layout: conversation log (scrollable, stick-to-bottom), input area (TextInput, submit/newline), status bar (2 lines: cwd+git, model+usage), animated divider
86-- [x] Wire agent loop: submit → build context → stream → render events → tool results → loop
87-- [x] Message rendering: user (bg color), assistant (streamed Markdown), tool calls (shell: bordered output, edit: path + unified diff), errors
88-- [x] Interrupt: Escape during streaming aborts via AbortSignal
89-
90-### Notes from Phase 4b (ui.ts)
91-
92-- `ui.ts` exports: `startUI(state)`. Single entry point that owns the cel-tui lifecycle (`cel.init` / `cel.stop`).
93-- Layout matches the spec diagram: scrollable conversation log (flex: 1) → animated divider → TextInput (maxHeight: 10) → static divider → status bar (height: 2).
94-- Animated divider: scanning pulse (bright `═` segment sweeps across dimmed `─` line) via `setInterval` at 60ms. Starts on agent loop start, stops on completion.
95-- Message rendering: user messages get `bgColor` from theme, assistant messages use `Markdown()` component, tool calls get left border (`│`) with dimmed text. Edit tool calls show unified diff via `structuredPatch` from the `diff` package. Streaming response rendered from accumulation buffers + pending tool call list.
96-- Agent loop wiring: `submitMessage` appends user message to DB (turn auto-assigned by `appendMessage`), refreshes git state, builds prompt + tools, runs `runAgentLoop` with `onEvent` callback. Events update streaming buffers and trigger `cel.render()`.
97-- Key bindings: Enter submits (returns `false` in `onKeyPress` to prevent newline), Escape interrupts running agent, Ctrl+C / Ctrl+D graceful exit.
98-- `Theme` type changed from `string` values to cel-tui `Color` type — eliminates `as any` casts throughout the UI.
99-- `tsconfig.json`: removed `noImplicitReturns` for cel-tui compatibility (their `onKeyPress` callbacks return `false | void`).
100-- `spec.md`: removed `submitKey: "enter"` reference — cel-tui uses the `onKeyPress` return-false pattern instead.
101-- 158 tests still pass across 9 files.
102-
103-### 4c — Commands
104-
105-- [x] `/model` — interactive model selector (Select component, available providers/models)
106-- [x] `/effort` — effort level selector
107-- [x] `/session` — session manager (list, resume). Scoped to CWD.
108-- [x] `/login` — OAuth login via pi-ai (browser-based flow, no manual code input)
109-- [x] Overlay layer system for interactive Select commands
110-- [x] Wire `parseInput()` into Enter handler, route commands vs text
111-- [x] Session truncation — keep max 20 per CWD, runs on init
112-- [x] Fix: pass `apiKey` from `state.providers` through `RunAgentOpts` to `streamSimple` (OAuth providers failed without this)
113-- [x] Fix: pass `effort` (reasoning level) to `streamSimple` (was silently ignored)
114-- [x] `/logout` — OAuth logout (Select of logged-in providers, clear creds, nullify model if needed)
115-- [x] `/new` — new session, reset messages/stats
116-- [x] `/fork` — fork current session, info message
117-- [x] `/undo` — interrupt if running, then remove last turn
118-- [x] `/reasoning` — toggle `showReasoning`
119-- [x] `/verbose` — toggle `verbose`
120-- [x] Info messages separated from `state.messages` — display-only `infoMessages` array, not sent to LLM, cleared on session switch
121-- [x] `/` + Tab — command autocomplete overlay (all 11 commands with descriptions)
122-- [x] `/help` — list commands, providers, model, AGENTS.md files, skills, plugins
123-
124-### Notes from Phase 4c
125-
126-- Overlay system: cel-tui multi-layer viewport. `activeOverlay` module state holds a `SelectInstance` + title. When active, `cel.viewport()` returns `[base, overlayLayer]`. Overlay is a centered modal with `padding: { x: 4 }` and fixed height (`OVERLAY_MAX_VISIBLE + 3`), `bgColor: theme.overlayBg`.
127-- Escape dismissal: cel-tui intercepts Escape at the framework level (unfocuses before `onKeyPress` fires), so overlay dismissal uses `onBlur: dismissOverlay` instead of `onKeyPress`.
128-- `/model` builds items from `getAvailableModels(state)` (new helper in `index.ts`), marks current with `(current)` suffix, `filterText` includes both provider and model id.
129-- `/effort` shows 4 levels (low/medium/high/xhigh), marks current.
130-- `/session` lists sessions via `listSessions(db, cwd)`, labels show relative timestamp (`formatSessionDate`) + model + `(current)` marker. Resume swaps `state.session`, reloads messages and stats.
131-- `truncateSessions(db, cwd, keep)` in `session.ts` — deletes oldest beyond limit per CWD. `listSessions` SQL uses `rowid DESC` tiebreaker for deterministic ordering.
132-- `/login` shows OAuth providers from `getOAuthProviders()` with login status. `performLogin()` calls `provider.login()` with `onAuth` (opens browser via `xdg-open`/`open`), `onProgress` (status in log). `onPrompt` rejects (no manual code input). On success: persists creds, registers API key in `state.providers`, auto-selects model if none.
133-- `/logout` filters `getOAuthProviders()` to those with saved creds. On select: deletes creds, removes from `state.providers`, clears model if it belonged to the provider.
134-- `/new` creates session via `createSession`, clears messages/stats/infoMessages. Guards against running state.
135-- `/fork` calls `forkSession`, reloads messages/stats, shows info message. Guards against running state.
136-- `/undo` aborts agent if running, then `undoLastTurn`, reloads messages/stats.
137-- `/reasoning` and `/verbose` toggle their respective `AppState` booleans and re-render.
138-- `apiKey` added to `RunAgentOpts` and passed to `streamSimple` — required for OAuth providers (env vars not set). `effort` also passed as `reasoning` option.
139-- `handleInput()` routes through `parseInput()` → `handleCommand()` for commands, `submitMessage()` for text. Skill and image cases are stubs for Phase 4d.
140-- `Theme` gained `overlayBg: Color` (default `"color08"`).
141-- `appendInfoMessage()` helper for display-only status messages. Uses separate `infoMessages` array (not `state.messages`) so info text is never sent to the LLM. Cleared on `/new`, `/session` resume, `/fork`.
142-- `/help` renders commands (with descriptions), providers, model, AGENTS.md paths, skills, plugins as a multi-line info message.
143-- `/` + Tab in TextInput triggers `showCommandAutocomplete()` — overlay Select with all 11 commands from `COMMANDS` + `COMMAND_DESCRIPTIONS`. Selection executes the command via `handleInput`. Tab without `/` falls through (file autocomplete deferred to Phase 4d).
144-- All 11 spec commands implemented. Phase 4c complete.
145-- 162 tests across 9 files (session: 24, tools: 36, git: 10, skills: 14, prompt: 21, agent: 12, plugins: 10, input: 30, theme: 5).
146-
147-### Spec review findings (Phase 4c checkpoint)
148-
149-**Bugs (from earlier phases, deferred):**
150-
151-- Assistant messages not visibly streaming — text appears as full blocks instead of incrementally, causing jarring scroll jumps. Likely a rendering or event issue in `ui.ts` streaming path (Phase 4b).
152-- Shell tool rendering doesn't show exit code (spec: "Shows the command, head + tail truncated output with a visual marker, and exit code"). `ToolExecResult` carries `isError` but not the numeric exit code (Phase 4b).
153-- Status bar CWD truncation from the left (`…/mini-coder`) on narrow terminals — not implemented, just shows full abbreviated path (Phase 4b).
154-- `Ctrl+Z` suspend/background — not implemented (spec lists it in key bindings) (Phase 4b).
155-
156-**Design decisions:**
157-
158-- `/session` delete deferred — spec says "list, resume, delete" but Select component doesn't expose highlighted item for secondary actions.
159-- `/login` has no manual code input fallback — `onPrompt` rejects. Browser callback has always worked in practice.
160-
161-### 4d — Polish
162-
163-- [ ] Tab file path autocomplete in input
164-- [ ] `/skill:name` input handling (strip prefix, prepend skill body)
165-- [ ] Image embedding (entire input is image path → embed as ImageContent)
32+- [ ] `/skill:name` input handling (strip prefix, prepend skill body to user message)
33+- [ ] Image embedding (entire input is image path → embed as `ImageContent`)
16634 - [ ] Conditional `readImage` tool registration (only for vision-capable models, re-evaluated on `/model`)
35+- [ ] Tab file path autocomplete in input
16736 - [ ] Context limit compaction (threshold detection, model-generated summary, prompt cache preservation)
16837
16938 ## Future ideas
17039
17140 - [ ] User preferences persistence (model, effort) — not in spec, currently resets to defaults on launch
172-- [ ] Session list preview — show first user message snippet in `/session` selector for easier identification
173-- [ ] Divider theme plugin — customizable divider animations. Candidates designed during Phase 4 UI exploration:
174- - **Scanning pulse** (current default): bright segment sweeps across the dimmed divider
175- - **Breathing**: divider alternates between two dim levels, subtle pulse
176- - **Flowing dots**: dot characters move along the divider like a marquee
177- - **Wave**: characters cycle through `─` / `═` to create a moving wave effect
41+- [ ] Session list preview — show first user message snippet in `/session` selector
42+- [ ] Divider theme plugin — customizable divider animations (scanning pulse, breathing, flowing dots, wave)
src/ui.test.ts+56−0
@@ -0,0 +1,56 @@
1+import { describe, expect, test } from "bun:test";
2+import { fauxAssistantMessage } from "@mariozechner/pi-ai";
3+import { DEFAULT_THEME } from "./theme.ts";
4+import {
5+ type PendingToolCall,
6+ renderAssistantMessage,
7+ renderStreamingResponse,
8+} from "./ui.ts";
9+
10+const RENDER_OPTS = {
11+ showReasoning: false,
12+ verbose: false,
13+ theme: DEFAULT_THEME,
14+};
15+
16+describe("ui rendering", () => {
17+ test("renderAssistantMessage keeps streamed markdown inside one top-level container", () => {
18+ const message = fauxAssistantMessage("First paragraph\n\nSecond paragraph");
19+
20+ const node = renderAssistantMessage(message, RENDER_OPTS);
21+
22+ expect(node).not.toBeNull();
23+ expect(node?.type).toBe("vstack");
24+ if (!node || node.type !== "vstack") {
25+ throw new Error("Expected a vstack container");
26+ }
27+ expect(node.children.length).toBeGreaterThan(1);
28+ });
29+
30+ test("renderStreamingResponse keeps text and tool output inside one top-level container", () => {
31+ const pendingToolCalls: PendingToolCall[] = [
32+ {
33+ name: "shell",
34+ args: { command: "echo hi" },
35+ resultText: "hi",
36+ isError: false,
37+ },
38+ ];
39+
40+ const node = renderStreamingResponse(
41+ {
42+ text: "Working...",
43+ thinking: "",
44+ pendingToolCalls,
45+ },
46+ RENDER_OPTS,
47+ );
48+
49+ expect(node).not.toBeNull();
50+ expect(node?.type).toBe("vstack");
51+ if (!node || node.type !== "vstack") {
52+ throw new Error("Expected a vstack container");
53+ }
54+ expect(node.children.length).toBeGreaterThanOrEqual(2);
55+ });
56+});
src/ui.ts+117−64
@@ -53,6 +53,7 @@ import {
5353 loadMessages,
5454 undoLastTurn,
5555 } from "./session.ts";
56+import type { Theme } from "./theme.ts";
5657 import { truncateOutput } from "./tools.ts";
5758
5859 // ---------------------------------------------------------------------------
@@ -105,7 +106,8 @@ let isStreaming = false;
105106 * Stores the tool name and arguments from `tool_start`, and the
106107 * result text from `tool_end` (filled in when the tool finishes).
107108 */
108-interface PendingToolCall {
109+/** A pending tool call shown in the streaming tail. */
110+export interface PendingToolCall {
109111 /** Tool name. */
110112 name: string;
111113 /** Tool call arguments. */
@@ -116,6 +118,26 @@ interface PendingToolCall {
116118 isError: boolean;
117119 }
118120
121+/** Render options shared by completed and streaming assistant content. */
122+export interface ConversationRenderOpts {
123+ /** Whether reasoning blocks are visible. */
124+ showReasoning: boolean;
125+ /** Whether tool output should be truncated in the UI. */
126+ verbose: boolean;
127+ /** Active UI theme. */
128+ theme: Theme;
129+}
130+
131+/** Display-only assistant content that is still streaming. */
132+export interface StreamingRenderState {
133+ /** Streamed markdown text so far. */
134+ text: string;
135+ /** Streamed thinking text so far. */
136+ thinking: string;
137+ /** Tool calls observed in the current streaming turn. */
138+ pendingToolCalls: PendingToolCall[];
139+}
140+
119141 /** Tool calls collected during the current streaming turn. */
120142 let pendingToolCalls: PendingToolCall[] = [];
121143
@@ -290,24 +312,30 @@ function renderUserMessage(msg: Message, theme: AppState["theme"]): Node {
290312 ]);
291313 }
292314
315+/** Render markdown blocks with stable top-level containers. */
316+function renderMarkdownContent(content: string): Node[] {
317+ return Markdown(content).map((node) => {
318+ if (node.type === "text" && node.content === "") {
319+ return node;
320+ }
321+ return HStack({ padding: { x: 1 } }, [VStack({ flex: 1 }, [node])]);
322+ });
323+}
324+
293325 /** Render a completed assistant message from history. */
294-function renderAssistantMessage(
326+export function renderAssistantMessage(
295327 msg: AssistantMessage,
296- state: AppState,
297-): Node[] {
298- const nodes: Node[] = [];
328+ opts: ConversationRenderOpts,
329+): Node | null {
330+ const children: Node[] = [];
299331
300332 for (const block of msg.content) {
301333 if (block.type === "text" && (block as TextContent).text) {
302- nodes.push(
303- ...Markdown((block as TextContent).text).map((n) =>
304- HStack({ padding: { x: 1 } }, [VStack({ flex: 1 }, [n])]),
305- ),
306- );
307- } else if (block.type === "thinking" && state.showReasoning) {
334+ children.push(...renderMarkdownContent((block as TextContent).text));
335+ } else if (block.type === "thinking" && opts.showReasoning) {
308336 const thinking = (block as ThinkingContent).thinking;
309337 if (thinking) {
310- nodes.push(
338+ children.push(
311339 VStack({ padding: { x: 1 } }, [
312340 Text(thinking, {
313341 wrap: "word",
@@ -321,16 +349,20 @@ function renderAssistantMessage(
321349 }
322350
323351 if (msg.stopReason === "error" && msg.errorMessage) {
324- nodes.push(
352+ children.push(
325353 VStack({ padding: { x: 1 } }, [
326354 Text(`Error: ${msg.errorMessage}`, {
327- fgColor: state.theme.error,
355+ fgColor: opts.theme.error,
328356 }),
329357 ]),
330358 );
331359 }
332360
333- return nodes;
361+ if (children.length === 0) {
362+ return null;
363+ }
364+
365+ return VStack({}, children);
334366 }
335367
336368 /** Render a shell tool call with left border. */
@@ -338,9 +370,9 @@ function renderShellToolCall(
338370 command: string,
339371 output: string,
340372 _isError: boolean,
341- state: AppState,
373+ opts: Pick<ConversationRenderOpts, "verbose" | "theme">,
342374 ): Node {
343- const displayed = state.verbose
375+ const displayed = opts.verbose
344376 ? output
345377 : truncateOutput(output, UI_MAX_SHELL_LINES);
346378
@@ -352,8 +384,8 @@ function renderShellToolCall(
352384 }
353385
354386 return HStack({ padding: { x: 1 } }, [
355- Text("│ ", { fgColor: state.theme.toolBorder }),
356- VStack({ flex: 1, fgColor: state.theme.toolText }, lines),
387+ Text("│ ", { fgColor: opts.theme.toolBorder }),
388+ VStack({ flex: 1, fgColor: opts.theme.toolText }, lines),
357389 ]);
358390 }
359391
@@ -364,12 +396,12 @@ function renderEditToolCall(
364396 newText: string,
365397 isError: boolean,
366398 resultText: string,
367- state: AppState,
399+ theme: Theme,
368400 ): Node {
369401 if (isError) {
370402 return HStack({ padding: { x: 1 } }, [
371- Text("│ ", { fgColor: state.theme.toolBorder }),
372- VStack({ flex: 1 }, [Text(resultText, { fgColor: state.theme.error })]),
403+ Text("│ ", { fgColor: theme.toolBorder }),
404+ VStack({ flex: 1 }, [Text(resultText, { fgColor: theme.error })]),
373405 ]);
374406 }
375407
@@ -378,7 +410,7 @@ function renderEditToolCall(
378410 ];
379411
380412 if (oldText === "") {
381- lines.push(Text("(new file)", { fgColor: state.theme.diffAdded }));
413+ lines.push(Text("(new file)", { fgColor: theme.diffAdded }));
382414 } else {
383415 const patch = structuredPatch("", "", oldText, newText, "", "", {
384416 context: 2,
@@ -386,18 +418,18 @@ function renderEditToolCall(
386418 for (const hunk of patch.hunks) {
387419 for (const line of hunk.lines) {
388420 if (line.startsWith("+")) {
389- lines.push(Text(line, { fgColor: state.theme.diffAdded }));
421+ lines.push(Text(line, { fgColor: theme.diffAdded }));
390422 } else if (line.startsWith("-")) {
391- lines.push(Text(line, { fgColor: state.theme.diffRemoved }));
423+ lines.push(Text(line, { fgColor: theme.diffRemoved }));
392424 } else {
393- lines.push(Text(line, { fgColor: state.theme.toolText }));
425+ lines.push(Text(line, { fgColor: theme.toolText }));
394426 }
395427 }
396428 }
397429 }
398430
399431 return HStack({ padding: { x: 1 } }, [
400- Text("│ ", { fgColor: state.theme.toolBorder }),
432+ Text("│ ", { fgColor: theme.toolBorder }),
401433 VStack({ flex: 1 }, lines),
402434 ]);
403435 }
@@ -407,12 +439,12 @@ function renderGenericToolCall(
407439 toolName: string,
408440 output: string,
409441 isError: boolean,
410- state: AppState,
442+ theme: Theme,
411443 ): Node {
412- const fgColor = isError ? state.theme.error : state.theme.toolText;
444+ const fgColor = isError ? theme.error : theme.toolText;
413445
414446 return HStack({ padding: { x: 1 } }, [
415- Text("│ ", { fgColor: state.theme.toolBorder }),
447+ Text("│ ", { fgColor: theme.toolBorder }),
416448 VStack({ flex: 1 }, [
417449 Text(toolName, { fgColor: "color05", bold: true }),
418450 ...(output ? [Text(output, { wrap: "word", fgColor })] : []),
@@ -426,15 +458,13 @@ function renderToolResult(
426458 args: Record<string, unknown>,
427459 resultText: string,
428460 isError: boolean,
429- state: AppState,
461+ opts: ConversationRenderOpts,
430462 ): Node {
431463 if (toolName === "shell") {
432- return renderShellToolCall(
433- args.command as string,
434- resultText,
435- isError,
436- state,
437- );
464+ return renderShellToolCall(args.command as string, resultText, isError, {
465+ verbose: opts.verbose,
466+ theme: opts.theme,
467+ });
438468 }
439469 if (toolName === "edit") {
440470 return renderEditToolCall(
@@ -443,10 +473,10 @@ function renderToolResult(
443473 args.newText as string,
444474 isError,
445475 resultText,
446- state,
476+ opts.theme,
447477 );
448478 }
449- return renderGenericToolCall(toolName, resultText, isError, state);
479+ return renderGenericToolCall(toolName, resultText, isError, opts.theme);
450480 }
451481
452482 // ---------------------------------------------------------------------------
@@ -458,13 +488,16 @@ function renderToolResult(
458488 *
459489 * Shows thinking (if enabled), streamed markdown, and pending tool calls.
460490 */
461-function renderStreamingResponse(state: AppState): Node[] {
462- const nodes: Node[] = [];
463-
464- if (state.showReasoning && streamingThinking) {
465- nodes.push(
491+export function renderStreamingResponse(
492+ streaming: StreamingRenderState,
493+ opts: ConversationRenderOpts,
494+): Node | null {
495+ const children: Node[] = [];
496+
497+ if (opts.showReasoning && streaming.thinking) {
498+ children.push(
466499 VStack({ padding: { x: 1 } }, [
467- Text(streamingThinking, {
500+ Text(streaming.thinking, {
468501 wrap: "word",
469502 fgColor: "color08",
470503 italic: true,
@@ -473,18 +506,14 @@ function renderStreamingResponse(state: AppState): Node[] {
473506 );
474507 }
475508
476- if (streamingText) {
477- nodes.push(
478- ...Markdown(streamingText).map((n) =>
479- HStack({ padding: { x: 1 } }, [VStack({ flex: 1 }, [n])]),
480- ),
481- );
509+ if (streaming.text) {
510+ children.push(...renderMarkdownContent(streaming.text));
482511 }
483512
484- for (const tc of pendingToolCalls) {
513+ for (const tc of streaming.pendingToolCalls) {
485514 if (tc.resultText !== null) {
486- nodes.push(
487- renderToolResult(tc.name, tc.args, tc.resultText, tc.isError, state),
515+ children.push(
516+ renderToolResult(tc.name, tc.args, tc.resultText, tc.isError, opts),
488517 );
489518 } else {
490519 // Tool still running — show indicator
@@ -494,9 +523,9 @@ function renderStreamingResponse(state: AppState): Node[] {
494523 : tc.name === "edit"
495524 ? `~ ${tc.args.path ?? ""}…`
496525 : `${tc.name}…`;
497- nodes.push(
526+ children.push(
498527 HStack({ padding: { x: 1 } }, [
499- Text("│ ", { fgColor: state.theme.toolBorder }),
528+ Text("│ ", { fgColor: opts.theme.toolBorder }),
500529 VStack({ flex: 1 }, [
501530 Text(label, { fgColor: "color06", italic: true }),
502531 ]),
@@ -505,7 +534,11 @@ function renderStreamingResponse(state: AppState): Node[] {
505534 }
506535 }
507536
508- return nodes;
537+ if (children.length === 0) {
538+ return null;
539+ }
540+
541+ return VStack({}, children);
509542 }
510543
511544 // ---------------------------------------------------------------------------
@@ -515,6 +548,17 @@ function renderStreamingResponse(state: AppState): Node[] {
515548 /** Build the full conversation log as an array of nodes. */
516549 function buildConversationLog(state: AppState): Node[] {
517550 const nodes: Node[] = [];
551+ const renderOpts: ConversationRenderOpts = {
552+ showReasoning: state.showReasoning,
553+ verbose: state.verbose,
554+ theme: state.theme,
555+ };
556+
557+ const pushConversationNode = (node: Node | null): void => {
558+ if (!node) return;
559+ if (nodes.length > 0) nodes.push(Text(""));
560+ nodes.push(node);
561+ };
518562
519563 // Map toolCallId → { name, args } so we can render diffs for edits.
520564 const toolCallArgs = new Map<
@@ -524,9 +568,7 @@ function buildConversationLog(state: AppState): Node[] {
524568
525569 for (const msg of state.messages) {
526570 if (msg.role === "user") {
527- if (nodes.length > 0) nodes.push(Text(""));
528- nodes.push(renderUserMessage(msg, state.theme));
529- nodes.push(Text(""));
571+ pushConversationNode(renderUserMessage(msg, state.theme));
530572 } else if (msg.role === "assistant") {
531573 const am = msg as AssistantMessage;
532574 for (const block of am.content) {
@@ -535,7 +577,7 @@ function buildConversationLog(state: AppState): Node[] {
535577 toolCallArgs.set(tc.id, { name: tc.name, args: tc.arguments });
536578 }
537579 }
538- nodes.push(...renderAssistantMessage(am, state));
580+ pushConversationNode(renderAssistantMessage(am, renderOpts));
539581 } else if (msg.role === "toolResult") {
540582 const info = toolCallArgs.get(msg.toolCallId);
541583 const name = info?.name ?? msg.toolName;
@@ -544,18 +586,29 @@ function buildConversationLog(state: AppState): Node[] {
544586 .filter((c): c is TextContent => c.type === "text")
545587 .map((c) => c.text)
546588 .join("\n");
547- nodes.push(renderToolResult(name, args, text, msg.isError, state));
589+ pushConversationNode(
590+ renderToolResult(name, args, text, msg.isError, renderOpts),
591+ );
548592 }
549593 }
550594
551595 // Append in-progress streaming response
552596 if (isStreaming) {
553- nodes.push(...renderStreamingResponse(state));
597+ pushConversationNode(
598+ renderStreamingResponse(
599+ {
600+ text: streamingText,
601+ thinking: streamingThinking,
602+ pendingToolCalls,
603+ },
604+ renderOpts,
605+ ),
606+ );
554607 }
555608
556609 // Append display-only info messages
557610 for (const msg of infoMessages) {
558- nodes.push(
611+ pushConversationNode(
559612 VStack({ padding: { x: 1 } }, [
560613 Text(typeof msg.content === "string" ? msg.content : "", {
561614 fgColor: "color08",