xonecas.io
64875
Mc

mini-coder / commit 5eac87d

refactor: split ui into focused modules

xonecas2026-04-07 5eac87d893b0a5afe88461e6cb29b0e943dc96e8 parent 20af7c0

15 files changed

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

TODO.md+1−0
@@ -33,6 +33,7 @@ The spec.md and code are the sources of truth, not this file, don't assume anyth
3333
3434 ## Future ideas
3535
36+- [ ] Colocate extracted UI module tests under `src/ui/` (`agent.test.ts`, `commands.test.ts`, etc.) instead of keeping them at `src/ui.*.test.ts`
3637 - [ ] Demo asset tooling — script README preview GIF/poster generation from terminal recordings instead of relying on ad hoc `ffmpeg` commands
3738 - [ ] Session list preview — show first user message snippet in `/session` selector
3839 - [ ] Divider theme plugin — customizable divider animations (scanning pulse, breathing, flowing dots, wave)
src/ui.agent.test.ts+49−0
@@ -0,0 +1,49 @@
1+import { describe, expect, test } from "bun:test";
2+import { isEmptyUserContent, stripSkillFrontmatter } from "./ui/agent.ts";
3+
4+describe("ui/agent", () => {
5+ test("stripSkillFrontmatter removes frontmatter and keeps the skill body", () => {
6+ const content = [
7+ "---",
8+ "name: code-review",
9+ 'description: "Review code for issues"',
10+ "---",
11+ "# Review Checklist",
12+ "- Find bugs",
13+ "",
14+ ].join("\n");
15+
16+ expect(stripSkillFrontmatter(content)).toBe(
17+ "# Review Checklist\n- Find bugs\n",
18+ );
19+ });
20+
21+ test("stripSkillFrontmatter leaves content without frontmatter unchanged", () => {
22+ expect(stripSkillFrontmatter("# Skill\nUse this carefully\n")).toBe(
23+ "# Skill\nUse this carefully\n",
24+ );
25+ });
26+
27+ test("isEmptyUserContent returns true for empty text-only content", () => {
28+ expect(isEmptyUserContent(" \n\t")).toBe(true);
29+ expect(
30+ isEmptyUserContent([
31+ { type: "text", text: " " },
32+ { type: "text", text: "\n" },
33+ ]),
34+ ).toBe(true);
35+ });
36+
37+ test("isEmptyUserContent returns false when multipart content includes an image", () => {
38+ expect(
39+ isEmptyUserContent([
40+ { type: "text", text: " " },
41+ {
42+ type: "image",
43+ data: Buffer.from("fake-png-data").toString("base64"),
44+ mimeType: "image/png",
45+ },
46+ ]),
47+ ).toBe(false);
48+ });
49+});
src/ui.commands.test.ts+238−0
@@ -0,0 +1,238 @@
1+import { describe, expect, test } from "bun:test";
2+import { join } from "node:path";
3+import type { ContainerNode, Node } from "@cel-tui/types";
4+import { registerFauxProvider } from "@mariozechner/pi-ai";
5+import type { AppState } from "./index.ts";
6+import { COMMANDS } from "./input.ts";
7+import { appendPromptHistory, openDatabase } from "./session.ts";
8+import { DEFAULT_THEME } from "./theme.ts";
9+import {
10+ createCommandController,
11+ formatPromptHistoryPreview,
12+ formatRelativeDate,
13+} from "./ui/commands.ts";
14+import type { ActiveOverlay } from "./ui/overlay.ts";
15+import { renderOverlay } from "./ui/overlay.ts";
16+
17+function collectText(node: Node | null): string[] {
18+ if (!node) {
19+ return [];
20+ }
21+ if (node.type === "text") {
22+ return [node.content];
23+ }
24+ if (node.type === "textinput") {
25+ return [];
26+ }
27+ return node.children.flatMap((child) => collectText(child));
28+}
29+
30+function findNodeWithKeyPress(node: Node | null): ContainerNode | null {
31+ if (!node || node.type === "textinput" || node.type === "text") {
32+ return null;
33+ }
34+ if (typeof node.props.onKeyPress === "function") {
35+ return node;
36+ }
37+ for (const child of node.children) {
38+ const found = findNodeWithKeyPress(child);
39+ if (found) {
40+ return found;
41+ }
42+ }
43+ return null;
44+}
45+
46+function createTestState(): AppState {
47+ const db = openDatabase(":memory:");
48+ const cwd = "/tmp/mini-coder-ui-commands-test";
49+ return {
50+ db,
51+ session: null,
52+ model: null,
53+ effort: "medium",
54+ messages: [],
55+ stats: { totalInput: 0, totalOutput: 0, totalCost: 0 },
56+ agentsMd: [],
57+ skills: [],
58+ plugins: [],
59+ theme: DEFAULT_THEME,
60+ git: null,
61+ providers: new Map(),
62+ oauthCredentials: {},
63+ settings: {},
64+ settingsPath: join(cwd, "settings.json"),
65+ cwd,
66+ canonicalCwd: cwd,
67+ running: false,
68+ abortController: null,
69+ showReasoning: true,
70+ verbose: false,
71+ };
72+}
73+
74+describe("ui/commands", () => {
75+ test("showCommandAutocomplete clears the current draft and opens the commands overlay", () => {
76+ const state = createTestState();
77+ const runtimeState = { overlay: null as ActiveOverlay | null };
78+ let inputValue = "draft";
79+ const controller = createCommandController({
80+ openOverlay: (nextOverlay) => {
81+ runtimeState.overlay = nextOverlay;
82+ },
83+ dismissOverlay: () => {
84+ runtimeState.overlay = null;
85+ },
86+ setInputValue: (value) => {
87+ inputValue = value;
88+ },
89+ appendInfoMessage: () => {},
90+ scrollConversationToBottom: () => {},
91+ render: () => {},
92+ openInBrowser: () => {},
93+ });
94+
95+ try {
96+ controller.showCommandAutocomplete(state);
97+
98+ const overlay = runtimeState.overlay;
99+
100+ expect(inputValue).toBe("");
101+ expect(overlay).not.toBeNull();
102+ if (!overlay) {
103+ throw new Error("Expected the commands overlay to open");
104+ }
105+ expect(overlay.title).toBe("Commands");
106+
107+ const text = collectText(renderOverlay(state.theme, overlay));
108+ expect(text).toContain("Commands");
109+ for (const command of COMMANDS) {
110+ expect(text.some((line) => line.includes(`/${command}`))).toBe(true);
111+ }
112+ } finally {
113+ state.db.close();
114+ }
115+ });
116+
117+ test("showInputHistoryOverlay restores the selected raw prompt", () => {
118+ const state = createTestState();
119+ const runtimeState = { overlay: null as ActiveOverlay | null };
120+ let inputValue = "draft";
121+ const rawPrompt = "first line\nsecond line";
122+ const controller = createCommandController({
123+ openOverlay: (nextOverlay) => {
124+ runtimeState.overlay = nextOverlay;
125+ },
126+ dismissOverlay: () => {
127+ runtimeState.overlay = null;
128+ },
129+ setInputValue: (value) => {
130+ inputValue = value;
131+ },
132+ appendInfoMessage: () => {},
133+ scrollConversationToBottom: () => {},
134+ render: () => {},
135+ openInBrowser: () => {},
136+ });
137+
138+ try {
139+ appendPromptHistory(state.db, {
140+ text: "older prompt",
141+ cwd: "/tmp/older",
142+ });
143+ appendPromptHistory(state.db, { text: rawPrompt, cwd: state.cwd });
144+
145+ controller.showInputHistoryOverlay(state);
146+
147+ const overlay = runtimeState.overlay;
148+
149+ expect(overlay).not.toBeNull();
150+ if (!overlay) {
151+ throw new Error("Expected the input history overlay to open");
152+ }
153+ expect(overlay.title).toBe("Input history");
154+
155+ const selectNode = findNodeWithKeyPress(
156+ renderOverlay(state.theme, overlay),
157+ );
158+ expect(selectNode).not.toBeNull();
159+ if (!selectNode) {
160+ throw new Error("Expected overlay to contain a Select root");
161+ }
162+
163+ selectNode.props.onKeyPress?.("enter");
164+
165+ expect(runtimeState.overlay).toBeNull();
166+ expect(inputValue).toBe(rawPrompt);
167+ } finally {
168+ state.db.close();
169+ }
170+ });
171+
172+ test("handleCommand returns false for unknown commands", () => {
173+ const state = createTestState();
174+ const controller = createCommandController({
175+ openOverlay: () => {},
176+ dismissOverlay: () => {},
177+ setInputValue: () => {},
178+ appendInfoMessage: () => {},
179+ scrollConversationToBottom: () => {},
180+ render: () => {},
181+ openInBrowser: () => {},
182+ });
183+
184+ try {
185+ expect(controller.handleCommand("unknown", state)).toBe(false);
186+ } finally {
187+ state.db.close();
188+ }
189+ });
190+
191+ test("applyModelSelection updates the state and persists the default model", () => {
192+ const faux = registerFauxProvider();
193+ const state = createTestState();
194+ const model = faux.getModel();
195+ const controller = createCommandController({
196+ openOverlay: () => {},
197+ dismissOverlay: () => {},
198+ setInputValue: () => {},
199+ appendInfoMessage: () => {},
200+ scrollConversationToBottom: () => {},
201+ render: () => {},
202+ openInBrowser: () => {},
203+ });
204+
205+ try {
206+ controller.applyModelSelection(state, model);
207+
208+ expect(state.model).toBe(model);
209+ expect(state.settings.defaultModel).toBe(`${model.provider}/${model.id}`);
210+ } finally {
211+ faux.unregister();
212+ state.db.close();
213+ }
214+ });
215+
216+ test("formatRelativeDate accepts an explicit clock for deterministic output", () => {
217+ const now = new Date("2026-04-07T12:00:00Z");
218+
219+ expect(formatRelativeDate(new Date("2026-04-07T11:59:45Z"), now)).toBe(
220+ "just now",
221+ );
222+ expect(formatRelativeDate(new Date("2026-04-07T11:50:00Z"), now)).toBe(
223+ "10m ago",
224+ );
225+ expect(formatRelativeDate(new Date("2026-04-07T10:00:00Z"), now)).toBe(
226+ "2h ago",
227+ );
228+ expect(formatRelativeDate(new Date("2026-04-04T12:00:00Z"), now)).toBe(
229+ "3d ago",
230+ );
231+ });
232+
233+ test("formatPromptHistoryPreview collapses whitespace into one line", () => {
234+ expect(formatPromptHistoryPreview(" first\n\n second\tthird ")).toBe(
235+ "first second third",
236+ );
237+ });
238+});
src/ui.conversation.test.ts+151−0
@@ -0,0 +1,151 @@
1+import { describe, expect, test } from "bun:test";
2+import type { Node } from "@cel-tui/types";
3+import { DEFAULT_THEME, type Theme } from "./theme.ts";
4+import {
5+ previewToolRenderLines,
6+ renderToolResult,
7+ type ToolRenderLine,
8+} from "./ui/conversation.ts";
9+
10+const RENDER_OPTS = {
11+ showReasoning: false,
12+ verbose: false,
13+ theme: DEFAULT_THEME,
14+};
15+
16+function collectText(node: Node | null): string[] {
17+ if (!node) {
18+ return [];
19+ }
20+ if (node.type === "text") {
21+ return [node.content];
22+ }
23+ if (node.type === "textinput") {
24+ return [];
25+ }
26+ return node.children.flatMap((child) => collectText(child));
27+}
28+
29+function findTextNode(node: Node | null, content: string): Node | null {
30+ if (!node) {
31+ return null;
32+ }
33+ if (node.type === "text") {
34+ return node.content === content ? node : null;
35+ }
36+ if (node.type === "textinput") {
37+ return null;
38+ }
39+ for (const child of node.children) {
40+ const found = findTextNode(child, content);
41+ if (found) {
42+ return found;
43+ }
44+ }
45+ return null;
46+}
47+
48+describe("ui/conversation", () => {
49+ test("previewToolRenderLines keeps all lines in verbose mode", () => {
50+ const lines: ToolRenderLine[] = Array.from({ length: 25 }, (_, i) => ({
51+ kind: "text",
52+ text: `line ${i + 1}`,
53+ }));
54+
55+ const preview = previewToolRenderLines(lines, true, 20);
56+
57+ expect(preview).toEqual(lines);
58+ });
59+
60+ test("previewToolRenderLines shows first 20 lines plus a summary when verbose mode is off", () => {
61+ const lines: ToolRenderLine[] = Array.from({ length: 25 }, (_, i) => ({
62+ kind: "text",
63+ text: `line ${i + 1}`,
64+ }));
65+
66+ const preview = previewToolRenderLines(lines, false, 20);
67+
68+ expect(preview).toHaveLength(21);
69+ expect(preview.at(0)?.text).toBe("line 1");
70+ expect(preview.at(19)?.text).toBe("line 20");
71+ expect(preview.at(20)).toEqual({
72+ kind: "summary",
73+ text: "And 5 lines more",
74+ });
75+ });
76+
77+ test("renderToolResult uses themed accent colors for tool headers", () => {
78+ const theme: Theme = {
79+ ...DEFAULT_THEME,
80+ accentText: "color04",
81+ secondaryAccentText: "color05",
82+ };
83+
84+ const shellNode = renderToolResult(
85+ "shell",
86+ { command: "seq 1 3" },
87+ "1\n2\n3",
88+ false,
89+ { ...RENDER_OPTS, theme },
90+ );
91+ const shellHeader = findTextNode(shellNode, "$ seq 1 3");
92+ expect(shellHeader).not.toBeNull();
93+ if (!shellHeader || shellHeader.type !== "text") {
94+ throw new Error("Expected shell header to be a text node");
95+ }
96+ expect(shellHeader.props.fgColor).toBe(theme.accentText);
97+
98+ const pluginNode = renderToolResult("plugin-tool", {}, "ok", false, {
99+ ...RENDER_OPTS,
100+ theme,
101+ });
102+ const pluginHeader = findTextNode(pluginNode, "plugin-tool");
103+ expect(pluginHeader).not.toBeNull();
104+ if (!pluginHeader || pluginHeader.type !== "text") {
105+ throw new Error("Expected plugin header to be a text node");
106+ }
107+ expect(pluginHeader.props.fgColor).toBe(theme.secondaryAccentText);
108+ });
109+
110+ test("renderToolResult truncates shell output in non-verbose mode", () => {
111+ const output = Array.from({ length: 25 }, (_, i) => `line ${i + 1}`).join(
112+ "\n",
113+ );
114+
115+ const node = renderToolResult(
116+ "shell",
117+ { command: "seq 1 25" },
118+ output,
119+ false,
120+ RENDER_OPTS,
121+ );
122+ const text = collectText(node);
123+
124+ expect(text).toContain("$ seq 1 25");
125+ expect(text).toContain("line 1");
126+ expect(text).toContain("line 20");
127+ expect(text).toContain("And 5 lines more");
128+ expect(text).not.toContain("line 21");
129+ });
130+
131+ test("renderToolResult shows full edit diffs in verbose mode", () => {
132+ const oldText = Array.from({ length: 25 }, (_, i) => `old ${i + 1}`).join(
133+ "\n",
134+ );
135+ const newText = Array.from({ length: 25 }, (_, i) => `new ${i + 1}`).join(
136+ "\n",
137+ );
138+
139+ const node = renderToolResult(
140+ "edit",
141+ { path: "src/file.ts", oldText, newText },
142+ "Edited src/file.ts",
143+ false,
144+ { ...RENDER_OPTS, verbose: true },
145+ );
146+ const text = collectText(node);
147+
148+ expect(text).toContain("+new 25");
149+ expect(text.some((line) => /^And \d+ lines more$/.test(line))).toBe(false);
150+ });
151+});
src/ui.help.test.ts+24−0
@@ -0,0 +1,24 @@
1+import { describe, expect, test } from "bun:test";
2+import { DEFAULT_SHOW_REASONING } from "./settings.ts";
3+import { buildHelpText, type HelpRenderState } from "./ui/help.ts";
4+
5+describe("ui/help", () => {
6+ test("buildHelpText includes current reasoning and verbose state", () => {
7+ const helpState: HelpRenderState = {
8+ providers: new Map(),
9+ model: null,
10+ agentsMd: [],
11+ skills: [],
12+ plugins: [],
13+ showReasoning: DEFAULT_SHOW_REASONING,
14+ verbose: false,
15+ };
16+
17+ const text = buildHelpText(helpState);
18+
19+ expect(text).toContain(
20+ `/reasoning Toggle thinking display (currently ${DEFAULT_SHOW_REASONING ? "on" : "off"})`,
21+ );
22+ expect(text).toContain("/verbose Toggle full output (currently off)");
23+ });
24+});
src/ui.input.test.ts+71−0
@@ -0,0 +1,71 @@
1+import { afterEach, describe, expect, test } from "bun:test";
2+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import { DEFAULT_THEME } from "./theme.ts";
6+import {
7+ autocompleteInputPath,
8+ type InputController,
9+ renderInputArea,
10+} from "./ui/input.ts";
11+
12+const tempDirs: string[] = [];
13+
14+function createTempDir(): string {
15+ const dir = mkdtempSync(join(tmpdir(), "mini-coder-ui-input-test-"));
16+ tempDirs.push(dir);
17+ return dir;
18+}
19+
20+afterEach(() => {
21+ for (const dir of tempDirs.splice(0)) {
22+ rmSync(dir, { recursive: true, force: true });
23+ }
24+});
25+
26+describe("ui/input", () => {
27+ test("renderInputArea returns a direct TextInput with the provided state and handlers", () => {
28+ const controller: InputController = {
29+ onChange: () => {},
30+ onFocus: () => {},
31+ onBlur: () => {},
32+ onKeyPress: () => undefined,
33+ };
34+
35+ const input = renderInputArea(DEFAULT_THEME, controller, "draft", true);
36+
37+ expect(input.type).toBe("textinput");
38+ if (input.type !== "textinput") {
39+ throw new Error("Expected a TextInput node");
40+ }
41+
42+ expect(input.props.value).toBe("draft");
43+ expect(input.props.focused).toBe(true);
44+ expect(input.props.placeholder?.props.fgColor).toBe(
45+ DEFAULT_THEME.mutedText,
46+ );
47+ expect(input.props.padding).toEqual({ x: 1 });
48+ expect(input.props.minHeight).toBe(2);
49+ expect(input.props.maxHeight).toBe(10);
50+ expect(input.props.onChange).toBe(controller.onChange);
51+ expect(input.props.onFocus).toBe(controller.onFocus);
52+ expect(input.props.onBlur).toBe(controller.onBlur);
53+ expect(input.props.onKeyPress).toBe(controller.onKeyPress);
54+ });
55+
56+ test("autocompleteInputPath completes the last file path token", () => {
57+ const cwd = createTempDir();
58+ mkdirSync(join(cwd, "src"), { recursive: true });
59+ writeFileSync(join(cwd, "src", "ui.ts"), "", "utf-8");
60+
61+ expect(autocompleteInputPath("inspect src/u", cwd)).toBe(
62+ "inspect src/ui.ts",
63+ );
64+ });
65+
66+ test("autocompleteInputPath returns null when no completion is available", () => {
67+ const cwd = createTempDir();
68+
69+ expect(autocompleteInputPath("inspect src/u", cwd)).toBeNull();
70+ });
71+});
src/ui.overlay.test.ts+49−0
@@ -0,0 +1,49 @@
1+import { describe, expect, test } from "bun:test";
2+import { Select } from "@cel-tui/components";
3+import { DEFAULT_THEME } from "./theme.ts";
4+import {
5+ type ActiveOverlay,
6+ OVERLAY_MAX_VISIBLE,
7+ OVERLAY_PADDING_X,
8+ renderOverlay,
9+} from "./ui/overlay.ts";
10+
11+describe("ui/overlay", () => {
12+ test("renderOverlay centers a titled modal with theme background", () => {
13+ const overlay: ActiveOverlay = {
14+ title: "Commands",
15+ select: Select({
16+ items: [{ label: "overlay body", value: "body", filterText: "body" }],
17+ maxVisible: 1,
18+ placeholder: "type to filter...",
19+ focused: true,
20+ highlightColor: DEFAULT_THEME.accentText,
21+ onSelect: () => {},
22+ onBlur: () => {},
23+ }),
24+ };
25+
26+ const node = renderOverlay(DEFAULT_THEME, overlay);
27+
28+ expect(node.type).toBe("vstack");
29+ if (node.type !== "vstack") {
30+ throw new Error("Expected overlay root to be a VStack");
31+ }
32+
33+ expect(node.props.height).toBe("100%");
34+ expect(node.props.justifyContent).toBe("center");
35+ expect(node.props.padding).toEqual({ x: OVERLAY_PADDING_X });
36+
37+ const modal = node.children[0];
38+ expect(modal?.type).toBe("vstack");
39+ if (!modal || modal.type !== "vstack") {
40+ throw new Error("Expected overlay modal to be a VStack");
41+ }
42+
43+ expect(modal.props.height).toBe(OVERLAY_MAX_VISIBLE + 3);
44+ expect(modal.props.bgColor).toBe(DEFAULT_THEME.overlayBg);
45+ expect(modal.props.padding).toEqual({ x: 1 });
46+ expect(modal.children[0]?.type).toBe("text");
47+ expect(modal.children[1]?.type).toBe("vstack");
48+ });
49+});
src/ui.ts+86−1857
@@ -9,82 +9,62 @@
99 */
1010
1111 import { exec } from "node:child_process";
12-import { readdirSync, readFileSync } from "node:fs";
13-import { homedir, platform } from "node:os";
14-import { isAbsolute, join } from "node:path";
15-import type { SelectInstance } from "@cel-tui/components";
16-import { Markdown, Select, Spacer } from "@cel-tui/components";
17-import {
18- cel,
19- HStack,
20- ProcessTerminal,
21- Text,
22- TextInput,
23- VStack,
24-} from "@cel-tui/core";
12+import { platform } from "node:os";
13+import { cel, HStack, ProcessTerminal, Text, VStack } from "@cel-tui/core";
2514 import type { Node } from "@cel-tui/types";
26-import type {
27- AssistantMessage,
28- Message,
29- TextContent,
30- ThinkingLevel,
31- ToolCall,
32- UserMessage,
33-} from "@mariozechner/pi-ai";
34-import type { OAuthProviderInterface } from "@mariozechner/pi-ai/oauth";
35-import { getOAuthProviders } from "@mariozechner/pi-ai/oauth";
36-import { structuredPatch } from "diff";
37-import type { AgentEvent } from "./agent.ts";
38-import { runAgentLoop } from "./agent.ts";
39-import { getGitState } from "./git.ts";
4015 import type { AppState } from "./index.ts";
41-import {
42- buildPrompt,
43- buildToolList,
44- getAvailableModels,
45- MAX_PROMPT_HISTORY,
46- MAX_SESSIONS_PER_CWD,
47- saveOAuthCredentials,
48- shutdown,
49-} from "./index.ts";
50-import { COMMANDS, parseInput } from "./input.ts";
16+import { MAX_SESSIONS_PER_CWD, shutdown } from "./index.ts";
5117 import {
5218 appendMessage,
53- appendPromptHistory,
54- computeStats,
5519 createSession,
5620 createUiMessage,
57- filterModelMessages,
58- forkSession,
59- getAssistantUsage,
60- listPromptHistory,
61- listSessions,
62- loadMessages,
63- truncatePromptHistory,
6421 truncateSessions,
65- type UiMessage,
66- undoLastTurn,
6722 } from "./session.ts";
68-import { updateSettings } from "./settings.ts";
6923 import type { Theme } from "./theme.ts";
70-import { executeReadImage } from "./tools.ts";
24+import {
25+ createUiAgentController,
26+ getStreamingConversationState,
27+ resetUiAgentState,
28+} from "./ui/agent.ts";
29+import { createCommandController } from "./ui/commands.ts";
30+import { buildConversationLogNodes } from "./ui/conversation.ts";
31+import type { InputController } from "./ui/input.ts";
32+import {
33+ autocompleteInputPath,
34+ renderInputArea as renderInputAreaNode,
35+} from "./ui/input.ts";
36+import { type ActiveOverlay, renderOverlay } from "./ui/overlay.ts";
37+import { renderStatusBar } from "./ui/status.ts";
38+
39+export {
40+ applyEffortSelection,
41+ applyModelSelection,
42+ formatPromptHistoryPreview,
43+ formatRelativeDate,
44+} from "./ui/commands.ts";
45+export {
46+ type ConversationRenderOpts,
47+ type PendingToolCall,
48+ previewToolRenderLines,
49+ renderAssistantMessage,
50+ renderToolResult,
51+ type ToolRenderLine,
52+ type ToolRenderLineKind,
53+} from "./ui/conversation.ts";
54+export { buildHelpText, type HelpRenderState } from "./ui/help.ts";
55+export type { InputController } from "./ui/input.ts";
56+export { renderStatusBar } from "./ui/status.ts";
7157
7258 // ---------------------------------------------------------------------------
7359 // Constants
7460 // ---------------------------------------------------------------------------
7561
76-/** Max body lines shown for tool results when verbose mode is off. */
77-const UI_TOOL_PREVIEW_LINES = 20;
78-
7962 /** Divider animation speed (ms per frame). */
8063 const DIVIDER_FRAME_MS = 60;
8164
8265 /** Width of the bright pulse segment in the animated divider. */
8366 const PULSE_WIDTH = 5;
8467
85-/** Conservative fixed estimate for an image block's token footprint. */
86-const ESTIMATED_IMAGE_TOKENS = 1_200;
87-
8868 // ---------------------------------------------------------------------------
8969 // UI state (module-scoped, not in AppState)
9070 // ---------------------------------------------------------------------------
@@ -107,93 +87,12 @@ let dividerTick = 0;
10787 /** Divider animation timer handle. */
10888 let dividerTimer: ReturnType<typeof setInterval> | null = null;
10989
110-/** Streaming assistant content for the current response. */
111-let streamingContent: AssistantMessage["content"] = [];
112-
113-/** Whether we are currently streaming a response. */
114-let isStreaming = false;
115-
116-/**
117- * A tool call observed during streaming, before it lands in history.
118- *
119- * Stores the tool name and arguments from `tool_start`, progressive
120- * text updates from `tool_delta`, and the final result from `tool_end`.
121- */
122-/** A pending tool call shown in the streaming tail. */
123-export interface PendingToolCall {
124- /** Tool call id from the assistant message. */
125- toolCallId: string;
126- /** Tool name. */
127- name: string;
128- /** Tool call arguments. */
129- args: Record<string, unknown>;
130- /** Progressive text output captured so far. */
131- resultText: string;
132- /** Whether the tool result was an error. */
133- isError: boolean;
134- /** Whether the tool has finished. */
135- done: boolean;
136-}
137-
138-/** Render options shared by completed and in-progress assistant content. */
139-export interface ConversationRenderOpts {
140- /** Whether reasoning blocks are visible. */
141- showReasoning: boolean;
142- /** Whether tool output should be truncated in the UI. */
143- verbose: boolean;
144- /** Active UI theme. */
145- theme: Theme;
146-}
147-
148-/** Display-only assistant state used while a response is still streaming. */
149-interface AssistantRenderState {
150- /** Assistant content blocks accumulated so far. */
151- content: AssistantMessage["content"];
152- /** Tool calls observed in the current streaming turn. */
153- pendingToolCalls?: PendingToolCall[];
154- /** Optional error text appended below the assistant content. */
155- errorMessage?: string;
156-}
157-
158-/** Semantic line kinds used when rendering tool output in the log. */
159-export type ToolRenderLineKind =
160- | "command"
161- | "path"
162- | "toolName"
163- | "text"
164- | "diffAdded"
165- | "diffRemoved"
166- | "summary"
167- | "error";
168-
169-/** A single logical line in a rendered tool block. */
170-export interface ToolRenderLine {
171- /** Semantic line kind for styling. */
172- kind: ToolRenderLineKind;
173- /** Text content for this line. */
174- text: string;
175-}
176-
177-/** Tool calls collected during the current streaming turn. */
178-let pendingToolCalls: PendingToolCall[] = [];
179-
18090 // ---------------------------------------------------------------------------
18191 // Overlay state
18292 // ---------------------------------------------------------------------------
18393
184-/** Max visible items in the overlay Select. */
185-const OVERLAY_MAX_VISIBLE = 15;
186-
187-/** Horizontal padding around the overlay modal. */
188-const OVERLAY_PADDING_X = 4;
189-
19094 /** Active overlay for interactive commands (/model, /effort, etc.). */
191-let activeOverlay: {
192- /** The Select component instance. */
193- select: SelectInstance;
194- /** Title displayed above the Select. */
195- title: string;
196-} | null = null;
95+let activeOverlay: ActiveOverlay | null = null;
19796
19897 /**
19998 * Reset all module-scoped UI state.
@@ -207,9 +106,7 @@ export function resetUiState(): void {
207106 inputFocused = true;
208107 dividerTick = 0;
209108 stopDividerAnimation();
210- streamingContent = [];
211- isStreaming = false;
212- pendingToolCalls = [];
109+ resetUiAgentState();
213110 activeOverlay = null;
214111 }
215112
@@ -277,700 +174,26 @@ function renderDivider(state: AppState, width: number): Node {
277174 return HStack({ height: 1 }, segments);
278175 }
279176
280-// ---------------------------------------------------------------------------
281-// Status bar formatting
282-// ---------------------------------------------------------------------------
283-
284-/** Abbreviate a path with ~ for the home directory. */
285-function abbreviatePath(p: string): string {
286- const home = homedir();
287- if (p === home) return "~";
288- if (p.startsWith(`${home}/`)) return `~${p.slice(home.length)}`;
289- return p;
290-}
291-
292-/** Format a token count with human-friendly units (1.2k, 45k, 1.2M). */
293-function formatTokens(n: number): string {
294- if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
295- if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
296- return String(n);
297-}
298-
299-/** Format a token capacity, trimming unnecessary trailing `.0`. */
300-function formatTokenCapacity(n: number): string {
301- return formatTokens(n).replace(/\.0([kM])$/, "$1");
302-}
303-
304-/** Format a dollar cost. */
305-function formatCost(cost: number): string {
306- return `$${cost.toFixed(2)}`;
307-}
308-
309-/** Format the effort level for display. */
310-function formatEffort(effort: string): string {
311- const map: Record<string, string> = {
312- minimal: "min",
313- low: "low",
314- medium: "med",
315- high: "high",
316- xhigh: "xhigh",
317- };
318- return map[effort] ?? effort;
319-}
320-
321-/** Format git status for the status bar right side. */
322-function formatGitStatus(state: AppState): string {
323- if (!state.git) return "";
324- const parts: string[] = [state.git.branch];
325- if (state.git.staged > 0) parts.push(`+${state.git.staged}`);
326- if (state.git.modified > 0) parts.push(`~${state.git.modified}`);
327- if (state.git.untracked > 0) parts.push(`?${state.git.untracked}`);
328- if (state.git.ahead > 0) parts.push(`▲ ${state.git.ahead}`);
329- if (state.git.behind > 0) parts.push(`▼ ${state.git.behind}`);
330- return parts.join(" ");
331-}
332-
333-/** Format model info for the status bar left side. */
334-function formatModelInfo(state: AppState): string {
335- if (!state.model) return "no model";
336- return `${state.model.provider}/${state.model.id} · ${formatEffort(state.effort)}`;
337-}
338-
339-/** Calculate context tokens from assistant usage, falling back when `totalTokens` is zero. */
340-function calculateUsageTokens(usage: AssistantMessage["usage"]): number {
341- return (
342- usage.totalTokens ||
343- usage.input + usage.output + usage.cacheRead + usage.cacheWrite
344- );
345-}
346-
347-/** Estimate token usage from a character count using a conservative chars/4 heuristic. */
348-function estimateCharacterTokens(charCount: number): number {
349- return Math.ceil(charCount / 4);
350-}
351-
352-/** Estimate token usage for a model-visible message. */
353-function estimateMessageTokens(message: Message): number {
354- switch (message.role) {
355- case "user": {
356- if (typeof message.content === "string") {
357- return estimateCharacterTokens(message.content.length);
358- }
359-
360- let chars = 0;
361- let imageTokens = 0;
362- for (const block of message.content) {
363- if (block.type === "text") {
364- chars += block.text.length;
365- } else if (block.type === "image") {
366- imageTokens += ESTIMATED_IMAGE_TOKENS;
367- }
368- }
369- return estimateCharacterTokens(chars) + imageTokens;
370- }
371- case "assistant": {
372- let chars = 0;
373- for (const block of message.content) {
374- if (block.type === "text") {
375- chars += block.text.length;
376- } else if (block.type === "thinking") {
377- chars += block.thinking.length;
378- } else if (block.type === "toolCall") {
379- chars += block.name.length + JSON.stringify(block.arguments).length;
380- }
381- }
382- return estimateCharacterTokens(chars);
383- }
384- case "toolResult": {
385- let chars = 0;
386- let imageTokens = 0;
387- for (const block of message.content) {
388- if (block.type === "text") {
389- chars += block.text.length;
390- } else if (block.type === "image") {
391- imageTokens += ESTIMATED_IMAGE_TOKENS;
392- }
393- }
394- return estimateCharacterTokens(chars) + imageTokens;
395- }
396- }
397-}
398-
399-/** Find the latest assistant usage that can anchor context estimation. */
400-function getLatestValidAssistantUsage(
401- messages: readonly Message[],
402-): { index: number; tokens: number } | null {
403- for (let i = messages.length - 1; i >= 0; i--) {
404- const message = messages[i];
405- if (
406- message?.role === "assistant" &&
407- message.stopReason !== "aborted" &&
408- message.stopReason !== "error"
409- ) {
410- const usage = getAssistantUsage(message);
411- if (!usage) {
412- continue;
413- }
414- return {
415- index: i,
416- tokens: calculateUsageTokens(usage),
417- };
418- }
419- }
420- return null;
421-}
422-
423-/** Estimate the current model-visible context size for the next request. */
424-function estimateCurrentContextTokens(state: AppState): number {
425- const messages = filterModelMessages(state.messages);
426- const latestUsage = getLatestValidAssistantUsage(messages);
427-
428- if (!latestUsage) {
429- return messages.reduce((total, message) => {
430- return total + estimateMessageTokens(message);
431- }, 0);
432- }
433-
434- let total = latestUsage.tokens;
435- for (let i = latestUsage.index + 1; i < messages.length; i++) {
436- total += estimateMessageTokens(messages[i]!);
437- }
438- return total;
439-}
440-
441-/** Format cumulative session totals plus estimated current context usage for the status bar. */
442-function formatUsage(state: AppState): string {
443- if (!state.model) return "";
444- const inp = formatTokens(state.stats.totalInput);
445- const out = formatTokens(state.stats.totalOutput);
446- const contextTokens = estimateCurrentContextTokens(state);
447- const ctxPct =
448- state.model.contextWindow > 0
449- ? (contextTokens / state.model.contextWindow) * 100
450- : 0;
451- const ctxWindow = formatTokenCapacity(state.model.contextWindow);
452- return `in:${inp} out:${out} · ${ctxPct.toFixed(1)}%/${ctxWindow} · ${formatCost(state.stats.totalCost)}`;
453-}
454-
Cut short: this commit's diff is over 1000 lines.
src/ui/agent.ts+381−0
Cut short: this commit's diff is over 1000 lines.
src/ui/commands.ts+545−0
Cut short: this commit's diff is over 1000 lines.
src/ui/conversation.ts+638−0
Cut short: this commit's diff is over 1000 lines.
src/ui/help.ts+119−0
Cut short: this commit's diff is over 1000 lines.
src/ui/input.ts+138−0
Cut short: this commit's diff is over 1000 lines.
src/ui/overlay.ts+59−0
Cut short: this commit's diff is over 1000 lines.
src/ui/status.ts+250−0
Cut short: this commit's diff is over 1000 lines.