xonecas.io
64875
Mc

mini-coder / commit 32f0405

fix: land UI and session fixes with spec cleanup

- preserve streamed thinking in assistant messages and add regression coverage\n- persist UI-only session log entries without leaking them into model context\n- tighten UI defaults and tool preview rendering behavior\n- sync spec/TODO with the implemented behavior and clean up bad edits

xonecas2026-04-06 32f040586c9f310f178df8f1a65856f050c45807 parent 2ed8041

9 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+30−12
@@ -2,36 +2,54 @@
22
33 ## Bugs — from code review
44
5-### BREAKING MUST FIX
5+### MUST FIX
66
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.
7+- [ ] **Tool outputs are not streamed into the UI** (`agent.ts` / `ui.ts`) — shell/edit/plugin tool results only become visible on `tool_end`, so long-running tools make the UI feel stalled instead of progressively updating. This conflicts with the spec's emphasis on speed and streaming feel. Fix: design a streaming/partial tool-output path (or explicit progressive status model) so tool execution remains visibly active before the final result lands.
8+
9+- [ ] **TextInput cursor is off by one after line wrapping** (`ui.ts` / cel-tui TextInput integration) — when the input wraps onto a new line, the visual cursor position drifts by one column from the actual insertion point. My current suspicion is that wrapping is happening at the cell level, but the cursor position is being computed against the logical text position without staying in sync with where the wrapped cell actually lands on the next line. That makes editing long prompts confusing a …
10+
11+- [ ] **Streaming Markdown wraps can corrupt the UI until the turn finishes** (`ui.ts` / cel-tui Markdown integration) — some styled Markdown lines break badly at wrap boundaries during streaming, causing duplicated/corrupted rendering in the conversation log. The corruption clears itself once the assistant turn completes, which suggests a bug in the incremental render path around wrapped styled content rather than persisted message rendering. Fix: reproduce with a regression test and adjust t …
12+
13+- [ ] **Status bar context usage percentage is wrong** (`ui.ts`) — the token usage indicator reports a much higher fraction of the model context window than is actually in use (for example, showing roughly half full when usage is still low). That makes the context meter untrustworthy and could mislead users about when compaction is needed. Fix: audit the percentage calculation and ensure it uses the correct token totals against the active model's real context window.
14+
15+- [ ] **Conversation log scroll speed is too slow** (`ui.ts`) — scrolling the conversation log appears to move only one line at a time, which makes navigating longer sessions tedious. The scroll step should feel responsive and usable for large transcripts. Fix: audit the wheel/key scroll increment and tune it to scroll by a larger chunk per interaction.
16+
17+- [ ] **UI theming is broken on non-dark background terminals** This is on us. `cel-tui` explicitly handles the terminal bg and fg; we hardcoded colors without any thought for how the theme feels or looks. Awful work.
918
1019 ### High
1120
21+- [ ] **Animated turn divider flickers a cursor-shaped artifact at the pulse edge** (`ui.ts`) — while the agent is running, the divider animation shows a flickering cursor-like mark on the right edge of the bright moving segment. So far this was only observed in Alacritty; Ghostty renders the same animation correctly, which suggests a terminal-specific rendering or cursor interaction issue. That makes the busy indicator look glitchy and suggests the animated segment rendering is leaving a stal …
22+
1223 - [ ] **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 …
24+
1325 - [ ] **`/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.
26+
27+- [ ] **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: append a persisted UI message so the error surfaces in the conversation log without leaking into model context.
1528
1629 ### Medium
1730
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.
1931 - [ ] **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`.
32+
2033 - [ ] **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; }`).
34+
2135 - [ ] **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.
2236
23-### Low (deferred from earlier phases)
37+- [ ] **Persisted UI messages create awkward undo/session turn boundaries** (`ui.ts` / `session.ts`) — `/help`, fork notices, and OAuth progress are now correctly persisted in session history, but each UI message currently starts its own turn. That means `/undo` peels off UI log lines one at a time instead of cleanly undoing the last conversational turn, and multi-step flows like OAuth can fragment the history. Fix: decide how UI messages should join turns (e.g. current turn / explicit synthet …
38+
39+### Low
2440
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.
2741 - [ ] **`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.
2942
30-## Phase 4d — Polish
43+- [ ] **Shell output missing exit code** — spec says shell tool rendering should show the command, tool output preview/full output, and exit code. `ToolExecResult` carries `isError` but not the numeric exit code.
44+
45+- [ ] **CWD truncation on narrow terminals** — spec says truncate from left (`…/mini-coder`). Currently shows the full abbreviated path.
46+
47+- [ ] **`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.
48+
49+## Polish (deferred until user says so)
3150
3251 - [ ] `/skill:name` input handling (strip prefix, prepend skill body to user message)
33-- [ ] Image embedding (entire input is image path → embed as `ImageContent`)
34-- [x] Conditional `readImage` tool registration (only for vision-capable models, re-evaluated on `/model`)
52+- [ ] Sending images in the prompt
3553 - [ ] Tab file path autocomplete in input
3654 - [ ] Context limit compaction (threshold detection, model-generated summary, prompt cache preservation)
3755
spec.md+34−33
@@ -65,7 +65,7 @@ Runs a command in the user's shell. Returns stdout, stderr, and exit code.
6565
6666 Implementation details:
6767
68-- Large outputs are truncated (keeping head + tail with a middle marker) to avoid context explosion.
68+- Large outputs are truncated to avoid context explosion caused by reading a massive file or binary by accident. This is a guard at the tool level, and not related to the user-configured verbose setting.
6969 - The truncation threshold is configurable, tuned to keep useful output while staying well within context limits.
7070 - Commands run via `$SHELL -c "<command>"` (falling back to `/bin/sh` if `$SHELL` is unset) with the CWD set to the session's working directory.
7171 - Timeout: no default timeout. The user can interrupt via `Escape`.
@@ -201,11 +201,11 @@ The core runtime. This is what happens on each turn:
201201
202202 1. **User submits a message** — the input text (plus any embedded images or skill bodies from `/skill:name`) becomes a pi-ai `UserMessage`. It is appended to the session's message history and persisted to the DB.
203203
204-2. **Build context** — construct a pi-ai `Context`: the system prompt (see [System prompt](#system-prompt)), the full message history, and the registered tool definitions (built-in + plugin tools). Git state in the session footer is refreshed before each turn.
204+2. **Build context** — construct a pi-ai `Context`: the system prompt (see [System prompt](#system-prompt)), the full message history, and the registered tool definitions (built-in + plugin tools). Git state in the session footer is refreshed at session start and after each turn.
205205
206206 3. **Stream to LLM** — call `streamSimple(model, context, options)` from pi-ai. Iterate over the event stream:
207- - `text_delta` / `thinking_delta` → update the UI (stream markdown, show thinking if enabled).
208- - `toolcall_end` → execute the tool call (see below), append the `ToolResultMessage` to history and DB.
207+ - `text_delta` / `thinking_delta` / `toolcall_delta` → update the in-progress assistant message and the UI incrementally (stream markdown, show thinking if enabled, accumulate tool call arguments as they arrive).
208+ - `toolcall_end` → finalize the structured tool call in the in-progress `AssistantMessage`.
209209 - `done` → append the `AssistantMessage` to history and DB. Update cumulative stats. If `stopReason` is `"toolUse"`, go to step 4. If `"stop"` or `"length"`, return to the input prompt.
210210 - `error` → display error in the log, return to the input prompt.
211211
@@ -385,25 +385,24 @@ Key decisions informed by the Codex prompting guide and Claude prompting best pr
385385 Three zones, top to bottom:
386386
387387 ```
388-│ │
389-│ ┌─────────────────────────────────────────────┐ │
390-│ │ fix the tests │ │ user: bg color
391-│ └─────────────────────────────────────────────┘ │
392-│ │
393-│ I'll check the test suite first. │ agent: default bg
394-│ │
395-│ │ $ bun test │ tool: left border
396-│ │ 3 passed, 1 failed │ dimmed text
397-│ │ ... truncated 45 lines ... │
388+│ │
389+│ ┌─────────────────────────────────────────────┐ │
390+│ │ fix the tests │ │ user: bg color
391+│ └─────────────────────────────────────────────┘ │
392+│ │
393+│ I'll check the test suite first. │ agent: default bg
394+│ │
395+│ │ $ bun test │ tool: left border
396+│ │ 3 passed, 1 failed │ dimmed text
398397 │ │ FAIL src/agent.test.ts > handles error │
399398 │ │ exit 1 │
400399 │ │ │
401400 │ │ ~ src/agent.ts │ edit: path + diff
402-│ │ - expect(result).toBe("stop"); │ red removed
403-│ │ + expect(result).toBe("error"); │ green added
401+│ │ - expect(result).toBe("stop"); │ red removed
402+│ │ + expect(result).toBe("error"); │ green added
404403 │ │ │
405404 │ Fixed the assertion. Tests pass now. │
406-│ │
405+│ │
407406 ────══════─────────────────────────────────────────── animated divider
408407 fix the remaining lint warnings │ input: no prefix
409408 in the utils file too_ │
@@ -417,7 +416,7 @@ cel-tui structure:
417416 ```ts
418417 VStack({ height: "100%" }, [
419418 // Conversation log — takes all available space
420- VStack({ flex: 1, overflow: "scroll", scrollbar: true }),
419+ VStack({ flex: 1, overflow: "scroll" }),
421420 // Top divider — animated scanning pulse when agent is working
422421 Divider(),
423422 // Input area — intrinsic height, no prompt prefix
@@ -487,13 +486,14 @@ Scrollable area that shows the full conversation history. Stick-to-bottom by def
487486 Message types and their rendering:
488487
489488 - **User messages**: displayed as plain text with a subtle background color to distinguish them from agent responses. No prefix or role indicator.
490-- **Assistant messages**: streamed markdown rendered via cel-tui's `Markdown` component on the default background. Thinking/reasoning content is collapsible (hidden by default, toggled with `/reasoning`).
491-- **Tool calls — shell**: rendered with a left border (`│`) and dimmed foreground. Shows the command (`$ command`), head + tail truncated output with a visual marker, and exit code. Full output viewable with `/verbose`.
492-- **Tool calls — edit**: rendered with a left border (`│`) and dimmed foreground. Shows the file path and a unified diff of the change (added lines in green, removed in red). Uses the `diff` package (`structuredPatch`) for line-level diffing.
489+- **Assistant messages**: streamed markdown rendered via cel-tui's `Markdown` component on the default background. Thinking/reasoning content is collapsible (shown by default, toggled with `/reasoning`).
490+- **Tool calls — shell**: rendered with a left border (`│`) and dimmed foreground. Shows the command (`$ command`) and the tool output. When `/verbose` is off, shell output is previewed as the first 20 lines followed by `And X lines more` when additional lines exist. When `/verbose` is on, the shell block expands to the full stored tool result. Exit code display is intended but not implemented yet.
491+- **Tool calls — edit**: rendered with a left border (`│`) and dimmed foreground. Shows the file path and a unified diff of the change (added lines in green, removed in red). When `/verbose` is off, the diff preview shows the first 20 diff lines followed by `And X lines more` when additional lines exist. When `/verbose` is on, the diff expands to the full stored tool result. Uses the `diff` package (`structuredPatch`) for line-level diffing.
493492 - **Tool calls — plugin tools**: rendered with a left border, prefixed with plugin/tool name.
493+- **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, and excluded from model context.
494494 - **Errors**: one-line summary, styled distinctly.
495495
496-While the agent is working, the top divider (above the input area) animates with a scanning pulse — a bright 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.
496+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.
497497
498498 ### Input area
499499
@@ -504,7 +504,7 @@ Supports:
504504 - `Tab` for file path autocomplete.
505505 - `/command` prefix for slash commands.
506506 - `/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.
507-- Image embedding: if the entire input (after trimming) is 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 sentenc …
507+- 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.
508508
509509 ### Key bindings
510510
@@ -513,7 +513,6 @@ Supports:
513513 | `Enter` | Input focused | Submit message |
514514 | `Shift+Enter` | Input focused | Insert newline |
515515 | `Escape` | Agent working | Interrupt current turn, preserve partial response |
516-| `Escape` | Input focused | Unfocus input |
517516 | `Tab` | Input focused | File path autocomplete |
518517 | `Ctrl+C` | Any | Graceful exit |
519518 | `Ctrl+D` | Input empty | Graceful exit (EOF) |
@@ -525,16 +524,16 @@ Supports:
525524 | Command | Description |
526525 | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
527526 | `/model` | Interactive model selector (provider + model + effort). Switching models mid-session is allowed — pi-ai's context is model-agnostic. The `readImage` tool is re-evaluated (added/removed based on the new model's capabilities). The status bar updates immediately. The session record's `model` field is not updated (it reflects the initial choice). |
528-| `/session` | Interactive session manager (list, resume, delete). Sessions scoped to CWD. |
527+| `/session` | Interactive session manager (list, resume). Sessions scoped to CWD. |
529528 | `/new` | Start a new session. Clears conversation, resets cost/token counters. |
530529 | `/fork` | Fork the current conversation into a new session. Copies the full message history, continues from here independently. The original session is preserved. |
531530 | `/undo` | Remove the last turn from conversation history (the user message and all assistant/tool messages that followed). Context-only — does not revert filesystem changes. |
532-| `/reasoning` | Toggle display of model thinking/reasoning content in the log. |
533-| `/verbose` | Toggle full output display (disables truncation in the UI). |
531+| `/reasoning` | Toggle display of model thinking/reasoning content in the log. Reasoning is shown by default. |
532+| `/verbose` | Toggle full shell-output and edit-diff display in the UI. When off, those tool blocks show a concise preview (first 20 lines plus `And X lines more` when applicable). When on, they expand to the full stored tool result. Verbose mode is off by default. |
534533 | `/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. |
535534 | `/logout` | Interactive OAuth logout. Shows a selector with logged-in OAuth providers. Selecting one clears its saved credentials. |
536535 | `/effort` | Interactive effort selector. Shows the four reasoning levels (`low`, `med`, `high`, `xhigh`) with the current level highlighted. Updates the status bar immediately. Does not update the session record's `effort` field (it reflects the initial choice, like `/model`). |
537-| `/help` | List available commands, loaded AGENTS.md files, discovered skills, and active plugins. |
536+| `/help` | List available commands, including the current on/off state of `/reasoning` and `/verbose`, plus loaded AGENTS.md files, discovered skills, and active plugins. |
538537
539538 Commands are discoverable via `/` + Tab to interactively select/filter in the input area.
540539
@@ -544,8 +543,8 @@ On launch, mini-coder:
544543
545544 1. Discovers providers (env vars, OAuth tokens).
546545 2. Loads AGENTS.md files, skills, plugins.
547-3. Starts a new session.
548-4. Renders the UI with an empty conversation log and the status bar populated.
546+3. Renders the UI with an empty conversation log and the status bar populated.
547+4. Starts a new session when the user sends a message (no 0-message sessions in the DB).
549548
550549 No banner or splash screen. The status bar already shows all the context the user needs.
551550
@@ -572,7 +571,7 @@ CREATE TABLE messages (
572571 id INTEGER PRIMARY KEY AUTOINCREMENT,
573572 session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
574573 turn INTEGER NOT NULL, -- groups a user message with its response cycle
575- data TEXT NOT NULL, -- JSON-serialized pi-ai Message
574+ data TEXT NOT NULL, -- JSON-serialized persisted message (pi-ai Message or internal UI message)
576575 created_at INTEGER NOT NULL -- unix ms
577576 );
578577
@@ -581,7 +580,7 @@ CREATE INDEX idx_messages_session ON messages(session_id, turn);
581580
582581 ### Design decisions
583582
584-**Messages as JSON blobs**: pi-ai's `Message` type (UserMessage, AssistantMessage, ToolResultMessage) is already serializable. We store the full object as JSON in `data` rather than normalizing into columns. We never need to query by message content — we only load all messages for a session and replay them into a pi-ai `Context`.
583+**Messages as JSON blobs**: pi-ai's `Message` type (UserMessage, AssistantMessage, ToolResultMessage) is already serializable, and we also persist internal UI-only log entries in the same table. We store the full object as JSON in `data` rather than normalizing into columns. Session load returns the complete chronological log; model context construction filters out UI-only messages before replaying the remaining pi-ai messages into a pi-ai `Context`.
585584
586585 **Turn grouping**: the `turn` column groups messages that belong to the same turn. A turn is: one user message + one or more assistant messages + any tool result messages from that agent loop. `/undo` deletes all messages with the highest `turn` value in the session. `/fork` copies all messages to a new session preserving turn numbers.
587586
@@ -591,6 +590,8 @@ CREATE INDEX idx_messages_session ON messages(session_id, turn);
591590
592591 **Model/effort on the session**: stored at creation for display in `/session` list. The user can change models mid-session via `/model`; the session record reflects the initial choice, individual messages record their actual model via pi-ai's `AssistantMessage.model`.
593592
593+**Session truncation**: sessions are truncated per cwd to keep only the 20 most recently updated sessions (`updated_at DESC`), deleting older sessions and their messages via cascade.
594+
594595 ### Operations
595596
596597 | Operation | SQL |
@@ -600,5 +601,5 @@ CREATE INDEX idx_messages_session ON messages(session_id, turn);
600601 | Undo | `DELETE FROM messages WHERE session_id = ? AND turn = (SELECT MAX(turn) FROM messages WHERE session_id = ?)` |
601602 | Fork | `INSERT INTO sessions` (new id, `forked_from` set), then `INSERT INTO messages SELECT ... FROM messages WHERE session_id = ?` (copy all, new session_id) |
602603 | List sessions | `SELECT * FROM sessions WHERE cwd = ? ORDER BY updated_at DESC` |
603-| Load session | `SELECT data FROM messages WHERE session_id = ? ORDER BY id` → parse JSON → pi-ai `Message[]` |
604+| Load session | `SELECT data FROM messages WHERE session_id = ? ORDER BY id` → parse JSON → persisted message log (`pi-ai Message[]` + internal UI messages) |
604605 | Delete session | `DELETE FROM sessions WHERE id = ?` (cascade deletes messages) |
src/agent.test.ts+227−1
@@ -3,12 +3,23 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
33 import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
6-import type { AssistantMessage, Tool, UserMessage } from "@mariozechner/pi-ai";
6+import type {
7+ AssistantMessage,
8+ Model,
9+ Tool,
10+ Usage,
11+ UserMessage,
12+} from "@mariozechner/pi-ai";
713 import {
14+ createAssistantMessageEventStream,
815 type FauxProviderRegistration,
916 fauxAssistantMessage,
17+ fauxText,
18+ fauxThinking,
1019 fauxToolCall,
20+ registerApiProvider,
1121 registerFauxProvider,
22+ unregisterApiProviders,
1223 } from "@mariozechner/pi-ai";
1324 import { type AgentEvent, runAgentLoop, type ToolHandler } from "./agent.ts";
1425 import {
@@ -43,6 +54,15 @@ function makeUser(text: string): UserMessage {
4354 return { role: "user", content: text, timestamp: Date.now() };
4455 }
4556
57+const ZERO_USAGE: Usage = {
58+ input: 0,
59+ output: 0,
60+ cacheRead: 0,
61+ cacheWrite: 0,
62+ totalTokens: 0,
63+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
64+};
65+
4666 /** Built-in tool definitions for tests. */
4767 function builtinToolDefs(): Tool[] {
4868 return [shellTool, editTool];
@@ -308,6 +328,177 @@ describe("agent loop", () => {
308328 expect(doneEvents).toHaveLength(1);
309329 });
310330
331+ test("emits thinking delta events during streaming", async () => {
332+ faux.setResponses([
333+ fauxAssistantMessage([
334+ fauxThinking("Need to inspect the failing test."),
335+ fauxText("Done."),
336+ ]),
337+ ]);
338+
339+ const events: AgentEvent[] = [];
340+
341+ const session = createSession(db, { cwd: tmp });
342+ const userMsg = makeUser("hi");
343+ const turn = appendMessage(db, session.id, userMsg);
344+
345+ await runAgentLoop({
346+ db,
347+ sessionId: session.id,
348+ turn,
349+ model: faux.getModel(),
350+ systemPrompt: "Test",
351+ tools: [],
352+ toolHandlers: new Map(),
353+ messages: [userMsg],
354+ cwd: tmp,
355+ onEvent: (e) => events.push(e),
356+ });
357+
358+ const thinkingDeltas = events.filter((e) => e.type === "thinking_delta");
359+ expect(thinkingDeltas.length).toBeGreaterThan(0);
360+ });
361+
362+ test("reconstructs thinking content when the final done message omits it", async () => {
363+ const api = "reasoning-drop-test";
364+ const sourceId = "reasoning-drop-test-source";
365+ const model: Model<string> = {
366+ id: "reasoning-drop-model",
367+ name: "Reasoning Drop Model",
368+ api,
369+ provider: "test",
370+ baseUrl: "http://localhost:0",
371+ reasoning: true,
372+ input: ["text"],
373+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
374+ contextWindow: 128000,
375+ maxTokens: 4096,
376+ };
377+
378+ registerApiProvider(
379+ {
380+ api,
381+ stream: (_model, _context, _options) => {
382+ const stream = createAssistantMessageEventStream();
383+ const partial: AssistantMessage = {
384+ role: "assistant",
385+ content: [
386+ fauxThinking("Need to inspect the failing test."),
387+ fauxText("Done."),
388+ ],
389+ api,
390+ provider: "test",
391+ model: model.id,
392+ usage: ZERO_USAGE,
393+ stopReason: "stop",
394+ timestamp: Date.now(),
395+ };
396+ const finalMessage: AssistantMessage = {
397+ ...partial,
398+ content: [fauxText("Done.")],
399+ };
400+
401+ queueMicrotask(() => {
402+ stream.push({
403+ type: "thinking_delta",
404+ contentIndex: 0,
405+ delta: "Need to inspect the failing test.",
406+ partial,
407+ });
408+ stream.push({
409+ type: "text_delta",
410+ contentIndex: 1,
411+ delta: "Done.",
412+ partial,
413+ });
414+ stream.push({
415+ type: "done",
416+ reason: "stop",
417+ message: finalMessage,
418+ });
419+ stream.end(finalMessage);
420+ });
421+
422+ return stream;
423+ },
424+ streamSimple: (_model, _context, _options) => {
425+ const stream = createAssistantMessageEventStream();
426+ const partial: AssistantMessage = {
427+ role: "assistant",
428+ content: [
429+ fauxThinking("Need to inspect the failing test."),
430+ fauxText("Done."),
431+ ],
432+ api,
433+ provider: "test",
434+ model: model.id,
435+ usage: ZERO_USAGE,
436+ stopReason: "stop",
437+ timestamp: Date.now(),
438+ };
439+ const finalMessage: AssistantMessage = {
440+ ...partial,
441+ content: [fauxText("Done.")],
442+ };
443+
444+ queueMicrotask(() => {
445+ stream.push({
446+ type: "thinking_delta",
447+ contentIndex: 0,
448+ delta: "Need to inspect the failing test.",
449+ partial,
450+ });
451+ stream.push({
452+ type: "text_delta",
453+ contentIndex: 1,
454+ delta: "Done.",
455+ partial,
456+ });
457+ stream.push({
458+ type: "done",
459+ reason: "stop",
460+ message: finalMessage,
461+ });
462+ stream.end(finalMessage);
463+ });
464+
465+ return stream;
466+ },
467+ },
468+ sourceId,
469+ );
470+
471+ try {
472+ const session = createSession(db, { cwd: tmp });
473+ const userMsg = makeUser("hi");
474+ const turn = appendMessage(db, session.id, userMsg);
475+
476+ const result = await runAgentLoop({
477+ db,
478+ sessionId: session.id,
479+ turn,
480+ model,
481+ systemPrompt: "Test",
482+ tools: [],
483+ toolHandlers: new Map(),
484+ messages: [userMsg],
485+ cwd: tmp,
486+ });
487+
488+ const assistant = result.messages[1];
489+ expect(assistant?.role).toBe("assistant");
490+ if (assistant?.role !== "assistant") {
491+ throw new Error("Expected assistant message");
492+ }
493+ expect(assistant.content).toContainEqual(
494+ fauxThinking("Need to inspect the failing test."),
495+ );
496+ expect(assistant.content).toContainEqual(fauxText("Done."));
497+ } finally {
498+ unregisterApiProviders(sourceId);
499+ }
500+ });
501+
311502 test("emits tool events during tool execution", async () => {
312503 faux.setResponses([
313504 fauxAssistantMessage([fauxToolCall("shell", { command: "echo test" })], {
@@ -383,6 +574,41 @@ describe("agent loop", () => {
383574 expect(dbLast.stopReason).toBe("aborted");
384575 });
385576
577+ test("preserves thinking content on assistant messages", async () => {
578+ faux.setResponses([
579+ fauxAssistantMessage([
580+ fauxThinking("Need to inspect the failing test."),
581+ fauxText("Done."),
582+ ]),
583+ ]);
584+
585+ const session = createSession(db, { cwd: tmp });
586+ const userMsg = makeUser("hello");
587+ const turn = appendMessage(db, session.id, userMsg);
588+
589+ const result = await runAgentLoop({
590+ db,
591+ sessionId: session.id,
592+ turn,
593+ model: faux.getModel(),
594+ systemPrompt: "Test",
595+ tools: [],
596+ toolHandlers: new Map(),
597+ messages: [userMsg],
598+ cwd: tmp,
599+ });
600+
601+ const assistant = result.messages[1];
602+ expect(assistant?.role).toBe("assistant");
603+ if (assistant?.role !== "assistant") {
604+ throw new Error("Expected assistant message");
605+ }
606+ expect(assistant.content).toContainEqual(
607+ fauxThinking("Need to inspect the failing test."),
608+ );
609+ expect(assistant.content).toContainEqual(fauxText("Done."));
610+ });
611+
386612 test("handles LLM error gracefully", async () => {
387613 faux.setResponses([
388614 fauxAssistantMessage("", {
src/agent.ts+82−0
@@ -88,6 +88,77 @@ export interface AgentLoopResult {
8888 stopReason: "stop" | "length" | "error" | "aborted";
8989 }
9090
91+/** Merge streamed partial assistant content into the final message content. */
92+function mergeAssistantContent(
93+ partialContent: AssistantMessage["content"],
94+ finalContent: AssistantMessage["content"],
95+): AssistantMessage["content"] {
96+ if (partialContent.length === 0) return finalContent;
97+ if (finalContent.length === 0) return partialContent;
98+
99+ const merged: AssistantMessage["content"] = [];
100+ let partialIndex = 0;
101+ let finalIndex = 0;
102+
103+ while (
104+ partialIndex < partialContent.length ||
105+ finalIndex < finalContent.length
106+ ) {
107+ const partialBlock = partialContent[partialIndex];
108+ const finalBlock = finalContent[finalIndex];
109+
110+ if (!partialBlock) {
111+ merged.push(finalBlock!);
112+ finalIndex++;
113+ continue;
114+ }
115+ if (!finalBlock) {
116+ merged.push(partialBlock);
117+ partialIndex++;
118+ continue;
119+ }
120+ if (partialBlock.type === finalBlock.type) {
121+ if (
122+ partialBlock.type === "thinking" &&
123+ finalBlock.type === "thinking" &&
124+ partialBlock.thinking &&
125+ !finalBlock.thinking
126+ ) {
127+ merged.push(partialBlock);
128+ } else {
129+ merged.push(finalBlock);
130+ }
131+ partialIndex++;
132+ finalIndex++;
133+ continue;
134+ }
135+ if (partialBlock.type === "thinking") {
136+ merged.push(partialBlock);
137+ partialIndex++;
138+ continue;
139+ }
140+ merged.push(finalBlock);
141+ partialIndex++;
142+ finalIndex++;
143+ }
144+
145+ return merged;
146+}
147+
148+/** Merge a final assistant message with the richest streamed partial content seen. */
149+function mergeAssistantMessage(
150+ partialMessage: AssistantMessage,
151+ finalMessage: AssistantMessage,
152+): AssistantMessage {
153+ return {
154+ ...finalMessage,
155+ content: mergeAssistantContent(
156+ partialMessage.content,
157+ finalMessage.content,
158+ ),
159+ };
160+}
161+
91162 // ---------------------------------------------------------------------------
92163 // Agent loop
93164 // ---------------------------------------------------------------------------
@@ -137,8 +208,13 @@ export async function runAgentLoop(
137208 };
138209 const eventStream = streamSimple(model, context, streamOpts);
139210 let assistantMessage: AssistantMessage | undefined;
211+ let partialAssistantMessage: AssistantMessage | undefined;
140212
141213 for await (const event of eventStream) {
214+ if ("partial" in event) {
215+ partialAssistantMessage = event.partial;
216+ }
217+
142218 switch (event.type) {
143219 case "text_delta":
144220 onEvent?.({ type: "text_delta", delta: event.delta });
@@ -162,6 +238,12 @@ export async function runAgentLoop(
162238 if (!assistantMessage) {
163239 assistantMessage = await eventStream.result();
164240 }
241+ if (partialAssistantMessage) {
242+ assistantMessage = mergeAssistantMessage(
243+ partialAssistantMessage,
244+ assistantMessage,
245+ );
246+ }
165247
166248 // Append assistant message to history and DB
167249 messages.push(assistantMessage);
src/index.ts+10−3
@@ -38,6 +38,7 @@ import {
3838 import {
3939 computeStats,
4040 createSession,
41+ filterModelMessages,
4142 loadMessages,
4243 openDatabase,
4344 type Session,
@@ -74,6 +75,12 @@ const AUTH_PATH = join(DATA_DIR, "auth.json");
7475 /** Default effort level. */
7576 const DEFAULT_EFFORT: ThinkingLevel = "medium";
7677
78+/** Whether reasoning blocks are shown by default. */
79+export const DEFAULT_SHOW_REASONING = true;
80+
81+/** Whether full tool output is shown by default. */
82+export const DEFAULT_VERBOSE = false;
83+
7784 /** Maximum sessions to keep per CWD. */
7885 const MAX_SESSIONS_PER_CWD = 20;
7986
@@ -349,7 +356,7 @@ export async function init(): Promise<AppState> {
349356 // Init plugins
350357 const context: AgentContext = {
351358 cwd,
352- messages,
359+ messages: filterModelMessages(messages),
353360 dataDir: DATA_DIR,
354361 };
355362 const plugins = await initPlugins(pluginEntries, context, (entry, err) => {
@@ -380,8 +387,8 @@ export async function init(): Promise<AppState> {
380387 canonicalCwd,
381388 running: false,
382389 abortController: null,
383- showReasoning: false,
384- verbose: false,
390+ showReasoning: DEFAULT_SHOW_REASONING,
391+ verbose: DEFAULT_VERBOSE,
385392 };
386393 }
387394
src/session.test.ts+33−1
@@ -9,7 +9,9 @@ import {
99 appendMessage,
1010 computeStats,
1111 createSession,
12+ createUiMessage,
1213 deleteSession,
14+ filterModelMessages,
1315 forkSession,
1416 getSession,
1517 listSessions,
@@ -68,6 +70,10 @@ function makeToolResult(toolCallId: string, text: string): ToolResultMessage {
6870 };
6971 }
7072
73+function makeUiMessage(text: string) {
74+ return createUiMessage(text);
75+}
76+
7177 // ---------------------------------------------------------------------------
7278 // Tests
7379 // ---------------------------------------------------------------------------
@@ -194,6 +200,18 @@ describe("message persistence and turn numbering", () => {
194200 db.close();
195201 });
196202
203+ test("loadMessages round-trips persisted UI messages", () => {
204+ const db = openDatabase(":memory:");
205+ const session = createSession(db, { cwd: "/tmp/test" });
206+ const uiMessage = makeUiMessage("Help output");
207+
208+ appendMessage(db, session.id, uiMessage);
209+
210+ const msgs = loadMessages(db, session.id);
211+ expect(msgs).toEqual([uiMessage]);
212+ db.close();
213+ });
214+
197215 test("appendMessage updates session updated_at", () => {
198216 const db = openDatabase(":memory:");
199217 const session = createSession(db, { cwd: "/tmp/test" });
@@ -372,9 +390,10 @@ describe("cumulative stats", () => {
372390 });
373391
374392 test("computeStats ignores non-assistant messages", () => {
375- const messages: Message[] = [
393+ const messages = [
376394 makeUser("hello"),
377395 makeToolResult("tc1", "result"),
396+ makeUiMessage("Help output"),
378397 ];
379398
380399 const stats = computeStats(messages);
@@ -382,6 +401,19 @@ describe("cumulative stats", () => {
382401 expect(stats.totalOutput).toBe(0);
383402 expect(stats.totalCost).toBe(0);
384403 });
404+
405+ test("filterModelMessages excludes UI messages", () => {
406+ const ui = makeUiMessage("Help output");
407+ const user = makeUser("hello");
408+ const assistant = makeAssistant("reply");
409+ const messages = [ui, user, assistant];
410+
411+ const filtered = filterModelMessages(messages);
412+
413+ expect(filtered).toHaveLength(2);
414+ expect(filtered[0]).toEqual(user);
415+ expect(filtered[1]).toEqual(assistant);
416+ });
385417 });
386418
387419 describe("truncateSessions", () => {
src/session.ts+69−10
@@ -57,6 +57,21 @@ export interface SessionStats {
5757 totalCost: number;
5858 }
5959
60+/** A persisted UI-only message shown in the conversation log. */
61+export interface UiMessage {
62+ /** Identifies this as an internal UI message. */
63+ role: "ui";
64+ /** UI message category for rendering and future behavior. */
65+ kind: "info";
66+ /** Display text shown in the conversation log. */
67+ content: string;
68+ /** Unix timestamp in milliseconds. */
69+ timestamp: number;
70+}
71+
72+/** Any message persisted in session history. */
73+export type PersistedMessage = Message | UiMessage;
74+
6075 /** Options for creating a new session. */
6176 interface CreateSessionOpts {
6277 /** Working directory to scope the session to. */
@@ -269,6 +284,45 @@ export function truncateSessions(
269284 // Messages
270285 // ---------------------------------------------------------------------------
271286
287+/**
288+ * Create a persisted UI message.
289+ *
290+ * @param content - Display text shown in the conversation log.
291+ * @returns A new {@link UiMessage}.
292+ */
293+export function createUiMessage(content: string): UiMessage {
294+ return {
295+ role: "ui",
296+ kind: "info",
297+ content,
298+ timestamp: Date.now(),
299+ };
300+}
301+
302+/**
303+ * Check whether a persisted message is a UI-only message.
304+ *
305+ * @param message - Message to inspect.
306+ * @returns `true` when the message is a {@link UiMessage}.
307+ */
308+export function isUiMessage(message: PersistedMessage): message is UiMessage {
309+ return message.role === "ui";
310+}
311+
312+/**
313+ * Filter persisted session history down to model-visible pi-ai messages.
314+ *
315+ * @param messages - Persisted session history.
316+ * @returns Only the pi-ai {@link Message} entries.
317+ */
318+export function filterModelMessages(
319+ messages: readonly PersistedMessage[],
320+): Message[] {
321+ return messages.filter(
322+ (message): message is Message => !isUiMessage(message),
323+ );
324+}
325+
272326 /**
273327 * Append a message to a session's history.
274328 *
@@ -283,14 +337,14 @@ export function truncateSessions(
283337 *
284338 * @param db - Open database handle.
285339 * @param sessionId - The session to append to.
286- * @param message - A pi-ai {@link Message} (UserMessage, AssistantMessage, or ToolResultMessage).
340+ * @param message - A persisted message (pi-ai message or internal UI message).
287341 * @param turn - Explicit turn number to join. Omit to start a new turn.
288342 * @returns The turn number the message was stored with.
289343 */
290344 export function appendMessage(
291345 db: Database,
292346 sessionId: string,
293- message: Message,
347+ message: PersistedMessage,
294348 turn?: number,
295349 ): number {
296350 const now = Date.now();
@@ -316,17 +370,20 @@ export function appendMessage(
316370 * Load all messages for a session in insertion order.
317371 *
318372 * Messages are deserialized from their JSON representation back into
319- * pi-ai {@link Message} objects. The ordering matches the original
320- * append order (by autoincrement `id`), preserving the conversation flow.
373+ * persisted app messages. The ordering matches the original append order
374+ * (by autoincrement `id`), preserving the conversation flow.
321375 *
322376 * @param db - Open database handle.
323377 * @param sessionId - The session to load messages for.
324- * @returns An array of {@link Message} objects, empty if the session has
325- * no messages or does not exist.
378+ * @returns An array of {@link PersistedMessage} objects, empty if the session
379+ * has no messages or does not exist.
326380 */
327-export function loadMessages(db: Database, sessionId: string): Message[] {
381+export function loadMessages(
382+ db: Database,
383+ sessionId: string,
384+): PersistedMessage[] {
328385 const rows = db.query<DataRow, [string]>(SQL.loadMessages).all(sessionId);
329- return rows.map((row) => JSON.parse(row.data) as Message);
386+ return rows.map((row) => JSON.parse(row.data) as PersistedMessage);
330387 }
331388
332389 // ---------------------------------------------------------------------------
@@ -412,10 +469,12 @@ export function forkSession(db: Database, sourceId: string): Session {
412469 * designed to be called once on session load, with the result maintained
413470 * in-memory via a running accumulator during the session.
414471 *
415- * @param messages - The full message history for a session.
472+ * @param messages - The full persisted message history for a session.
416473 * @returns Aggregated {@link SessionStats}.
417474 */
418-export function computeStats(messages: Message[]): SessionStats {
475+export function computeStats(
476+ messages: readonly PersistedMessage[],
477+): SessionStats {
419478 let totalInput = 0;
420479 let totalOutput = 0;
421480 let totalCost = 0;
src/ui.test.ts+245−1
@@ -1,10 +1,28 @@
11 import { describe, expect, test } from "bun:test";
2-import { fauxAssistantMessage } from "@mariozechner/pi-ai";
2+import type { Node } from "@cel-tui/types";
3+import {
4+ fauxAssistantMessage,
5+ fauxText,
6+ fauxThinking,
7+} from "@mariozechner/pi-ai";
8+import {
9+ type AppState,
10+ DEFAULT_SHOW_REASONING,
11+ DEFAULT_VERBOSE,
12+} from "./index.ts";
13+import { createSession, openDatabase } from "./session.ts";
314 import { DEFAULT_THEME } from "./theme.ts";
415 import {
16+ buildConversationLog,
17+ buildHelpText,
18+ type HelpRenderState,
19+ handleInput,
520 type PendingToolCall,
21+ previewToolRenderLines,
622 renderAssistantMessage,
723 renderStreamingResponse,
24+ renderToolResult,
25+ type ToolRenderLine,
826 } from "./ui.ts";
927
1028 const RENDER_OPTS = {
@@ -13,7 +31,52 @@ const RENDER_OPTS = {
1331 theme: DEFAULT_THEME,
1432 };
1533
34+function collectText(node: Node | null): string[] {
35+ if (!node) {
36+ return [];
37+ }
38+ if (node.type === "text") {
39+ return [node.content];
40+ }
41+ if (node.type === "textinput") {
42+ return [];
43+ }
44+ return node.children.flatMap((child) => collectText(child));
45+}
46+
47+function createTestState(): AppState {
48+ const db = openDatabase(":memory:");
49+ const cwd = "/tmp/mini-coder-ui-test";
50+ const session = createSession(db, { cwd });
51+ return {
52+ db,
53+ session,
54+ model: null,
55+ effort: "medium",
56+ messages: [],
57+ stats: { totalInput: 0, totalOutput: 0, totalCost: 0 },
58+ agentsMd: [],
59+ skills: [],
60+ plugins: [],
61+ theme: DEFAULT_THEME,
62+ git: null,
63+ providers: new Map(),
64+ oauthCredentials: {},
65+ cwd,
66+ canonicalCwd: cwd,
67+ running: false,
68+ abortController: null,
69+ showReasoning: DEFAULT_SHOW_REASONING,
70+ verbose: DEFAULT_VERBOSE,
71+ };
72+}
73+
1674 describe("ui rendering", () => {
75+ test("reasoning defaults on and verbose defaults off", () => {
76+ expect(DEFAULT_SHOW_REASONING).toBe(true);
77+ expect(DEFAULT_VERBOSE).toBe(false);
78+ });
79+
1780 test("renderAssistantMessage keeps streamed markdown inside one top-level container", () => {
1881 const message = fauxAssistantMessage("First paragraph\n\nSecond paragraph");
1982
@@ -27,6 +90,22 @@ describe("ui rendering", () => {
2790 expect(node.children.length).toBeGreaterThan(1);
2891 });
2992
93+ test("renderAssistantMessage shows thinking blocks when reasoning is enabled", () => {
94+ const message = fauxAssistantMessage([
95+ fauxThinking("I should inspect the tests first."),
96+ fauxText("Done."),
97+ ]);
98+
99+ const node = renderAssistantMessage(message, {
100+ ...RENDER_OPTS,
101+ showReasoning: true,
102+ });
103+ const text = collectText(node);
104+
105+ expect(text).toContain("I should inspect the tests first.");
106+ expect(text).toContain("Done.");
107+ });
108+
30109 test("renderStreamingResponse keeps text and tool output inside one top-level container", () => {
31110 const pendingToolCalls: PendingToolCall[] = [
32111 {
@@ -53,4 +132,169 @@ describe("ui rendering", () => {
53132 }
54133 expect(node.children.length).toBeGreaterThanOrEqual(2);
55134 });
135+
136+ test("renderStreamingResponse shows streaming thinking when reasoning is enabled", () => {
137+ const node = renderStreamingResponse(
138+ {
139+ text: "",
140+ thinking: "Reasoning in progress",
141+ pendingToolCalls: [],
142+ },
143+ {
144+ ...RENDER_OPTS,
145+ showReasoning: true,
146+ },
147+ );
148+ const text = collectText(node);
149+
150+ expect(text).toContain("Reasoning in progress");
151+ });
152+
153+ test("/help appends a persisted UI message to the conversation log", () => {
154+ const state = createTestState();
155+
156+ try {
157+ handleInput("/help", state);
158+ const logText = collectText({
159+ type: "vstack",
160+ props: {},
161+ children: buildConversationLog(state),
162+ });
163+
164+ expect(state.messages).toHaveLength(1);
165+ expect(state.messages[0]?.role).toBe("ui");
166+ expect(logText.some((line) => line.includes("Commands:"))).toBe(true);
167+ } finally {
168+ state.db.close();
169+ }
170+ });
171+
172+ test("buildHelpText includes current reasoning and verbose state", () => {
173+ const helpState: HelpRenderState = {
174+ providers: new Map(),
175+ model: null,
176+ agentsMd: [],
177+ skills: [],
178+ plugins: [],
Cut short: this commit's diff is over 1000 lines.
src/ui.ts+293−97
Cut short: this commit's diff is over 1000 lines.