xonecas.io
64875
Mc

mini-coder / commit b8846e7

feat: minimal TUI rework

xonecas2026-09-22 b8846e7ad81452b50446d7961fc1c7f3a35d692f parent d744b78

3 files changed

AGENTS.md+341−0
@@ -0,0 +1,341 @@
1+# mini-coder
2+
3+A fast, transparent, config-first terminal coding agent for one user at a time.
4+
5+This document records the intent and the decisions behind the code. The code is
6+the source of truth for behavior; this is the contract for anyone changing it.
7+
8+## Intent
9+
10+- A small, auditable agent core with no hidden machinery.
11+- A minimal system prompt with no injected meta-guidance.
12+- Provider work delegated entirely to `pi-ai`.
13+- Durable, user-owned, readable session logs.
14+- An append-only TUI with a small bounded live region and no full-screen buffer.
15+- First-class local (Ollama / llama.cpp / vLLM) and hosted models on equal footing.
16+
17+Prior art is reference, not template. `x.x.x-archive` holds the previous
18+implementation; `../awl/` (append-only live-region TUI, config-driven design),
19+`../bough/` (layer boundaries), and `../agent-ide/` (session durability, streaming)
20+are references. Extract ideas, do not port code.
21+
22+## Hard constraints
23+
24+- **Node.js directly.** No Bun, no Deno, no `Bun.*`, no Bun package scripts.
25+ Everything must work with `node`/`npm`.
26+- **No TUI library or framework.** No `cel-tui`, `OpenTUI`, `blessed`, `Ink`, or
27+ React. Render with direct `process.stdout` ANSI writes and plain strings.
28+- **`pi-ai` owns the provider layer.** All model requests, provider adapters,
29+ wire formats, streaming, auth resolution, and usage accounting go through
30+ `@earendil-works/pi-ai`. Never re-implement a provider protocol or fork it.
31+- **Do not copy other coding agents' source code.** Pi and `pi-ai` are behavioral references; write original code.
32+- **No sandboxing, no permission layer.** Tools run with the user's permissions.
33+ Isolation is an environment concern (`nono`), not the agent's. No jail,
34+ approval gate, or supervisor.
35+- **No loop limits.** No max turns, tool calls, token budgets, or agent-imposed
36+ timeouts. The user's ability to interrupt is the limit.
37+- **Config-first.** Every user-facing behavior that can vary comes from config
38+ with a sane default.
39+- **Minimal context.** The model sees only the configured system prompt plus
40+ explicitly opted-in resource files. No doom-loop reminders, hidden
41+ `<system-reminder>` blocks, internal-behavior text, or harness meta-text.
42+
43+## Runtime and repo shape
44+
45+- TypeScript, ESM, `"type": "module"`, `strict`, `erasableSyntaxOnly`,
46+ `verbatimModuleSyntax`.
47+- TypeScript runs directly through Node's native type stripping (`node src/cli.ts`).
48+ Use relative imports with explicit `.ts` extensions. Avoid non-erasable syntax
49+ (`enum`, `namespace`, parameter properties, legacy decorators).
50+- `bin/mini-coder.ts` is a thin shebang shim importing `src/cli.ts`.
51+- Module boundaries (names may change, boundaries may not move):
52+ - `cli` — argument parsing, mode selection, process wiring.
53+ - `config` — load, validate, merge, resolve config; build `pi-ai` models.
54+ - `session` — append-only JSONL store; projection to a `pi-ai` `Context`.
55+ - `agent` — streaming loop, tool dispatch, pause/cancel state. No UI, no
56+ provider-specific code.
57+ - `tools` — `edit`, `bash` runners. No UI.
58+ - `prompt` — system-prompt assembly (config, skills, `AGENTS.md`).
59+ - `tui` — terminal live region and input editor; a projection of agent events.
60+- The agent must not import `tui`. The TUI must not own agent or provider
61+ semantics. Headless and TUI are two projections of the same agent events.
62+
63+## Configuration
64+
65+Global config only, at `$XDG_CONFIG_HOME/mini-coder/config.json`
66+(default `~/.config/mini-coder/config.json`). No project-local config, no
67+config-override flags. A missing file is valid and uses defaults.
68+
69+Because `pi-ai` owns the provider catalog, auth env vars, base URLs, wire APIs,
70+and compat detection, model config stays thin. A built-in provider needs only
71+`provider` + `model`; `customProviders` exists only for endpoints `pi-ai` does
72+not ship.
73+
74+Fields and defaults:
75+
76+- `sessionsDir` — root for per-session directories. Default `<cwd>/sessions`.
77+- `systemPrompt` — base system prompt. Default `""`.
78+- `discoverAgentFiles` — include discovered `AGENTS.md`/`CLAUDE.md`. Default `true`.
79+- `skillsDirs` — directories scanned for `SKILL.md`. Default `[]` (no skills).
80+- `tools` — enabled tool names. Default `["edit", "bash"]`.
81+- `provider` — built-in `pi-ai` provider id or a `customProviders[].id`.
82+ Default `"anthropic"`.
83+- `model` — model id within that provider. Default `"claude-sonnet-4-5"`.
84+- `thinkingEffort` — one of `minimal`, `low`, `medium`, `high`, `xhigh`, `max`.
85+ Default `"medium"`.
86+- `customProviders` — array; default `[]`. Each entry:
87+ - `id` (matches the active `provider`),
88+ - `name` (display; defaults to `id`),
89+ - `baseUrl`,
90+ - `api` — explicit `pi-ai` wire id: `openai-completions`,
91+ `openai-responses`, `anthropic-messages`, or `google-generative-ai`. Never
92+ inferred from a name or URL,
93+ - `models` — model ids served there,
94+ - `envKeys` — optional credential env vars; omit for keyless local servers,
95+ - `headers` — optional extra request headers.
96+
97+Decisions:
98+
99+- Built-in models are looked up in `pi-ai`'s catalog. Do not duplicate catalog
100+ data or env vars in mini-coder.
101+- Omitted custom-model metadata uses safe defaults (`reasoning: false`,
102+ `input: ["text"]`, zero cost, 200k context, 32k max tokens). `pi-ai`
103+ auto-detects `compat` from `baseUrl`; add overrides only when a concrete
104+ endpoint misbehaves.
105+- `headers` merge into requests and are kept out of session records.
106+- Unknown `tools` names and unknown config keys are config errors. Validate at
107+ load and name the failing field.
108+
109+## Provider integration
110+
111+Use `pi-ai` entrypoints: `builtinModels()` / `createModels()`,
112+`createProvider({ id, name, baseUrl, auth, models, api })`,
113+`envApiKeyAuth(displayName, envVars)`,
114+`models.streamSimple(model, context, { reasoning, signal, sessionId })`, and the
115+`Type` re-export. Import API implementations only from
116+`@earendil-works/pi-ai/api/<api>.lazy` so unused provider SDKs are not bundled.
117+
118+Decisions:
119+
120+- Register built-ins with `builtinModels()` and custom entries with
121+ `createProvider`. Keyless custom providers get a stub auth that resolves a
122+ placeholder key rather than an env lookup.
123+- Auth is entirely `pi-ai`'s. Credentials resolve from env vars only; stored
124+ credentials, login flows, and a persistent `CredentialStore` are deferred.
125+- Keep the adapter thin. Consume `pi-ai` message/stream types directly; do not
126+ translate them into a parallel model. Keep provider-specific continuation data
127+ (opaque blocks, signatures) intact in the session.
128+
129+## Session persistence
130+
131+`pi-ai` ships no session store. The session layer is a thin append-only JSONL
132+wrapper over `pi-ai`'s own `Context`/`Message` types. Never invent a parallel
133+message model.
134+
135+One JSON object per line; never rewrite or delete committed lines. Records:
136+
137+- `{ type: "session", version: 1, id, cwd, createdAt, title }` — first line,
138+ written once.
139+- `{ type: "request", at, provider, model, api, thinkingEffort, systemPrompt,
140+ tools }` — written before each model request, capturing resolved inputs.
141+- `{ type: "message", at, message }` — each conversation message, stored as a
142+ `pi-ai` `Message` verbatim.
143+
144+Directory and file layout:
145+
146+```
147+<sessionsDir>/<YYYYMMDD>-<HHmmss>-<slug>-<shortid>/session.jsonl
148+```
149+
150+- The directory name is the session `id` and the canonical key. Never rename it.
151+- `YYYYMMDD-HHmmss` is UTC creation time, keeping `ls` chronological.
152+- `slug` comes from the first user message: lowercased, non-alphanumerics
153+ collapsed to `-`, trimmed, truncated to ~40 chars, falling back to `session`.
154+ The same function produces the `title`.
155+- `shortid` is 6 random base36 chars, disambiguating same-second, same-title
156+ sessions.
157+- Ensure `sessionsDir` recursively; create the session directory with exclusive
158+ `mkdirSync` and regenerate `shortid` on `EEXIST` (bounded attempts). No locks.
159+- Create lazily on the first user message so the slug is meaningful; the session
160+ is in-memory before that.
161+- One writer per session directory.
162+- Append with `writeSync` + `fsyncSync` so committed lines survive a crash. A
163+ persistence failure stops the turn; never continue with unrecorded side
164+ effects.
165+- On read, tolerate a truncated final line; reject corruption in committed
166+ history.
167+- Preserve message order and tool-call ↔ tool-result relationships. If partials
168+ are ever persisted, use `AssistantMessageFrameEncoder` /
169+ `reduceAssistantMessageFrames`, not a custom frame format.
170+
171+## Agent loop
172+
173+One loop, no limits. Per turn: assemble `{ systemPrompt, tools, messages }`,
174+`for await` over `streamSimple`, surface text/reasoning/tool-call events, append
175+the final assistant message, then execute any tool calls in order, appending
176+each result, and repeat. Stop when the assistant produces no tool calls, on
177+cancel, or on a surfaced error.
178+
179+Phases: `preparing`, `waitingModel`, `streaming`, `runningTool`, `pausing`,
180+`idle` (plus `cancelled` reachable from active states). Events: `phase`, `text`,
181+`reasoning`, `toolCall`, `toolOutput`, `toolResult`, `message`, `error`,
182+`cancelled`, `complete`.
183+
184+Decisions:
185+
186+- No compaction, summarization, or context rewriting.
187+- No automatic retries. Provider errors are surfaced, not hidden.
188+- No reminders or meta-messages between steps.
189+- The loop is driven by an `AbortSignal` and checks pause state at step
190+ boundaries (top of each iteration and before each tool call).
191+
192+## Tools
193+
194+`edit` and `bash` only. Stateless; recoverable failures return tool-result text,
195+not thrown errors. There is no `read` tool — the model reads files with Unix
196+tooling through `bash`. Tool arguments are untrusted input and are validated at
197+the boundary with Typebox (`Value.Parse`); application logic uses plain types.
198+
199+- **`edit`** — `{ path, oldText, newText }`. Exact find-and-replace. Fails when
200+ `oldText` is missing or matches more than once. Empty `oldText` creates a new
201+ file and fails if it exists. Returns a unified diff via `createTwoFilesPatch`
202+ from the `diff` package. Checks the abort signal before writing.
203+- **`bash`** — `{ command }`. Runs `bash -c` in `process.cwd()` in its own
204+ process group (`detached: true`) so cancellation can kill the whole tree.
205+ Streams stdout/stderr through `onOutput`, then returns combined output plus
206+ exit code. On abort, SIGTERM the group, then SIGKILL after a short grace.
207+ Output is bounded (10k head + 6k tail) and truncation is reported in
208+ `details` (`truncated`, `omittedChars`, `totalChars`) rather than silently
209+ dropped. No default timeout.
210+
211+Only tools named in config `tools` are exposed and may execute. No approval
212+prompts, sandboxing, or per-tool budgets.
213+
214+## System prompt assembly
215+
216+In order: config `systemPrompt`, then skills (when `skillsDirs` is non-empty),
217+then agent files (when `discoverAgentFiles`).
218+
219+- Agent files: load `AGENTS.md` and `CLAUDE.md` from `~/.agents/` and the project
220+ root (`process.cwd()`), trimmed, each under a heading naming its path.
221+- Skills: scan each `skillsDirs` entry for `<dir>/SKILL.md`, read its
222+ frontmatter (`name`, `description`), and advertise the absolute path so the
223+ model can read it with `bash` on demand. Progressive disclosure only — never
224+ inline skill bodies. No directories means no skills; there is no implicit
225+ global or project-local discovery.
226+- No other injected instructions, reminders, or environment blobs.
227+
228+## TUI
229+
230+Normal terminal screen. No alternate screen, no full-screen buffer, no
231+persistent cursor modes. Styling is unconstrained: SGR attributes and colour,
232+live or committed, are the renderer's choice, and `src/tui/` owns it. No flicker:
233+coalesce writes (16ms frame cadence) and never redraw committed output.
234+
235+Two regions:
236+
237+- **Committed history** — printed once to terminal scrollback and never
238+ redrawn. User turns, assistant text, tool calls, and tool results go here. The
239+ terminal owns scrollback, selection, and scrolling.
240+- **Live region** — at most the height of the terminal minus one row, holding
241+ the in-flight line (the current incomplete line of whichever stream is
242+ active), a one-row phase status, and the editor. Only this region is redrawn.
243+ When idle it holds the editor alone: no in-flight line, no status row.
244+
245+Scrollback is append-only and written before the live region is redrawn, never
246+after. Blocks — a user turn, a tool call with its result body, a terminal-state
247+line — are separated by exactly one blank line, never two, and never as the
248+first line. Each tool block is committed as a unit when its result arrives, so a
249+call and its body stay contiguous even when one assistant message announces
250+several calls before any of them runs.
251+
252+Redraw: move to the top of the live region, erase to end of screen, rewrite.
253+Track the region's height exactly: it changes when the status row appears or
254+disappears and when the in-flight line wraps, so erasing it means erasing every
255+occupied row, not one. When content is committed, print it above the live region
256+and shrink the region before the next frame. On `SIGWINCH`, drop the cursor
257+anchor and re-anchor rather than guessing; never erase committed history. Handle
258+wrapping, Unicode width, and tiny terminals without corrupting scrollback.
259+
260+Input editor (notepad-level, not Vim/readline parity): multiline
261+insertion/deletion, cursor movement across lines, reliable typing, backspace,
262+newline, and large bracketed paste. `Enter` submits; `Ctrl+J` inserts a newline
263+(`Shift+Enter` also maps to newline where the terminal sends it). The draft
264+survives redraws, cancellation, and errors. No undo/redo, history search, or
265+path completion.
266+
267+Terminal lifecycle: raw mode only in interactive mode; bracketed paste enabled;
268+restore prior mode, cursor visibility, and modified state on exit, cancel, and
269+`SIGINT`/`SIGTERM`. Re-read size on resize. Use `process.stdout.columns`/`rows`
270+with fallbacks for `0`/undefined. Escape sequences are parsed by a small state
271+machine with a short timeout to distinguish a lone ESC from a sequence.
272+
273+## Interruption and lifecycle
274+
275+- **ESC = polite pause request.** It never interrupts the current step: the
276+ in-flight model request completes and the running tool runs to completion. The
277+ loop then pauses at the next boundary for a steering message, which is
278+ appended before the turn continues.
279+- **CTRL+C = cancel the turn completely.** Abort the model request via
280+ `AbortSignal` and terminate the running tool's process group. Persist the
281+ aborted assistant message (`stopReason: "aborted"`). Return to idle; do not
282+ undo completed side effects.
283+- **CTRL+D = exit**, only when the input is empty. Flush the session, restore the
284+ terminal, exit cleanly.
285+- No max turns, tool-call budget, or automatic stop.
286+
287+## Headless mode
288+
289+`-p` / `--print` is the only CLI interface and the only flag. It runs one prompt
290+to completion non-interactively and prints the final assistant answer to stdout.
291+Accepted spellings: `-p <prompt>`, `--print <prompt>`, `-p=<prompt>`,
292+`--print=<prompt>`; unknown arguments are errors.
293+
294+- Persists the session under `sessionsDir` exactly like interactive mode; the
295+ JSONL log is the durable record. No other machine-readable stdout mode.
296+- Diagnostics, tool progress, and errors go to stderr.
297+- Never emit ANSI escapes or terminal controls when not a TTY; never wait for
298+ prompts.
299+- Exit `0` on success, non-zero on failure/cancel.
300+
301+## Reliability and diagnostics
302+
303+- Persistence failure stops the turn.
304+- Surface provider errors with their message; do not mask, summarize, or retry.
305+- Local diagnostics only. No remote telemetry. Debug output goes to stderr
306+ behind an explicit flag; redact secrets and prompt/tool content by default.
307+- No hidden stalls: every wait (model request, tool, pause) has a visible state
308+ in the TUI and a diagnostic path in headless mode.
309+
310+## Scope boundaries
311+
312+Deferred, not rejected. Do not build unless explicitly promoted:
313+
314+- context compaction / summarization / masking;
315+- prompt templates;
316+- custom agents / subagents / delegation;
317+- an extension or plugin system;
318+- a settings TUI or overlay editors;
319+- custom OAuth or auth implementations (use `pi-ai`'s provider auth);
320+- MCP, image generation, multi-agent orchestration;
321+- sandboxing, approval prompts, permission policies;
322+- tests and CI (standing rule: no tests unless asked);
323+- macOS/Windows behavior and cross-platform abstractions. Target Linux first.
324+
325+## Working agreement
326+
327+- Read `pi-ai`'s README and the reference projects before designing. Trace the
328+ real data flow; apply guards at the narrowest boundary.
329+- Keep the diff small. Do not opportunistically refactor or harden adjacent
330+ code.
331+- Prefer plain functions and objects over classes; keep exports minimal; define
332+ helpers near their use.
333+- Validate untrusted input once at the boundary (config, session records, tool
334+ args) with Typebox, then keep internal code plain-typed. Do not spread
335+ schema-derived types everywhere.
336+- Ask before adding a dependency. `diff` and `typebox` are approved;
337+ supply-chain risk is a real constraint.
338+- Do not add tests unless explicitly asked. Verify manually.
339+- Before finishing, review the diff against the hard constraints and the scope
340+ boundaries, remove anything that added scope, and report any requirement that
341+ could not be satisfied.
src/agent.ts+8−2
@@ -1,6 +1,7 @@
11 import {
22 type Api,
33 type AssistantMessage,
4+ type JsonObject,
45 type Message,
56 type Model,
67 type Models,
@@ -20,7 +21,7 @@ export type AgentEvent =
2021 | { type: "phase"; phase: Phase; detail?: string }
2122 | { type: "text"; delta: string }
2223 | { type: "reasoning"; delta: string }
23- | { type: "toolCall"; name: string; callId: string }
24+ | { type: "toolCall"; name: string; callId: string; arguments: JsonObject }
2425 | { type: "toolOutput"; name: string; callId: string; chunk: string }
2526 | { type: "toolResult"; name: string; callId: string; text: string; isError: boolean }
2627 | { type: "message"; message: AssistantMessage }
@@ -112,7 +113,12 @@ export async function runAgentTurn(run: AgentRun): Promise<void> {
112113 if (event.type === "text_delta") onEvent({ type: "text", delta: event.delta });
113114 else if (event.type === "thinking_delta") onEvent({ type: "reasoning", delta: event.delta });
114115 else if (event.type === "toolcall_end") {
115- onEvent({ type: "toolCall", name: event.toolCall.name, callId: event.toolCall.id });
116+ onEvent({
117+ type: "toolCall",
118+ name: event.toolCall.name,
119+ callId: event.toolCall.id,
120+ arguments: event.toolCall.arguments,
121+ });
116122 }
117123 }
118124 } catch (error) {
src/tui/tui.ts+241−94
@@ -2,6 +2,7 @@ import process from "node:process";
22 import type {
33 Api,
44 AssistantMessage,
5+ JsonObject,
56 Message,
67 Model,
78 Models,
@@ -12,7 +13,7 @@ import type {
1213 import { runAgentTurn, type AgentEvent, type Phase } from "../agent.ts";
1314 import type { Session } from "../session.ts";
1415 import type { ToolName } from "../config.ts";
15-import { Terminal, wrapLine, type Key } from "./term.ts";
16+import { Terminal, expandTabs, wrapLine, type Key } from "./term.ts";
1617 import { Editor } from "./editor.ts";
1718
1819 export interface TuiOptions {
@@ -25,45 +26,74 @@ export interface TuiOptions {
2526 session: Session;
2627 }
2728
28-const MAX_LIVE_ROWS = 8;
29-const MAX_LIVE_CHARS = 4000;
29+/** Status-row spinner frames; the only animation in the TUI. */
30+const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
31+const SPINNER_MS = 120;
3032
31-function wrapText(text: string, width: number): string[] {
32- return text.split("\n").flatMap((line) => wrapLine(line, width));
33+/**
34+ * Display-only elision for tool bodies, deliberately worded differently from
35+ * the model-facing `... output truncated ...` marker in `tools.ts`.
36+ */
37+const MAX_BODY_ROWS = 12;
38+const ELIDED_HEAD = 4;
39+const ELIDED_TAIL = 4;
40+
41+const BODY_PREFIX = " | ";
42+const ERROR_PREFIX = " ! ";
43+const EXIT_LINE = /^exit code: (.+)$/;
44+const EDIT_HEADER = /^(Index: |={3,}$|--- |\+\+\+ )/;
45+
46+function dim(text: string): string {
47+ return `\x1b[2m${text}\x1b[22m`;
3348 }
3449
35-interface LiveRow {
36- text: string;
37- dim: boolean;
50+/** The text after the last newline: what is still incomplete. */
51+function incomplete(text: string): string {
52+ const index = text.lastIndexOf("\n");
53+ return index >= 0 ? text.slice(index + 1) : text;
3854 }
3955
40-function wrapStyled(text: string, width: number, dim: boolean): LiveRow[] {
41- return wrapText(text, width).map((line) => ({ text: line, dim }));
56+/** The lines completed by the newest text, excluding the incomplete tail. */
57+function completeLines(text: string): string[] {
58+ const lines = text.split("\n");
59+ lines.pop();
60+ return lines;
4261 }
4362
44-function dim(text: string): string {
45- return `\x1b[2m${text}\x1b[22m`;
63+function callSummary(name: string, args: JsonObject): string {
64+ if (name === "bash" && typeof args.command === "string") return args.command.replace(/\s*\n\s*/g, " ");
65+ if (name === "edit" && typeof args.path === "string") return args.path;
66+ return JSON.stringify(args);
4667 }
4768
48-function tail(text: string): string {
49- return text.length > MAX_LIVE_CHARS ? text.slice(text.length - MAX_LIVE_CHARS) : text;
69+/** Display rewrite of a tool result, by tool name. */
70+function resultLines(name: string, text: string, isError: boolean): string[] {
71+ const lines = text.trimEnd().split("\n");
72+ if (name === "bash") {
73+ const exit = EXIT_LINE.exec(lines[lines.length - 1]);
74+ if (exit !== null) {
75+ lines.pop();
76+ if (isError) lines.push(`exit ${exit[1]}`);
77+ }
78+ } else if (name === "edit" && /^(edited|created) /.test(lines[0])) {
79+ lines.shift();
80+ // The call line already names the path; drop the repeated diff file header.
81+ while (lines.length > 0 && EDIT_HEADER.test(lines[0])) lines.shift();
82+ }
83+ return lines;
5084 }
5185
52-function phaseStatus(phase: Phase, detail?: string): string {
53- switch (phase) {
54- case "preparing":
55- return "preparing";
56- case "waitingModel":
57- return "waiting for provider";
58- case "streaming":
59- return "streaming";
60- case "runningTool":
61- return `running ${detail ?? "tool"}`;
62- case "pausing":
63- return "paused — type steering, Enter to continue";
64- case "idle":
65- return "ready";
86+function bodyRows(lines: string[], width: number): string[] {
87+ const rows = lines.flatMap((line) => wrapLine(expandTabs(line), width));
88+ if (rows.length > MAX_BODY_ROWS) {
89+ const hidden = rows.length - ELIDED_HEAD - ELIDED_TAIL;
90+ return [
91+ ...rows.slice(0, ELIDED_HEAD),
92+ `... ${hidden} lines not shown ...`,
93+ ...rows.slice(rows.length - ELIDED_TAIL),
94+ ];
6695 }
96+ return rows;
6797 }
6898
6999 class LiveRegion {
@@ -86,11 +116,12 @@ class LiveRegion {
86116 return out;
87117 }
88118
89- draw(lines: LiveRow[], cursorRow: number, cursorCol: number): string {
119+ /** `lines` are already styled; the live region adds no attributes of its own. */
120+ draw(lines: string[], cursorRow: number, cursorCol: number): string {
90121 let out = this.clear();
91122 for (let i = 0; i < lines.length; i++) {
92123 if (i > 0) out += "\r\n";
93- out += lines[i].dim ? dim(lines[i].text) : lines[i].text;
124+ out += lines[i];
94125 }
95126 const up = lines.length - 1 - cursorRow;
96127 if (up > 0) out += `\x1b[${up}A`;
@@ -111,10 +142,8 @@ class Tui {
111142 readonly done: Promise<void>;
112143
113144 private resolveExit: () => void = () => {};
114- private status = "ready";
115- private reasoning = "";
116- private answer = "";
117- private toolOutput = "";
145+ private phase: Phase = "idle";
146+ private detail: string | undefined;
118147 private active = false;
119148 private paused = false;
120149 private pauseRequested = false;
@@ -124,6 +153,21 @@ class Tui {
124153 private reanchor = false;
125154 private closed = false;
126155
156+ // Scrollback: lines accumulate here and are written above the live region.
157+ private scroll = "";
158+ private wrote = false;
159+ private lastBlank = false;
160+ private separator = false;
161+
162+ // In-flight stream state, never persisted: all display-only.
163+ private pending = "";
164+ private preview = "";
165+ private pendingCalls: string[] = [];
166+ private streamed = "";
167+ private turnStart = 0;
168+ private frame = 0;
169+ private spinner: NodeJS.Timeout | undefined;
170+
127171 constructor(opts: TuiOptions) {
128172 this.opts = opts;
129173 this.term = new Terminal({
@@ -139,10 +183,12 @@ class Tui {
139183 this.term.start();
140184 process.on("SIGINT", this.onSignal);
141185 process.on("SIGTERM", this.onSignal);
142- this.commit(
186+ this.separator = true;
187+ this.push(
143188 `mini-coder · ${this.opts.model.provider}/${this.opts.model.id} · ` +
144189 "Enter submit · Ctrl+J newline · Esc pause · Ctrl+C cancel · Ctrl+D exit",
145190 );
191+ this.separator = true;
146192 this.render();
147193 }
148194
@@ -174,7 +220,6 @@ class Tui {
174220 if (key.type === "escape") {
175221 if (this.active && !this.paused) {
176222 this.pauseRequested = true;
177- this.status = "pause requested";
178223 this.render();
179224 }
180225 return;
@@ -209,7 +254,14 @@ class Tui {
209254 private startTurn(): void {
210255 this.active = true;
211256 this.abort = new AbortController();
212- this.status = "preparing";
257+ this.phase = "preparing";
258+ this.detail = undefined;
259+ this.turnStart = Date.now();
260+ this.frame = 0;
261+ this.spinner = setInterval(() => {
262+ this.frame++;
263+ this.render();
264+ }, SPINNER_MS);
213265 void this.runTurn();
214266 this.render();
215267 }
@@ -245,8 +297,8 @@ class Tui {
245297 onEvent: (event) => this.handleAgentEvent(event),
246298 });
247299 } catch (error) {
248- this.status = "failed";
249- this.commit(`! ${(error as Error).message}`);
300+ this.separator = true;
301+ this.push(`! ${(error as Error).message}`);
250302 } finally {
251303 this.active = false;
252304 this.abort = null;
@@ -257,6 +309,8 @@ class Tui {
257309 resolve("");
258310 }
259311 this.paused = false;
312+ if (this.spinner) clearInterval(this.spinner);
313+ this.spinner = undefined;
260314 this.render();
261315 }
262316 }
@@ -269,7 +323,6 @@ class Tui {
269323 resolve("");
270324 }
271325 this.abort?.abort();
272- this.status = "cancelling";
273326 this.render();
274327 }
275328
@@ -277,79 +330,148 @@ class Tui {
277330 if (this.closed) return;
278331 switch (event.type) {
279332 case "phase":
280- this.status = phaseStatus(event.phase, event.detail);
333+ this.phase = event.phase;
334+ this.detail = event.detail;
281335 if (event.phase === "pausing") this.paused = true;
282336 break;
283337 case "text":
284- this.answer = tail(this.answer + event.delta);
338+ this.preview = "";
339+ this.pending += event.delta;
340+ this.streamed += event.delta;
341+ for (const line of completeLines(this.pending)) this.push(line);
342+ this.pending = incomplete(this.pending);
285343 break;
286344 case "reasoning":
287- this.reasoning = tail(this.reasoning + event.delta);
345+ if (this.pending === "") this.preview = incomplete(this.preview + event.delta);
288346 break;
289347 case "toolCall":
348+ // Flush first so scrollback order matches execution order, then hold the
349+ // call line until its result arrives: a message may carry several calls,
350+ // all announced before any of them runs.
351+ this.flushPending();
352+ this.preview = "";
353+ this.pendingCalls.push(`-> ${event.name} ${callSummary(event.name, event.arguments)}`);
290354 break;
291355 case "toolOutput":
292- this.toolOutput = tail(this.toolOutput + event.chunk);
356+ this.preview = incomplete(this.preview + event.chunk);
293357 break;
294358 case "message":
295- this.commitAssistant(event.message);
296- this.answer = "";
297- this.reasoning = "";
359+ this.commitMessage(event.message);
298360 break;
299361 case "toolResult":
300- this.commitToolResult(event.text, event.isError);
301- this.toolOutput = "";
362+ this.preview = "";
363+ this.commitToolResult(event.name, event.text, event.isError);
302364 break;
303365 case "error":
304- this.status = "failed";
305- this.commit(`! ${event.message}`);
366+ this.finishTurn();
367+ this.flushPending();
368+ this.flushCalls();
369+ this.separator = true;
370+ this.push(`! ${event.message}`);
306371 break;
307372 case "cancelled":
308- this.status = "cancelled";
309- this.commit("! cancelled");
373+ this.finishTurn();
374+ this.flushPending();
375+ this.flushCalls();
376+ this.separator = true;
377+ this.push("! cancelled");
310378 break;
311379 case "complete":
312- this.status = "complete";
380+ this.finishTurn();
381+ this.flushPending();
382+ this.flushCalls();
383+ this.separator = true;
384+ this.push(dim(`[complete · ${this.elapsed()}s]`));
313385 break;
314386 }
315387 this.render();
316388 }
317389
390+ /** Terminal states clear the status row instead of lingering in it. */
391+ private finishTurn(): void {
392+ this.phase = "idle";
393+ this.detail = undefined;
394+ this.paused = false;
395+ }
396+
397+ private elapsed(): number {
398+ return Math.max(0, Math.floor((Date.now() - this.turnStart) / 1000));
399+ }
400+
318401 private commitUser(text: string): void {
319- this.commit(
320- text
321- .split("\n")
322- .map((line) => `> ${line}`)
323- .join("\n"),
324- );
402+ this.separator = true;
403+ for (const line of text.split("\n")) this.push(`> ${line}`);
404+ this.separator = true;
325405 }
326406
327- private commitAssistant(message: AssistantMessage): void {
328- const parts: string[] = [];
329- for (const block of message.content) {
330- if (block.type === "thinking") {
331- if (block.thinking.trim()) parts.push(dim(block.thinking.trimEnd()));
332- } else if (block.type === "text") {
333- if (block.text.trim()) parts.push(block.text.trimEnd());
334- } else if (block.type === "toolCall") {
335- parts.push(`→ ${block.name} ${JSON.stringify(block.arguments)}`);
336- }
407+ /** Commits a line the model emitted without streaming it, plus the in-flight tail. */
408+ private commitMessage(message: AssistantMessage): void {
409+ this.preview = "";
410+ this.flushPending();
411+ const text = message.content
412+ .filter((block) => block.type === "text")
413+ .map((block) => block.text)
414+ .join("");
415+ if (text.trim() !== "" && !this.streamed.includes(text)) {
416+ for (const line of text.trimEnd().split("\n")) this.push(line);
337417 }
338- if (parts.length > 0) this.commit(parts.join("\n"));
418+ this.streamed = "";
339419 }
340420
341- private commitToolResult(text: string, isError: boolean): void {
342- const body = text.trimEnd();
343- if (body === "") return;
344- this.commit(isError ? `! ${body}` : body);
421+ private commitToolResult(name: string, text: string, isError: boolean): void {
422+ const call = this.pendingCalls.shift();
423+ this.separator = true;
424+ if (call !== undefined) this.push(call);
425+ const width = Math.max(1, this.term.width - BODY_PREFIX.length);
426+ const rows = bodyRows(resultLines(name, text, isError), width);
427+ for (let i = 0; i < rows.length; i++) {
428+ const prefix = isError && i === rows.length - 1 ? ERROR_PREFIX : BODY_PREFIX;
429+ this.push(prefix + rows[i]);
430+ }
431+ this.separator = true;
432+ }
433+
434+ /** Commits any call line whose result never arrived, e.g. after a cancel. */
435+ private flushCalls(): void {
436+ for (const call of this.pendingCalls) {
437+ this.separator = true;
438+ this.push(call);
439+ }
440+ this.pendingCalls = [];
441+ }
442+
443+ private flushPending(): void {
444+ if (this.pending === "") return;
445+ const line = this.pending;
446+ this.pending = "";
447+ this.push(line);
448+ }
449+
450+ /**
451+ * Appends one scrollback line. A block boundary owes exactly one blank line,
452+ * and two blank lines never appear in a row.
453+ */
454+ private push(line: string): void {
455+ const blank = line === "" || (this.separator && this.wrote);
456+ this.separator = false;
457+ if (blank && this.wrote && !this.lastBlank) {
458+ this.scroll += "\n";
459+ this.lastBlank = true;
460+ }
461+ if (line !== "") {
462+ this.scroll += `${line}\n`;
463+ this.wrote = true;
464+ this.lastBlank = false;
465+ }
466+ this.flushScroll();
345467 }
346468
347- private commit(text: string): void {
348- if (this.closed || text === "") return;
349- let out = this.live.clear();
350- out += text.endsWith("\n") ? text : `${text}\n`;
469+ /** Scrollback is written before the live region is redrawn, never after. */
470+ private flushScroll(): void {
471+ if (this.scroll === "") return;
472+ const out = this.live.clear() + this.scroll;
473+ this.scroll = "";
351474 this.term.write(out);
352- this.render();
353475 }
354476
355477 private render(): void {
@@ -361,25 +483,48 @@ class Tui {
361483 }, 16);
362484 }
363485
486+ /** One dim row while a turn is active or paused; nothing when idle. */
487+ private statusLine(): string | null {
488+ if (this.paused || this.phase === "pausing") return "paused - type steering, Enter to continue";
489+ if (!this.active || this.phase === "idle") return null;
490+ const label =
491+ this.phase === "preparing"
492+ ? "preparing"
493+ : this.phase === "waitingModel"
494+ ? "waiting for provider"
495+ : this.phase === "streaming"
496+ ? "streaming"
497+ : `running ${this.detail ?? "tool"}`;
498+ return `${SPINNER[this.frame % SPINNER.length]} ${label} · ${this.elapsed()}s`;
499+ }
500+
364501 private draw(): void {
365502 if (this.closed) return;
366503 const width = Math.max(1, this.term.width);
367- const maxLive = Math.max(1, Math.min(MAX_LIVE_ROWS, this.term.height - 1));
368- const all: LiveRow[] = [];
369- if (this.reasoning) all.push(...wrapStyled(this.reasoning, width, true));
370- if (this.answer) all.push(...wrapStyled(this.answer, width, false));
371- if (this.toolOutput) all.push(...wrapStyled(this.toolOutput, width, false));
372- all.push(...wrapStyled(`[${this.status}]`, width, true));
504+ const lines: string[] = [];
505+ const pending = this.pending !== "" ? this.pending : this.preview;
506+ if (pending !== "") {
507+ const styled = this.pending === "" ? dim : (row: string) => row;
508+ for (const row of wrapLine(expandTabs(pending), width)) lines.push(styled(row));
509+ }
510+ const status = this.statusLine();
511+ if (status !== null) lines.push(dim(status));
373512 const editor = this.editor.render(width);
374- for (const row of editor.rows) all.push({ text: row, dim: false });
375- const shown = all.slice(-maxLive);
376- const editorOffset = all.length - editor.rows.length;
377- const shownOffset = all.length - shown.length;
378- let cursorRow = editorOffset + editor.cursorRow - shownOffset;
513+ const editorStart = lines.length;
514+ lines.push(...editor.rows);
515+
516+ let cursorRow = editorStart + editor.cursorRow;
379517 let cursorCol = editor.cursorCol;
380- if (cursorRow < 0) {
381- cursorRow = 0;
382- cursorCol = 0;
518+ let shown = lines;
519+ const maxRows = Math.max(1, this.term.height - 1);
520+ if (lines.length > maxRows) {
521+ const dropped = lines.length - maxRows;
522+ shown = lines.slice(dropped);
523+ cursorRow -= dropped;
524+ if (cursorRow < 0) {
525+ cursorRow = 0;
526+ cursorCol = 0;
527+ }
383528 }
384529 if (cursorRow >= shown.length) cursorRow = shown.length - 1;
385530 const prefix = this.reanchor ? "\r\n" : "";
@@ -391,6 +536,8 @@ class Tui {
391536 if (this.closed) return;
392537 this.closed = true;
393538 this.abort?.abort();
539+ if (this.spinner) clearInterval(this.spinner);
540+ this.spinner = undefined;
394541 this.term.write(this.live.clear());
395542 this.term.stop();
396543 this.opts.session.close();