@@ -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.