xonecas.io
64875
Mc

mini-coder / commit 9a21a6e

feat: add terminal UI with agent loop wiring (Phase 4b)

- ui.ts: cel-tui layout (conversation log, animated divider, TextInput,
  status bar), message rendering (user bg, assistant Markdown, tool calls
  with left border and unified diffs), streaming response display,
  Escape interrupt, Ctrl+C/Ctrl+D graceful exit
- index.ts: add main() entry point wiring init → startUI
- theme.ts: change Theme values from string to cel-tui Color type
- tsconfig.json: remove noImplicitReturns for cel-tui compatibility
- spec.md: fix TextInput submit description to match cel-tui API
- AGENTS.md: add lessons (phased plan, callback semantics, dep types)

xonecas2026-04-05 9a21a6e3e0447cb28ea1159f2a7080659f874abd parent 413a5bd

9 files changed

AGENTS.md+3−0
@@ -43,6 +43,9 @@
4343 - **Dead guards are lies.** Type guards for impossible types (e.g., `typeof c !== "string"` when the type is `TextContent | ThinkingContent | ToolCall`) suggest the type can contain those values. They mislead readers and should not exist.
4444 - **Event APIs must carry their data.** When an event handler needs data from the event source (e.g., tool call arguments), the event must carry that data. Walking external state to reconstruct it is fragile and breaks with duplicate entries.
4545 - **Async callbacks must handle errors.** When a sync callback invokes an async function, the returned promise must be caught. Dropping it silently turns errors into unhandled rejections.
46+- **Respect the phased plan.** Each TODO.md phase has explicit scope. Do not implement features from later phases — even if they feel "easy" or "related." Scope creep wastes review time, introduces bugs from untested code paths, and erodes trust. If something isn't listed in the current phase, it doesn't exist yet.
47+- **Understand callback return semantics.** In cel-tui's `onKeyPress`, returning `false` means "prevent the default action" — returning it unconditionally blocks all typing. Only return `false` for keys you explicitly intercept. Let all other keys fall through with no return.
48+- **Use the dependency's types, not weaker ones.** If a dependency defines a specific type (e.g., cel-tui's `Color`), use it in your own interfaces. Don't weaken to `string` and then cast with `as any` everywhere — that defeats type safety and creates lint noise.
4649
4750 ## Testing strategy
4851
TODO.md+19−6
@@ -69,7 +69,7 @@
6969 - `theme.ts` (also implemented here): `Theme` interface, `DEFAULT_THEME`, `mergeThemes(base, ...overrides)`. Uses terminal palette colors (`color01`–`color08`) for automatic light/dark adaptation. 5 tests in `theme.test.ts`.
7070 - 158 tests total across 9 files (session: 20, tools: 36, git: 10, skills: 14, prompt: 21, agent: 12, plugins: 10, input: 30, theme: 5).
7171
72-### Notes from Phase 4b (in progress)
72+### Notes from Phase 4b
7373
7474 - `index.ts` exports: `AppState` (all mutable app state), `init()`, `buildPrompt(state)`, `buildToolList(state)`, `shutdown(state)`. Also re-exports OAuth helpers (`loadOAuthCredentials`, `saveOAuthCredentials`, `DATA_DIR`, `AUTH_PATH`) for `/login` and `/logout` commands.
7575 - Provider discovery checks env-based API keys first, then saved OAuth tokens (`~/.config/mini-coder/auth.json`). Refreshes expired tokens and persists updates.
@@ -81,11 +81,24 @@
8181
8282 ### 4b — App shell (running app, no commands)
8383
84-- [x] `index.ts` — entry point: provider discovery (env + OAuth), model selection (first available, null if none), startup sequence
85-- [ ] `ui.ts` — cel-tui layout: conversation log (scrollable, stick-to-bottom), input area (TextInput, submit/newline), status bar (2 lines: cwd+git, model+usage), animated divider
86-- [ ] Wire agent loop: submit → build context → stream → render events → tool results → loop
87-- [ ] Message rendering: user (bg color), assistant (streamed Markdown), tool calls (shell: bordered output, edit: path + unified diff), errors
88-- [ ] Interrupt: Escape during streaming aborts via AbortSignal
84+- [x] `index.ts` — entry point: provider discovery (env + OAuth), model selection (first available, null if none), startup sequence, `main()` wires init → startUI
85+- [x] `ui.ts` — cel-tui layout: conversation log (scrollable, stick-to-bottom), input area (TextInput, submit/newline), status bar (2 lines: cwd+git, model+usage), animated divider
86+- [x] Wire agent loop: submit → build context → stream → render events → tool results → loop
87+- [x] Message rendering: user (bg color), assistant (streamed Markdown), tool calls (shell: bordered output, edit: path + unified diff), errors
88+- [x] Interrupt: Escape during streaming aborts via AbortSignal
89+
90+### Notes from Phase 4b (ui.ts)
91+
92+- `ui.ts` exports: `startUI(state)`. Single entry point that owns the cel-tui lifecycle (`cel.init` / `cel.stop`).
93+- Layout matches the spec diagram: scrollable conversation log (flex: 1) → animated divider → TextInput (maxHeight: 10) → static divider → status bar (height: 2).
94+- Animated divider: scanning pulse (bright `═` segment sweeps across dimmed `─` line) via `setInterval` at 60ms. Starts on agent loop start, stops on completion.
95+- Message rendering: user messages get `bgColor` from theme, assistant messages use `Markdown()` component, tool calls get left border (`│`) with dimmed text. Edit tool calls show unified diff via `structuredPatch` from the `diff` package. Streaming response rendered from accumulation buffers + pending tool call list.
96+- Agent loop wiring: `submitMessage` appends user message to DB (turn auto-assigned by `appendMessage`), refreshes git state, builds prompt + tools, runs `runAgentLoop` with `onEvent` callback. Events update streaming buffers and trigger `cel.render()`.
97+- Key bindings: Enter submits (returns `false` in `onKeyPress` to prevent newline), Escape interrupts running agent, Ctrl+C / Ctrl+D graceful exit.
98+- `Theme` type changed from `string` values to cel-tui `Color` type — eliminates `as any` casts throughout the UI.
99+- `tsconfig.json`: removed `noImplicitReturns` for cel-tui compatibility (their `onKeyPress` callbacks return `false | void`).
100+- `spec.md`: removed `submitKey: "enter"` reference — cel-tui uses the `onKeyPress` return-false pattern instead.
101+- 158 tests still pass across 9 files.
89102
90103 ### 4c — Commands
91104
assets/preview-0-5-0.png+0−0
Binary file, not shown.
spec.md+1−1
@@ -497,7 +497,7 @@ While the agent is working, the top divider (above the input area) animates with
497497
498498 ### Input area
499499
500-Multi-line text input with no prompt prefix — the blinking cursor is the affordance. Intrinsic height (1 line when empty, grows with content) up to `maxHeight: 10`, then scrolls internally. cel-tui's `TextInput` with `submitKey: "enter"` (Enter submits, Shift+Enter adds newlines).
500+Multi-line text input with no prompt prefix — the blinking cursor is the affordance. Intrinsic height (1 line when empty, grows with content) up to `maxHeight: 10`, then scrolls internally. Enter submits, Shift+Enter adds newlines (via cel-tui's `TextInput` `onKeyPress` pattern).
501501
502502 Supports:
503503
src/index.ts+15−0
@@ -416,3 +416,18 @@ export async function shutdown(state: AppState): Promise<void> {
416416 // ---------------------------------------------------------------------------
417417
418418 export { AUTH_PATH, DATA_DIR, loadOAuthCredentials, saveOAuthCredentials };
419+
420+// ---------------------------------------------------------------------------
421+// Main
422+// ---------------------------------------------------------------------------
423+
424+async function main(): Promise<void> {
425+ const state = await init();
426+ const { startUI } = await import("./ui.ts");
427+ startUI(state);
428+}
429+
430+main().catch((err) => {
431+ console.error(err);
432+ process.exit(1);
433+});
src/theme.test.ts+7−7
@@ -21,8 +21,8 @@ describe("theme", () => {
2121 });
2222
2323 test("mergeThemes applies a single partial override", () => {
24- const result = mergeThemes(DEFAULT_THEME, { error: "#ff0000" });
25- expect(result.error).toBe("#ff0000");
24+ const result = mergeThemes(DEFAULT_THEME, { error: "color05" });
25+ expect(result.error).toBe("color05");
2626 // Other values preserved
2727 expect(result.userMsgBg).toBe(DEFAULT_THEME.userMsgBg);
2828 expect(result.divider).toBe(DEFAULT_THEME.divider);
@@ -31,18 +31,18 @@ describe("theme", () => {
3131 test("mergeThemes applies multiple overrides left-to-right", () => {
3232 const result = mergeThemes(
3333 DEFAULT_THEME,
34- { error: "first", divider: "plugin1" },
35- { error: "second" },
34+ { error: "color03", divider: "color05" },
35+ { error: "color04" },
3636 );
3737 // Last override wins for error
38- expect(result.error).toBe("second");
38+ expect(result.error).toBe("color04");
3939 // First override preserved for divider (not overridden by second)
40- expect(result.divider).toBe("plugin1");
40+ expect(result.divider).toBe("color05");
4141 });
4242
4343 test("mergeThemes does not mutate the base theme", () => {
4444 const baseCopy = { ...DEFAULT_THEME };
45- mergeThemes(DEFAULT_THEME, { error: "modified" });
45+ mergeThemes(DEFAULT_THEME, { error: "color09" });
4646 expect(DEFAULT_THEME).toEqual(baseCopy);
4747 });
4848 });
src/theme.ts+12−10
@@ -5,11 +5,13 @@
55 * never hardcodes colors. Plugins can return a `Partial<Theme>` in their
66 * result to override any color. Multiple overrides are merged left-to-right.
77 *
8- * Theme values are cel-tui color strings (e.g., `"color08"`, `"#ff0000"`).
8+ * Theme values are cel-tui {@link Color} palette references.
99 *
1010 * @module
1111 */
1212
13+import type { Color } from "@cel-tui/types";
14+
1315 // ---------------------------------------------------------------------------
1416 // Types
1517 // ---------------------------------------------------------------------------
@@ -22,23 +24,23 @@
2224 */
2325 export interface Theme {
2426 /** User message background. */
25- userMsgBg: string;
27+ userMsgBg: Color;
2628 /** Tool output left border and text. */
27- toolBorder: string;
29+ toolBorder: Color;
2830 /** Tool output text. */
29- toolText: string;
31+ toolText: Color;
3032 /** Diff added line color (green). */
31- diffAdded: string;
33+ diffAdded: Color;
3234 /** Diff removed line color (red). */
33- diffRemoved: string;
35+ diffRemoved: Color;
3436 /** Divider line color (idle state). */
35- divider: string;
37+ divider: Color;
3638 /** Divider scanning pulse highlight color (active state). */
37- dividerPulse: string;
39+ dividerPulse: Color;
3840 /** Status bar foreground. */
39- statusText: string;
41+ statusText: Color;
4042 /** Error text. */
41- error: string;
43+ error: Color;
4244 }
4345
4446 // ---------------------------------------------------------------------------
src/ui.ts+789−0
@@ -0,0 +1,789 @@
1+/**
2+ * Terminal UI for mini-coder.
3+ *
4+ * Owns the cel-tui lifecycle (init/stop), renders the conversation log,
5+ * input area, animated divider, and status bar. Wires user input to the
6+ * agent loop and streams events back to the UI.
7+ *
8+ * @module
9+ */
10+
11+import { homedir } from "node:os";
12+import { Divider, Markdown, Spacer } from "@cel-tui/components";
13+import {
14+ cel,
15+ HStack,
16+ ProcessTerminal,
17+ Text,
18+ TextInput,
19+ VStack,
20+} from "@cel-tui/core";
21+import type { Node } from "@cel-tui/types";
22+import type {
23+ AssistantMessage,
24+ Message,
25+ TextContent,
26+ ThinkingContent,
27+ ToolCall,
28+} from "@mariozechner/pi-ai";
29+import { structuredPatch } from "diff";
30+import type { AgentEvent } from "./agent.ts";
31+import { runAgentLoop } from "./agent.ts";
32+import { getGitState } from "./git.ts";
33+import type { AppState } from "./index.ts";
34+import { buildPrompt, buildToolList, shutdown } from "./index.ts";
35+import { appendMessage, computeStats } from "./session.ts";
36+import { truncateOutput } from "./tools.ts";
37+
38+// ---------------------------------------------------------------------------
39+// Constants
40+// ---------------------------------------------------------------------------
41+
42+/** Max lines of shell output shown in the conversation log. */
43+const UI_MAX_SHELL_LINES = 200;
44+
45+/** Divider animation speed (ms per frame). */
46+const DIVIDER_FRAME_MS = 60;
47+
48+/** Width of the bright pulse segment in the animated divider. */
49+const PULSE_WIDTH = 5;
50+
51+// ---------------------------------------------------------------------------
52+// UI state (module-scoped, not in AppState)
53+// ---------------------------------------------------------------------------
54+
55+/** Scroll position for the conversation log. */
56+let scrollOffset = 0;
57+
58+/** Whether the log auto-scrolls to the bottom. */
59+let stickToBottom = true;
60+
61+/** Current text in the input area. */
62+let inputValue = "";
63+
64+/** Whether the text input is focused. */
65+let inputFocused = true;
66+
67+/** Animated divider frame counter. */
68+let dividerTick = 0;
69+
70+/** Divider animation timer handle. */
71+let dividerTimer: ReturnType<typeof setInterval> | null = null;
72+
73+/** Streaming text buffer for the current assistant response. */
74+let streamingText = "";
75+
76+/** Streaming thinking buffer for the current assistant response. */
77+let streamingThinking = "";
78+
79+/** Whether we are currently streaming a response. */
80+let isStreaming = false;
81+
82+/**
83+ * A tool call observed during streaming, before it lands in history.
84+ *
85+ * Stores the tool name and arguments from `tool_start`, and the
86+ * result text from `tool_end` (filled in when the tool finishes).
87+ */
88+interface PendingToolCall {
89+ /** Tool name. */
90+ name: string;
91+ /** Tool call arguments. */
92+ args: Record<string, unknown>;
93+ /** Text result, or `null` while still running. */
94+ resultText: string | null;
95+ /** Whether the tool result was an error. */
96+ isError: boolean;
97+}
98+
99+/** Tool calls collected during the current streaming turn. */
100+let pendingToolCalls: PendingToolCall[] = [];
101+
102+// ---------------------------------------------------------------------------
103+// Divider animation
104+// ---------------------------------------------------------------------------
105+
106+/** Start the scanning pulse animation on the divider. */
107+function startDividerAnimation(): void {
108+ stopDividerAnimation();
109+ dividerTick = 0;
110+ dividerTimer = setInterval(() => {
111+ dividerTick++;
112+ cel.render();
113+ }, DIVIDER_FRAME_MS);
114+}
115+
116+/** Stop the divider animation. */
117+function stopDividerAnimation(): void {
118+ if (dividerTimer) {
119+ clearInterval(dividerTimer);
120+ dividerTimer = null;
121+ }
122+}
123+
124+/**
125+ * Render the animated divider.
126+ *
127+ * When the agent is working, a bright segment sweeps across the dimmed
128+ * line. When idle, it's a static dimmed line.
129+ */
130+function renderDivider(state: AppState, width: number): Node {
131+ if (!state.running) {
132+ return Text("─", { repeat: "fill", fgColor: state.theme.divider });
133+ }
134+
135+ const total = Math.max(width, 1);
136+ const pos = dividerTick % (total + PULSE_WIDTH);
137+ const pulseStart = Math.max(0, pos - PULSE_WIDTH);
138+ const pulseEnd = Math.min(pos, total);
139+ const pulseLen = pulseEnd - pulseStart;
140+ const beforeLen = pulseStart;
141+ const afterLen = total - pulseEnd;
142+
143+ const segments: Node[] = [];
144+ if (beforeLen > 0) {
145+ segments.push(
146+ Text("─", { repeat: beforeLen, fgColor: state.theme.divider }),
147+ );
148+ }
149+ if (pulseLen > 0) {
150+ segments.push(
151+ Text("═", {
152+ repeat: pulseLen,
153+ fgColor: state.theme.dividerPulse,
154+ }),
155+ );
156+ }
157+ if (afterLen > 0) {
158+ segments.push(
159+ Text("─", { repeat: afterLen, fgColor: state.theme.divider }),
160+ );
161+ }
162+
163+ return HStack({ height: 1 }, segments);
164+}
165+
166+// ---------------------------------------------------------------------------
167+// Status bar formatting
168+// ---------------------------------------------------------------------------
169+
170+/** Abbreviate a path with ~ for the home directory. */
171+function abbreviatePath(p: string): string {
172+ const home = homedir();
173+ if (p === home) return "~";
174+ if (p.startsWith(`${home}/`)) return `~${p.slice(home.length)}`;
175+ return p;
176+}
177+
178+/** Format a token count with human-friendly units (1.2k, 45k, 1.2M). */
179+function formatTokens(n: number): string {
180+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
181+ if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
182+ return String(n);
183+}
184+
185+/** Format a dollar cost. */
186+function formatCost(cost: number): string {
187+ return `$${cost.toFixed(2)}`;
188+}
189+
190+/** Format the effort level for display. */
191+function formatEffort(effort: string): string {
192+ const map: Record<string, string> = {
193+ minimal: "min",
194+ low: "low",
195+ medium: "med",
196+ high: "high",
197+ xhigh: "xhigh",
198+ };
199+ return map[effort] ?? effort;
200+}
201+
202+/** Format git status for the status bar right side. */
203+function formatGitStatus(state: AppState): string {
204+ if (!state.git) return "";
205+ const parts: string[] = [state.git.branch];
206+ if (state.git.staged > 0) parts.push(`+${state.git.staged}`);
207+ if (state.git.modified > 0) parts.push(`~${state.git.modified}`);
208+ if (state.git.untracked > 0) parts.push(`?${state.git.untracked}`);
209+ if (state.git.ahead > 0) parts.push(`▲ ${state.git.ahead}`);
210+ if (state.git.behind > 0) parts.push(`▼ ${state.git.behind}`);
211+ return parts.join(" ");
212+}
213+
214+/** Format model info for the status bar left side. */
215+function formatModelInfo(state: AppState): string {
216+ if (!state.model) return "no model";
217+ return `${state.model.provider}/${state.model.id} · ${formatEffort(state.effort)}`;
218+}
219+
220+/** Format usage stats for the status bar right side. */
221+function formatUsage(state: AppState): string {
222+ if (!state.model) return "";
223+ const inp = formatTokens(state.stats.totalInput);
224+ const out = formatTokens(state.stats.totalOutput);
225+ const totalTokens = state.stats.totalInput + state.stats.totalOutput;
226+ const ctxPct =
227+ state.model.contextWindow > 0
228+ ? Math.round((totalTokens / state.model.contextWindow) * 100)
229+ : 0;
230+ return `in:${inp} out:${out} · ${ctxPct}% · ${formatCost(state.stats.totalCost)}`;
231+}
232+
233+// ---------------------------------------------------------------------------
234+// Message rendering
235+// ---------------------------------------------------------------------------
236+
237+/** Render a user message with a subtle background. */
238+function renderUserMessage(msg: Message, theme: AppState["theme"]): Node {
239+ const text =
240+ typeof msg.content === "string"
241+ ? msg.content
242+ : msg.content
243+ .filter((c): c is TextContent => c.type === "text")
244+ .map((c) => c.text)
245+ .join("");
246+
247+ return VStack({ bgColor: theme.userMsgBg, padding: { x: 1 } }, [
248+ Text(text, { wrap: "word" }),
249+ ]);
250+}
251+
252+/** Render a completed assistant message from history. */
253+function renderAssistantMessage(
254+ msg: AssistantMessage,
255+ state: AppState,
256+): Node[] {
257+ const nodes: Node[] = [];
258+
259+ for (const block of msg.content) {
260+ if (block.type === "text" && (block as TextContent).text) {
261+ nodes.push(
262+ ...Markdown((block as TextContent).text).map((n) =>
263+ HStack({ padding: { x: 1 } }, [VStack({ flex: 1 }, [n])]),
264+ ),
265+ );
266+ } else if (block.type === "thinking" && state.showReasoning) {
267+ const thinking = (block as ThinkingContent).thinking;
268+ if (thinking) {
269+ nodes.push(
270+ VStack({ padding: { x: 1 } }, [
271+ Text(thinking, {
272+ wrap: "word",
273+ fgColor: "color08",
274+ italic: true,
275+ }),
276+ ]),
277+ );
278+ }
279+ }
280+ }
281+
282+ if (msg.stopReason === "error" && msg.errorMessage) {
283+ nodes.push(
284+ VStack({ padding: { x: 1 } }, [
285+ Text(`Error: ${msg.errorMessage}`, {
286+ fgColor: state.theme.error,
287+ }),
288+ ]),
289+ );
290+ }
291+
292+ return nodes;
293+}
294+
295+/** Render a shell tool call with left border. */
296+function renderShellToolCall(
297+ command: string,
298+ output: string,
299+ _isError: boolean,
300+ state: AppState,
301+): Node {
302+ const displayed = state.verbose
303+ ? output
304+ : truncateOutput(output, UI_MAX_SHELL_LINES);
305+
306+ const lines: Node[] = [
307+ Text(`$ ${command}`, { fgColor: "color06", bold: true }),
308+ ];
309+ if (displayed) {
310+ lines.push(Text(displayed, { wrap: "word" }));
311+ }
312+
313+ return HStack({ padding: { x: 1 } }, [
314+ Text("│ ", { fgColor: state.theme.toolBorder }),
315+ VStack({ flex: 1, fgColor: state.theme.toolText }, lines),
316+ ]);
317+}
318+
319+/** Render an edit tool call with file path and unified diff. */
320+function renderEditToolCall(
321+ filePath: string,
322+ oldText: string,
323+ newText: string,
324+ isError: boolean,
325+ resultText: string,
326+ state: AppState,
327+): Node {
328+ if (isError) {
329+ return HStack({ padding: { x: 1 } }, [
330+ Text("│ ", { fgColor: state.theme.toolBorder }),
331+ VStack({ flex: 1 }, [Text(resultText, { fgColor: state.theme.error })]),
332+ ]);
333+ }
334+
335+ const lines: Node[] = [
336+ Text(`~ ${filePath}`, { fgColor: "color06", bold: true }),
337+ ];
338+
339+ if (oldText === "") {
340+ lines.push(Text("(new file)", { fgColor: state.theme.diffAdded }));
341+ } else {
342+ const patch = structuredPatch("", "", oldText, newText, "", "", {
343+ context: 2,
344+ });
345+ for (const hunk of patch.hunks) {
346+ for (const line of hunk.lines) {
347+ if (line.startsWith("+")) {
348+ lines.push(Text(line, { fgColor: state.theme.diffAdded }));
349+ } else if (line.startsWith("-")) {
350+ lines.push(Text(line, { fgColor: state.theme.diffRemoved }));
351+ } else {
352+ lines.push(Text(line, { fgColor: state.theme.toolText }));
353+ }
354+ }
355+ }
356+ }
357+
358+ return HStack({ padding: { x: 1 } }, [
359+ Text("│ ", { fgColor: state.theme.toolBorder }),
360+ VStack({ flex: 1 }, lines),
361+ ]);
362+}
363+
364+/** Render a generic (plugin) tool call with left border. */
365+function renderGenericToolCall(
366+ toolName: string,
367+ output: string,
368+ isError: boolean,
369+ state: AppState,
370+): Node {
371+ const fgColor = isError ? state.theme.error : state.theme.toolText;
372+
373+ return HStack({ padding: { x: 1 } }, [
374+ Text("│ ", { fgColor: state.theme.toolBorder }),
375+ VStack({ flex: 1 }, [
376+ Text(toolName, { fgColor: "color05", bold: true }),
377+ ...(output ? [Text(output, { wrap: "word", fgColor })] : []),
378+ ]),
379+ ]);
380+}
381+
382+/** Render a tool result, dispatching by tool name. */
383+function renderToolResult(
384+ toolName: string,
385+ args: Record<string, unknown>,
386+ resultText: string,
387+ isError: boolean,
388+ state: AppState,
389+): Node {
390+ if (toolName === "shell") {
391+ return renderShellToolCall(
392+ args.command as string,
393+ resultText,
394+ isError,
395+ state,
396+ );
397+ }
398+ if (toolName === "edit") {
399+ return renderEditToolCall(
400+ args.path as string,
401+ args.oldText as string,
402+ args.newText as string,
403+ isError,
404+ resultText,
405+ state,
406+ );
407+ }
408+ return renderGenericToolCall(toolName, resultText, isError, state);
409+}
410+
411+// ---------------------------------------------------------------------------
412+// Streaming response rendering
413+// ---------------------------------------------------------------------------
414+
415+/**
416+ * Render the in-progress streaming response.
417+ *
418+ * Shows thinking (if enabled), streamed markdown, and pending tool calls.
419+ */
420+function renderStreamingResponse(state: AppState): Node[] {
421+ const nodes: Node[] = [];
422+
423+ if (state.showReasoning && streamingThinking) {
424+ nodes.push(
425+ VStack({ padding: { x: 1 } }, [
426+ Text(streamingThinking, {
427+ wrap: "word",
428+ fgColor: "color08",
429+ italic: true,
430+ }),
431+ ]),
432+ );
433+ }
434+
435+ if (streamingText) {
436+ nodes.push(
437+ ...Markdown(streamingText).map((n) =>
438+ HStack({ padding: { x: 1 } }, [VStack({ flex: 1 }, [n])]),
439+ ),
440+ );
441+ }
442+
443+ for (const tc of pendingToolCalls) {
444+ if (tc.resultText !== null) {
445+ nodes.push(
446+ renderToolResult(tc.name, tc.args, tc.resultText, tc.isError, state),
447+ );
448+ } else {
449+ // Tool still running — show indicator
450+ const label =
451+ tc.name === "shell"
452+ ? `$ ${tc.args.command ?? ""}…`
453+ : tc.name === "edit"
454+ ? `~ ${tc.args.path ?? ""}…`
455+ : `${tc.name}…`;
456+ nodes.push(
457+ HStack({ padding: { x: 1 } }, [
458+ Text("│ ", { fgColor: state.theme.toolBorder }),
459+ VStack({ flex: 1 }, [
460+ Text(label, { fgColor: "color06", italic: true }),
461+ ]),
462+ ]),
463+ );
464+ }
465+ }
466+
467+ return nodes;
468+}
469+
470+// ---------------------------------------------------------------------------
471+// Conversation log
472+// ---------------------------------------------------------------------------
473+
474+/** Build the full conversation log as an array of nodes. */
475+function buildConversationLog(state: AppState): Node[] {
476+ const nodes: Node[] = [];
477+
478+ // Map toolCallId → { name, args } so we can render diffs for edits.
479+ const toolCallArgs = new Map<
480+ string,
481+ { name: string; args: Record<string, unknown> }
482+ >();
483+
484+ for (const msg of state.messages) {
485+ if (msg.role === "user") {
486+ if (nodes.length > 0) nodes.push(Text(""));
487+ nodes.push(renderUserMessage(msg, state.theme));
488+ nodes.push(Text(""));
489+ } else if (msg.role === "assistant") {
490+ const am = msg as AssistantMessage;
491+ for (const block of am.content) {
492+ if (block.type === "toolCall") {
493+ const tc = block as ToolCall;
494+ toolCallArgs.set(tc.id, { name: tc.name, args: tc.arguments });
495+ }
496+ }
497+ nodes.push(...renderAssistantMessage(am, state));
498+ } else if (msg.role === "toolResult") {
499+ const info = toolCallArgs.get(msg.toolCallId);
500+ const name = info?.name ?? msg.toolName;
501+ const args = info?.args ?? {};
502+ const text = msg.content
503+ .filter((c): c is TextContent => c.type === "text")
504+ .map((c) => c.text)
505+ .join("\n");
506+ nodes.push(renderToolResult(name, args, text, msg.isError, state));
507+ }
508+ }
509+
510+ // Append in-progress streaming response
511+ if (isStreaming) {
512+ nodes.push(...renderStreamingResponse(state));
513+ }
514+
515+ // Empty state
516+ if (nodes.length === 0) {
517+ nodes.push(Spacer());
518+ nodes.push(
519+ VStack({ alignItems: "center" }, [
520+ Text(
521+ state.model
522+ ? "Ready. Type a message to start."
523+ : "No providers configured. Use /login to authenticate.",
524+ { fgColor: "color08", italic: true },
525+ ),
526+ ]),
527+ );
528+ nodes.push(Spacer());
529+ }
530+
531+ return nodes;
532+}
533+
534+// ---------------------------------------------------------------------------
535+// Agent loop wiring
536+// ---------------------------------------------------------------------------
537+
538+/** Send a plain text message and run the agent loop. */
539+async function submitMessage(text: string, state: AppState): Promise<void> {
540+ if (!text.trim() || !state.model || state.running) return;
541+
542+ const userMessage: Message = {
543+ role: "user",
544+ content: text,
545+ timestamp: Date.now(),
546+ };
547+
548+ // Append user message — returns the auto-assigned turn number
549+ const turn = appendMessage(state.db, state.session.id, userMessage);
550+ state.messages.push(userMessage);
551+ stickToBottom = true;
552+ cel.render();
553+
554+ // Refresh git state before each turn
555+ state.git = await getGitState(state.cwd);
556+
557+ const systemPrompt = buildPrompt(state);
558+ const { tools, toolHandlers } = buildToolList(state);
559+
560+ // Start agent loop
561+ state.running = true;
562+ state.abortController = new AbortController();
563+ isStreaming = true;
564+ streamingText = "";
565+ streamingThinking = "";
566+ pendingToolCalls = [];
567+ startDividerAnimation();
568+ cel.render();
569+
570+ try {
571+ await runAgentLoop({
572+ db: state.db,
573+ sessionId: state.session.id,
574+ turn,
575+ model: state.model,
576+ systemPrompt,
577+ tools,
578+ toolHandlers,
579+ messages: state.messages,
580+ cwd: state.cwd,
581+ signal: state.abortController.signal,
582+ onEvent: (event) => handleAgentEvent(event, state),
583+ });
584+ state.stats = computeStats(state.messages);
585+ } finally {
586+ state.running = false;
587+ state.abortController = null;
588+ isStreaming = false;
589+ streamingText = "";
590+ streamingThinking = "";
591+ pendingToolCalls = [];
592+ stopDividerAnimation();
593+ cel.render();
594+ }
595+}
596+
597+/** Handle events emitted by the agent loop. */
598+function handleAgentEvent(event: AgentEvent, state: AppState): void {
599+ switch (event.type) {
600+ case "text_delta":
601+ streamingText += event.delta;
602+ stickToBottom = true;
603+ cel.render();
604+ break;
605+
606+ case "thinking_delta":
607+ streamingThinking += event.delta;
608+ if (state.showReasoning) {
609+ stickToBottom = true;
610+ cel.render();
611+ }
612+ break;
613+
614+ case "tool_start":
615+ // The assistant message is appended to history before tool_start,
616+ // so clear the streaming buffers — that text is now in history.
617+ streamingText = "";
618+ streamingThinking = "";
619+ pendingToolCalls.push({
620+ name: event.name,
621+ args: event.args,
622+ resultText: null,
623+ isError: false,
624+ });
625+ stickToBottom = true;
626+ cel.render();
627+ break;
628+
629+ case "tool_end": {
630+ const pending = pendingToolCalls.find(
631+ (tc) => tc.name === event.name && tc.resultText === null,
632+ );
633+ if (pending) {
634+ pending.resultText = event.result.content
635+ .filter((c) => c.type === "text")
636+ .map((c) => (c as TextContent).text)
637+ .join("\n");
638+ pending.isError = event.result.isError;
639+ }
640+ stickToBottom = true;
641+ cel.render();
642+ break;
643+ }
644+
645+ case "done":
646+ case "error":
647+ case "aborted":
648+ // Completed messages are already in state.messages.
649+ streamingText = "";
650+ streamingThinking = "";
651+ pendingToolCalls = [];
652+ isStreaming = false;
653+ stickToBottom = true;
654+ cel.render();
655+ break;
656+ }
657+}
658+
659+// ---------------------------------------------------------------------------
660+// Graceful exit
661+// ---------------------------------------------------------------------------
662+
663+/** Shut down cleanly and exit. */
664+async function gracefulExit(state: AppState): Promise<void> {
665+ stopDividerAnimation();
666+ if (state.abortController) state.abortController.abort();
667+ cel.stop();
668+ await shutdown(state);
669+ process.exit(0);
670+}
671+
672+// ---------------------------------------------------------------------------
673+// Main
674+// ---------------------------------------------------------------------------
675+
676+/**
677+ * Start the terminal UI.
678+ *
679+ * Initializes cel-tui, sets up the viewport, and takes over the terminal.
680+ * Does not return until the user exits.
681+ *
682+ * @param state - The initialized application state from {@link init}.
683+ */
684+export function startUI(state: AppState): void {
685+ const terminal = new ProcessTerminal();
686+ cel.init(terminal);
687+
688+ cel.viewport(() => {
689+ const cols = terminal.columns;
690+
691+ return VStack(
692+ {
693+ height: "100%",
694+ onKeyPress: (key) => {
695+ if (key === "ctrl+c") {
696+ gracefulExit(state).catch(() => process.exit(1));
697+ return;
698+ }
699+ if (key === "ctrl+d" && inputValue === "") {
700+ gracefulExit(state).catch(() => process.exit(1));
701+ return;
702+ }
703+ if (key === "escape" && state.running) {
704+ if (state.abortController) state.abortController.abort();
705+ return;
706+ }
707+ return false;
708+ },
709+ },
710+ [
711+ // ── Conversation log ──
712+ VStack(
713+ {
714+ flex: 1,
715+ overflow: "scroll",
716+ scrollbar: true,
717+ scrollOffset: stickToBottom ? Infinity : scrollOffset,
718+ onScroll: (offset, maxOffset) => {
719+ scrollOffset = offset;
720+ stickToBottom = offset >= maxOffset;
721+ cel.render();
722+ },
723+ },
724+ buildConversationLog(state),
725+ ),
726+
727+ // ── Animated divider (pulse when agent is working) ──
728+ renderDivider(state, cols),
729+
730+ // ── Input area ──
731+ VStack({ padding: { x: 1 } }, [
732+ TextInput({
733+ flex: 1,
734+ maxHeight: 10,
735+ value: inputValue,
736+ onChange: (value) => {
737+ inputValue = value;
738+ cel.render();
739+ },
740+ placeholder: Text("message…", { fgColor: "color08" }),
741+ focused: inputFocused,
742+ onFocus: () => {
743+ inputFocused = true;
744+ cel.render();
745+ },
746+ onBlur: () => {
747+ inputFocused = false;
748+ cel.render();
749+ },
750+ onKeyPress: (key) => {
751+ if (key === "enter") {
752+ submitMessage(inputValue, state).catch((err) => {
753+ console.error("Submit error:", err);
754+ });
755+ inputValue = "";
756+ cel.render();
757+ return false;
758+ }
759+ },
760+ }),
761+ ]),
762+
763+ // ── Static divider ──
764+ Divider({ fgColor: state.theme.divider }),
765+
766+ // ── Status bar (2 lines) ──
767+ VStack(
768+ {
769+ height: 2,
770+ padding: { x: 1 },
771+ fgColor: state.theme.statusText,
772+ },
773+ [
774+ HStack({}, [
775+ Text(abbreviatePath(state.cwd)),
776+ Spacer(),
777+ Text(formatGitStatus(state), { fgColor: "color05" }),
778+ ]),
779+ HStack({}, [
780+ Text(formatModelInfo(state), { fgColor: "color06" }),
781+ Spacer(),
782+ Text(formatUsage(state)),
783+ ]),
784+ ],
785+ ),
786+ ],
787+ );
788+ });
789+}
tsconfig.json+0−1
@@ -6,7 +6,6 @@
66 "lib": ["ESNext"],
77 "types": ["bun"],
88 "strict": true,
9- "noImplicitReturns": true,
109 "noFallthroughCasesInSwitch": true,
1110 "forceConsistentCasingInFileNames": true,
1211 "skipLibCheck": true,