xonecas.io
64875
Mc

mini-coder / commit a00378e

fix(ui): simplify tool rendering and align streamed output

xonecas2026-04-08 a00378e7e46d13ccfd1f96d86d177c2316a45ec1 parent 90739e8

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

spec.md+3−2
@@ -504,8 +504,9 @@ Message types and their rendering:
504504
505505 - **User messages**: displayed as plain text with a subtle background color to distinguish them from agent responses. No prefix or role indicator.
506506 - **Assistant messages**: streamed markdown rendered via cel-tui's `Markdown` component on the default background. Thinking/reasoning content is collapsible (shown or hidden according to the user's persisted `/reasoning` preference; defaults to shown when no setting exists).
507-- **Tool calls — shell**: rendered with a left border (`│`) and dimmed foreground. Shows the command (`$ command`) and the tool output. When `/verbose` is off, shell output is previewed as the first 20 lines followed by `And X lines more` when additional lines exist. When `/verbose` is on, the shell block expands to the full stored tool result. This is a UI-only display choice over the stored result; it is separate from the shell tool's own safety truncation for pathological output. Exit cod …
508-- **Tool calls — edit**: rendered with a left border (`│`) and dimmed foreground. Shows the file path and a unified diff of the change (added lines in green, removed in red). When `/verbose` is off, the diff preview shows the first 20 diff lines followed by `And X lines more` when additional lines exist. When `/verbose` is on, the diff expands to the full stored tool result. This is a UI-only display choice. Uses the `diff` package (`structuredPatch`) for line-level diffing.
507+- **Tool calls — shell**: rendered with a left border (`│`) and dimmed foreground. The assistant tool call streams the arguments as they arrive. The shell tool result is rendered as the tool output (not the raw json, the content), with no extra header or placeholder lines. When `/verbose` is off, shell output is previewed as the first 20 lines followed by `And X lines more` when additional lines exist. When `/verbose` is on, the shell block expands to the full stored tool result. This is a U …
508+- **Tool calls — edit**: rendered with a left border (`│`) and dimmed foreground. Shows the arguments streamed in, preserving whitespace (the content of the arguments, not JSON). Then shows a unified diff of the change (added lines in green, removed in red). When `/verbose` is off, the diff preview shows the first 20 diff lines followed by `And X lines more` when additional lines exist. When `/verbose` is on, the diff expands to the full stored tool result. This is a UI-only display choice. …
509+- **Tool calls — readImage**: rendered with a left border (`│`) and dimmed foreground. The assistant tool call streams the arguments as they arrive (the path, not the JSON). Successful tool results display the text `Read image.` instead of rendering the image itself.
509510 - **Tool calls — plugin tools**: rendered with a left border, prefixed with plugin/tool name.
510511 - **UI messages**: internal app messages such as `/help` output, OAuth progress, and other session-local notices. They are rendered in the conversation log, persisted with the session, excluded from model context, and do not participate in conversational turn numbering.
511512 - **Errors**: one-line summary, styled distinctly.
src/ui.test.ts+23−12
@@ -909,7 +909,7 @@ describe("ui rendering", () => {
909909 fauxAssistantMessage(
910910 [
911911 fauxText("I'll inspect the command output first."),
912- fauxToolCall("shell", { command: "sleep 0.2; echo tool-output" }),
912+ fauxToolCall("shell", { command: "echo tool-output; sleep 0.2" }),
913913 ],
914914 { stopReason: "toolUse" },
915915 ),
@@ -925,7 +925,11 @@ describe("ui rendering", () => {
925925 props: {},
926926 children: buildConversationLog(state),
927927 });
928- return logText.includes("Running...");
928+ return (
929+ state.running &&
930+ logText.includes("$ echo tool-output; sleep 0.2") &&
931+ logText.includes("tool-output")
932+ );
929933 });
930934
931935 const logText = collectText({
@@ -935,8 +939,12 @@ describe("ui rendering", () => {
935939 });
936940
937941 expect(logText).toContain("I'll inspect the command output first.");
938- expect(logText).toContain("$ sleep 0.2; echo tool-output");
939- expect(logText).toContain("Running...");
942+ expect(
943+ logText.filter((line) => line === "$ echo tool-output; sleep 0.2"),
944+ ).toHaveLength(1);
945+ expect(logText).toContain("tool-output");
946+ expect(logText).not.toContain("Exit code: 0");
947+ expect(logText).not.toContain("Running...");
940948 } finally {
941949 await stopRunningTurn(state);
942950 process.env.PATH = originalPath;
@@ -1081,11 +1089,7 @@ describe("ui rendering", () => {
10811089 props: {},
10821090 children: buildConversationLog(state),
10831091 });
1084- return (
1085- state.running &&
1086- logText.includes("$ echo staged-command") &&
1087- logText.includes("Preparing...")
1088- );
1092+ return state.running && logText.includes("$ echo staged-command");
10891093 });
10901094
10911095 const logText = collectText({
@@ -1094,8 +1098,10 @@ describe("ui rendering", () => {
10941098 children: buildConversationLog(state),
10951099 });
10961100
1097- expect(logText).toContain("$ echo staged-command");
1098- expect(logText).toContain("Preparing...");
1101+ expect(
1102+ logText.filter((line) => line === "$ echo staged-command"),
1103+ ).toHaveLength(1);
1104+ expect(logText).not.toContain("Preparing...");
10991105 } finally {
11001106 await stopRunningTurn(state);
11011107 unregisterApiProviders(sourceId);
@@ -1244,9 +1250,14 @@ describe("ui rendering", () => {
12441250 children: buildConversationLog(state),
12451251 });
12461252
1247- expect(logText).toContain("$ echo tool-output");
1253+ expect(
1254+ logText.filter((line) => line === "$ echo tool-output"),
1255+ ).toHaveLength(1);
12481256 expect(logText).toContain("tool-output");
12491257 expect(logText).toContain("Done streaming");
1258+ expect(logText).not.toContain("Exit code: 0");
1259+ expect(logText).not.toContain("Preparing...");
1260+ expect(logText).not.toContain("Running...");
12501261 } finally {
12511262 await stopRunningTurn(state);
12521263 process.env.PATH = originalPath;
src/ui/agent.ts+24−39
@@ -30,10 +30,9 @@ import {
3030 truncatePromptHistory,
3131 } from "../session.ts";
3232 import { executeReadImage } from "../tools.ts";
33-import {
34- getToolResultText,
35- type PendingToolCall,
36- type StreamingConversationState,
33+import type {
34+ PendingToolResult,
35+ StreamingConversationState,
3736 } from "./conversation.ts";
3837
3938 /** Streaming assistant content for the current response. */
@@ -42,8 +41,8 @@ let streamingContent: AssistantMessage["content"] = [];
4241 /** Whether a response is currently streaming. */
4342 let isStreaming = false;
4443
45-/** Tool calls collected during the current streaming turn. */
46-let pendingToolCalls: PendingToolCall[] = [];
44+/** Tool results collected during the current streaming turn. */
45+let pendingToolResults: PendingToolResult[] = [];
4746
4847 /** Hooks implemented by `ui.ts` to bridge controller logic with runtime UI state. */
4948 interface UiAgentRuntime {
@@ -77,19 +76,19 @@ interface UiAgentController {
7776 export function resetUiAgentState(): void {
7877 streamingContent = [];
7978 isStreaming = false;
80- pendingToolCalls = [];
79+ pendingToolResults = [];
8180 }
8281
8382 /**
8483 * Read the current streaming tail state for conversation rendering.
8584 *
86- * @returns The in-progress assistant content and pending tool calls.
85+ * @returns The in-progress assistant content and pending tool results.
8786 */
8887 export function getStreamingConversationState(): StreamingConversationState {
8988 return {
9089 isStreaming,
9190 content: streamingContent,
92- pendingToolCalls,
91+ pendingToolResults,
9392 };
9493 }
9594
@@ -220,7 +219,7 @@ export function createUiAgentController(
220219 state.abortController = new AbortController();
221220 isStreaming = true;
222221 streamingContent = [];
223- pendingToolCalls = [];
222+ pendingToolResults = [];
224223 runtime.startDividerAnimation();
225224 runtime.render();
226225
@@ -294,39 +293,25 @@ export function createUiAgentController(
294293 break;
295294
296295 case "tool_start":
297- pendingToolCalls.push({
298- toolCallId: event.toolCallId,
299- name: event.name,
300- args: event.args,
301- resultText: "",
302- isError: false,
303- done: false,
304- });
305- runtime.scrollConversationToBottom();
306- runtime.render();
307296 break;
308297
309- case "tool_delta": {
310- const pending = pendingToolCalls.find(
311- (toolCall) => toolCall.toolCallId === event.toolCallId,
312- );
313- if (pending) {
314- pending.resultText = getToolResultText(event.result);
315- pending.isError = event.result.isError;
316- }
317- runtime.scrollConversationToBottom();
318- runtime.render();
319- break;
320- }
321-
298+ case "tool_delta":
322299 case "tool_end": {
323- const pending = pendingToolCalls.find(
324- (toolCall) => toolCall.toolCallId === event.toolCallId,
300+ const pending = pendingToolResults.find(
301+ (toolResult) => toolResult.toolCallId === event.toolCallId,
325302 );
303+ const content = structuredClone(event.result.content);
326304 if (pending) {
327- pending.resultText = getToolResultText(event.result);
305+ pending.toolName = event.name;
306+ pending.content = content;
328307 pending.isError = event.result.isError;
329- pending.done = true;
308+ } else {
309+ pendingToolResults.push({
310+ toolCallId: event.toolCallId,
311+ toolName: event.name,
312+ content,
313+ isError: event.result.isError,
314+ });
330315 }
331316 runtime.scrollConversationToBottom();
332317 runtime.render();
@@ -335,8 +320,8 @@ export function createUiAgentController(
335320
336321 case "tool_result":
337322 state.messages.push(event.message);
338- pendingToolCalls = pendingToolCalls.filter(
339- (toolCall) => toolCall.toolCallId !== event.message.toolCallId,
323+ pendingToolResults = pendingToolResults.filter(
324+ (toolResult) => toolResult.toolCallId !== event.message.toolCallId,
340325 );
341326 runtime.scrollConversationToBottom();
342327 runtime.render();
src/ui/conversation.test.ts+105−49
@@ -8,7 +8,8 @@ import {
88 } from "@mariozechner/pi-ai";
99 import { DEFAULT_THEME, type Theme } from "../theme.ts";
1010 import {
11- type PendingToolCall,
11+ buildConversationLogNodes,
12+ type PendingToolResult,
1213 previewToolRenderLines,
1314 renderAssistantMessage,
1415 renderToolResult,
@@ -111,32 +112,44 @@ describe("ui/conversation", () => {
111112 expect(text).not.toContain("line two");
112113 });
113114
114- test("renderAssistantMessage keeps in-progress text and tool output inside one top-level container", () => {
115- const pendingToolCalls: PendingToolCall[] = [
115+ test("buildConversationLogNodes keeps tool call args and streamed shell output append-only", () => {
116+ const pendingToolResults: PendingToolResult[] = [
116117 {
117118 toolCallId: "tool-1",
118- name: "shell",
119- args: { command: "echo hi" },
120- resultText: "hi",
119+ toolName: "shell",
120+ content: [{ type: "text", text: "Exit code: 0\npartial output" }],
121121 isError: false,
122- done: true,
123122 },
124123 ];
125124
126- const node = renderAssistantMessage(
125+ const nodes = buildConversationLogNodes(
127126 {
128- content: [fauxText("Working...")],
129- pendingToolCalls,
127+ messages: [
128+ fauxAssistantMessage([
129+ fauxText("Working..."),
130+ fauxToolCall("shell", { command: "echo hi" }, { id: "tool-1" }),
131+ ]),
132+ ],
133+ showReasoning: false,
134+ verbose: false,
135+ theme: DEFAULT_THEME,
136+ },
137+ {
138+ isStreaming: true,
139+ content: [],
140+ pendingToolResults,
130141 },
131- RENDER_OPTS,
132142 );
143+ const text = collectText({
144+ type: "vstack",
145+ props: {},
146+ children: nodes,
147+ });
133148
134- expect(node).not.toBeNull();
135- expect(node?.type).toBe("vstack");
136- if (!node || node.type !== "vstack") {
137- throw new Error("Expected a vstack container");
138- }
139- expect(node.children.length).toBeGreaterThanOrEqual(2);
149+ expect(text).toContain("Working...");
150+ expect(text.filter((line) => line === "$ echo hi")).toHaveLength(1);
151+ expect(text).toContain("partial output");
152+ expect(text).not.toContain("Exit code: 0");
140153 });
141154
142155 test("renderAssistantMessage shows in-progress thinking when reasoning is enabled", () => {
@@ -169,7 +182,7 @@ describe("ui/conversation", () => {
169182 expect(text).toContain("Thinking... 1 line.");
170183 });
171184
172- test("renderAssistantMessage shows streamed tool call arguments before execution begins", () => {
185+ test("renderAssistantMessage shows streamed shell arguments semantically", () => {
173186 const node = renderAssistantMessage(
174187 {
175188 content: [
@@ -181,31 +194,53 @@ describe("ui/conversation", () => {
181194 const text = collectText(node);
182195
183196 expect(text).toContain("$ echo hi");
184- expect(text).toContain("Preparing...");
197+ expect(text).not.toContain('"command": "echo hi"');
198+ expect(text).not.toContain("Preparing...");
185199 });
186200
187- test("renderAssistantMessage shows partial tool output before the tool finishes", () => {
201+ test("renderAssistantMessage shows streamed readImage arguments semantically", () => {
188202 const node = renderAssistantMessage(
189203 {
190- content: [],
191- pendingToolCalls: [
192- {
193- toolCallId: "tool-1",
194- name: "shell",
195- args: { command: "echo hi" },
196- resultText: "partial output",
197- isError: false,
198- done: false,
199- },
204+ content: [
205+ fauxToolCall(
206+ "readImage",
207+ { path: "assets/preview.png" },
208+ { id: "tool-1" },
209+ ),
200210 ],
201211 },
202212 RENDER_OPTS,
203213 );
204214 const text = collectText(node);
205215
206- expect(text).toContain("$ echo hi");
207- expect(text).toContain("partial output");
208- expect(text).toContain("Running...");
216+ expect(text).toContain("~ assets/preview.png");
217+ expect(text).not.toContain("{");
218+ });
219+
220+ test("renderAssistantMessage shows streamed edit arguments semantically", () => {
221+ const node = renderAssistantMessage(
222+ {
223+ content: [
224+ fauxToolCall(
225+ "edit",
226+ {
227+ path: "src/file.ts",
228+ oldText: "old line",
229+ newText: "new line",
230+ },
231+ { id: "tool-1" },
232+ ),
233+ ],
234+ },
235+ RENDER_OPTS,
236+ );
237+ const text = collectText(node);
238+
239+ expect(text).toContain("~ src/file.ts");
240+ expect(text).toContain("-old line");
241+ expect(text).toContain("+new line");
242+ expect(text).not.toContain("-");
243+ expect(text).not.toContain("+");
209244 });
210245
211246 test("previewToolRenderLines keeps all lines in verbose mode", () => {
@@ -236,26 +271,31 @@ describe("ui/conversation", () => {
236271 });
237272 });
238273
239- test("renderToolResult uses themed accent colors for tool headers", () => {
274+ test("tool call headers use themed accent colors", () => {
240275 const theme: Theme = {
241276 ...DEFAULT_THEME,
242277 accentText: "color04",
243278 secondaryAccentText: "color05",
244279 };
245280
246- const shellNode = renderToolResult(
247- "shell",
248- { command: "seq 1 3" },
249- "1\n2\n3",
250- false,
281+ const editCallNode = renderAssistantMessage(
282+ {
283+ content: [
284+ fauxToolCall(
285+ "edit",
286+ { path: "src/file.ts", oldText: "old", newText: "new" },
287+ { id: "tool-1" },
288+ ),
289+ ],
290+ },
251291 { ...RENDER_OPTS, theme },
252292 );
253- const shellHeader = findTextNode(shellNode, "$ seq 1 3");
254- expect(shellHeader).not.toBeNull();
255- if (!shellHeader || shellHeader.type !== "text") {
256- throw new Error("Expected shell header to be a text node");
293+ const editHeader = findTextNode(editCallNode, "~ src/file.ts");
294+ expect(editHeader).not.toBeNull();
295+ if (!editHeader || editHeader.type !== "text") {
296+ throw new Error("Expected edit header to be a text node");
257297 }
258- expect(shellHeader.props.fgColor).toBe(theme.accentText);
298+ expect(editHeader.props.fgColor).toBe(theme.accentText);
259299
260300 const pluginNode = renderToolResult("plugin-tool", {}, "ok", false, {
261301 ...RENDER_OPTS,
@@ -283,11 +323,11 @@ describe("ui/conversation", () => {
283323 );
284324 const text = collectText(node);
285325
286- expect(text).toContain("$ seq 1 25");
287326 expect(text).toContain("line 1");
288327 expect(text).toContain("line 20");
289328 expect(text).toContain("And 5 lines more");
290329 expect(text).not.toContain("line 21");
330+ expect(text).not.toContain("$ seq 1 25");
291331 });
292332
293333 test("renderToolResult shows full shell output in verbose mode", () => {
@@ -308,7 +348,7 @@ describe("ui/conversation", () => {
308348 expect(text).not.toContain("And 5 lines more");
309349 });
310350
311- test("renderToolResult shows shell exit codes", () => {
351+ test("renderToolResult strips shell exit-code and stderr labels in the UI", () => {
312352 const node = renderToolResult(
313353 "shell",
314354 { command: "exit 42" },
@@ -318,8 +358,24 @@ describe("ui/conversation", () => {
318358 );
319359 const text = collectText(node);
320360
321- expect(text).toContain("$ exit 42");
322- expect(text).toContain("Exit code: 42");
361+ expect(text).toContain("boom");
362+ expect(text).not.toContain("$ exit 42");
363+ expect(text).not.toContain("Exit code: 42");
364+ expect(text).not.toContain("[stderr]");
365+ });
366+
367+ test("renderToolResult shows a readImage success message", () => {
368+ const node = renderToolResult(
369+ "readImage",
370+ { path: "diagram.png" },
371+ "",
372+ false,
373+ RENDER_OPTS,
374+ );
375+ const text = collectText(node);
376+
377+ expect(text).toContain("Read image.");
378+ expect(text).not.toContain("~ diagram.png");
323379 });
324380
325381 test("renderToolResult shows a diff for newly created files", () => {
@@ -354,7 +410,7 @@ describe("ui/conversation", () => {
354410 );
355411 const text = collectText(node);
356412
357- expect(text).toContain("~ src/file.ts");
413+ expect(text).not.toContain("~ src/file.ts");
358414 expect(text.at(-1)).toMatch(/^And \d+ lines more$/);
359415 expect(text).not.toContain("+new 11");
360416 });
src/ui/conversation.ts+209−255
@@ -14,10 +14,10 @@ import type { Node } from "@cel-tui/types";
1414 import type {
1515 AssistantMessage,
1616 TextContent,
17+ ToolResultMessage,
1718 UserMessage,
1819 } from "@mariozechner/pi-ai";
1920 import { structuredPatch } from "diff";
20-import type { AgentEvent } from "../agent.ts";
2121 import type { AppState } from "../index.ts";
2222 import type { UiMessage } from "../session.ts";
2323 import type { Theme } from "../theme.ts";
@@ -25,20 +25,16 @@ import type { Theme } from "../theme.ts";
2525 /** Max body lines shown for tool results when verbose mode is off. */
2626 const UI_TOOL_PREVIEW_LINES = 20;
2727
28-/** A pending tool call shown in the streaming tail. */
29-export interface PendingToolCall {
28+/** A pending tool result shown in the streaming tail. */
29+export interface PendingToolResult {
3030 /** Tool call id from the assistant message. */
3131 toolCallId: string;
3232 /** Tool name. */
33- name: string;
34- /** Tool call arguments. */
35- args: Record<string, unknown>;
36- /** Progressive text output captured so far. */
37- resultText: string;
33+ toolName: string;
34+ /** Progressive or final tool-result content captured so far. */
35+ content: ToolResultMessage["content"];
3836 /** Whether the tool result was an error. */
3937 isError: boolean;
40- /** Whether the tool has finished. */
41- done: boolean;
4238 }
4339
4440 /** Render options shared by completed and in-progress assistant content. */
@@ -57,16 +53,14 @@ export interface StreamingConversationState {
5753 isStreaming: boolean;
5854 /** Assistant content accumulated so far. */
5955 content: AssistantMessage["content"];
60- /** Tool calls observed during the current streaming turn. */
61- pendingToolCalls: readonly PendingToolCall[];
56+ /** Tool results observed during the current streaming turn. */
57+ pendingToolResults: readonly PendingToolResult[];
6258 }
6359
6460 /** Display-only assistant state used while a response is still streaming. */
6561 interface AssistantRenderState {
6662 /** Assistant content blocks accumulated so far. */
6763 content: AssistantMessage["content"];
68- /** Tool calls observed in the current streaming turn. */
69- pendingToolCalls?: readonly PendingToolCall[];
7064 /** Optional error text appended below the assistant content. */
7165 errorMessage?: string;
7266 }
@@ -127,21 +121,6 @@ function getAssistantErrorMessage(
127121 return assistant.errorMessage;
128122 }
129123
130-function getPendingToolCalls(
131- assistant: AssistantMessage | AssistantRenderState,
132-): readonly PendingToolCall[] {
133- if ("role" in assistant) {
134- return [];
135- }
136- return assistant.pendingToolCalls ?? [];
137-}
138-
139-function isStreamingAssistant(
140- assistant: AssistantMessage | AssistantRenderState,
141-): assistant is AssistantRenderState {
142- return !("role" in assistant);
143-}
144-
145124 function renderThinkingBlock(
146125 thinking: string,
147126 opts: ConversationRenderOpts,
@@ -169,7 +148,6 @@ function renderThinkingBlock(
169148 function renderAssistantContentBlock(
170149 block: AssistantMessage["content"][number],
171150 opts: ConversationRenderOpts,
172- isStreaming: boolean,
173151 ): Node[] {
174152 if (block.type === "text" && block.text) {
175153 return renderMarkdownContent(block.text);
@@ -177,8 +155,8 @@ function renderAssistantContentBlock(
177155 if (block.type === "thinking" && block.thinking) {
178156 return [renderThinkingBlock(block.thinking, opts)];
179157 }
180- if (block.type === "toolCall" && isStreaming) {
181- return [renderStreamingToolCall(block, opts)];
158+ if (block.type === "toolCall") {
159+ return renderToolCall(block, opts);
182160 }
183161 return [];
184162 }
@@ -194,15 +172,10 @@ export function renderAssistantMessage(
194172 assistant: AssistantMessage | AssistantRenderState,
195173 opts: ConversationRenderOpts,
196174 ): Node | null {
197- const streaming = isStreamingAssistant(assistant);
198175 const children = assistant.content.flatMap((block) => {
199- return renderAssistantContentBlock(block, opts, streaming);
176+ return renderAssistantContentBlock(block, opts);
200177 });
201178
202- for (const toolCall of getPendingToolCalls(assistant)) {
203- children.push(renderPendingToolCall(toolCall, opts));
204- }
205-
206179 const errorMessage = getAssistantErrorMessage(assistant);
207180 if (errorMessage) {
208181 children.push(
@@ -270,16 +243,22 @@ export function previewToolRenderLines(
270243 ];
271244 }
272245
246+/** Strip shell execution labels that should not appear in the UI. */
247+function normalizeShellOutput(output: string): string {
248+ return output
249+ .replace(/^Exit code: \d+\n?/, "")
250+ .replace(/(^|\n)\[stderr\]\n/g, "$1");
251+}
252+
273253 /** Build the logical render lines for a shell tool result. */
274254 function buildShellToolLines(
275- command: string,
276255 output: string,
277256 verbose: boolean,
278257 ): ToolRenderLine[] {
279- return [
280- { kind: "command", text: `$ ${command}` },
281- ...previewToolRenderLines(splitToolTextLines(output, "text"), verbose),
282- ];
258+ return previewToolRenderLines(
259+ splitToolTextLines(normalizeShellOutput(output), "text"),
260+ verbose,
261+ );
283262 }
284263
285264 function buildStructuredDiffLines(
@@ -311,9 +290,29 @@ function buildStructuredDiffLines(
311290 return diffLines;
312291 }
313292
293+function splitPrefixedToolTextLines(
294+ text: string,
295+ kind: "diffAdded" | "diffRemoved",
296+ prefix: string,
297+): ToolRenderLine[] {
298+ if (text === "") {
299+ return [];
300+ }
301+
302+ const lines = text.split("\n");
303+ if (lines.at(-1) === "") {
304+ lines.pop();
305+ }
306+
307+ return lines.map((line) => ({
308+ kind,
309+ text: `${prefix}${line}`,
310+ }));
311+}
312+
314313 /** Build the logical render lines for an edit tool result. */
315314 function buildEditToolLines(
316- filePath: string,
315+ _filePath: string,
317316 oldText: string,
318317 newText: string,
319318 isError: boolean,
@@ -321,26 +320,20 @@ function buildEditToolLines(
321320 verbose: boolean,
322321 ): ToolRenderLine[] {
323322 if (isError) {
324- return [
325- { kind: "path", text: `~ ${filePath}` },
326- ...previewToolRenderLines(
327- splitToolTextLines(resultText, "error"),
328- verbose,
329- ),
330- ];
323+ return previewToolRenderLines(
324+ splitToolTextLines(resultText, "error"),
325+ verbose,
326+ );
331327 }
332328
333329 const diffLines = buildStructuredDiffLines(oldText, newText);
334330
335- return [
336- { kind: "path", text: `~ ${filePath}` },
337- ...previewToolRenderLines(
338- diffLines.length > 0
339- ? diffLines
340- : [{ kind: "summary", text: "(empty file)" }],
341- verbose,
342- ),
343- ];
331+ return previewToolRenderLines(
332+ diffLines.length > 0
333+ ? diffLines
334+ : [{ kind: "summary", text: "(empty file)" }],
335+ verbose,
336+ );
344337 }
345338
346339 /** Render a single styled text node for a tool line. */
@@ -392,235 +385,184 @@ function renderToolBlock(lines: readonly ToolRenderLine[], theme: Theme): Node {
392385 ]);
393386 }
394387
395-/**
396- * Extract text blocks from a streamed tool result for UI rendering.
397- *
398- * @param result - Incremental or final tool result event payload.
399- * @returns Concatenated text blocks joined with newlines.
400- */
401-export function getToolResultText(
402- result: Extract<AgentEvent, { type: "tool_delta" | "tool_end" }>["result"],
403-): string {
404- return result.content
405- .filter((content): content is TextContent => content.type === "text")
406- .map((content) => content.text)
388+function getToolContentText(content: ToolResultMessage["content"]): string {
389+ return content
390+ .filter((entry): entry is TextContent => entry.type === "text")
391+ .map((entry) => entry.text)
407392 .join("\n");
408393 }
409394
410-/** Render a shell tool call with left border. */
411-function renderShellToolCall(
412- command: string,
413- output: string,
414- _isError: boolean,
415- opts: Pick<ConversationRenderOpts, "verbose" | "theme">,
416-): Node {
417- return renderToolBlock(
418- buildShellToolLines(command, output, opts.verbose),
419- opts.theme,
420- );
395+function buildToolHeaderLine(
396+ toolName: string,
397+ args: Record<string, unknown>,
398+): ToolRenderLine | null {
399+ if (toolName === "shell") {
400+ const command = getToolArgString(args, "command");
401+ return command ? { kind: "command", text: `$ ${command}` } : null;
402+ }
403+
404+ if (toolName === "edit" || toolName === "readImage") {
405+ const filePath = getToolArgString(args, "path");
406+ return filePath ? { kind: "path", text: `~ ${filePath}` } : null;
407+ }
408+
409+ return { kind: "toolName", text: toolName };
421410 }
422411
423-/** Render an edit tool call with file path and unified diff. */
424-function renderEditToolCall(
412+function buildEditToolCallLines(
425413 filePath: string,
426414 oldText: string,
427415 newText: string,
428- isError: boolean,
429- resultText: string,
430- opts: Pick<ConversationRenderOpts, "verbose" | "theme">,
431-): Node {
432- return renderToolBlock(
433- buildEditToolLines(
434- filePath,
435- oldText,
436- newText,
437- isError,
438- resultText,
439- opts.verbose,
440- ),
441- opts.theme,
442- );
443-}
416+ verbose: boolean,
417+): ToolRenderLine[] {
418+ const lines: ToolRenderLine[] = [];
419+ if (filePath) {
420+ lines.push({ kind: "path", text: `~ ${filePath}` });
421+ }
444422
445-/** Render a generic (plugin) tool call with left border. */
446-function renderGenericToolCall(
447- toolName: string,
448- output: string,
449- isError: boolean,
450- theme: Theme,
451-): Node {
452- const lines: ToolRenderLine[] = [
453- { kind: "toolName", text: toolName },
454- ...splitToolTextLines(output, isError ? "error" : "text"),
455- ];
423+ const bodyLines = previewToolRenderLines(
424+ [
425+ ...splitPrefixedToolTextLines(oldText, "diffRemoved", "-"),
426+ ...splitPrefixedToolTextLines(newText, "diffAdded", "+"),
427+ ],
428+ verbose,
429+ );
456430
457- return renderToolBlock(lines, theme);
431+ return [...lines, ...bodyLines];
458432 }
459433
460-/**
461- * Render a tool result, dispatching by tool name.
462- *
463- * @param toolName - Tool name to render.
464- * @param args - Tool call arguments used for headers and diffs.
465- * @param resultText - Text content from the tool result message.
466- * @param isError - Whether the tool execution failed.
467- * @param opts - Shared conversation render options.
468- * @returns The rendered tool block node.
469- */
470-export function renderToolResult(
434+function buildToolCallLines(
471435 toolName: string,
472436 args: Record<string, unknown>,
473- resultText: string,
474- isError: boolean,
475- opts: ConversationRenderOpts,
476-): Node {
477- if (toolName === "shell") {
478- return renderShellToolCall(
479- getToolArgString(args, "command"),
480- resultText,
481- isError,
482- {
483- verbose: opts.verbose,
484- theme: opts.theme,
485- },
486- );
437+ verbose: boolean,
438+): ToolRenderLine[] {
439+ if (toolName === "shell" || toolName === "readImage") {
440+ const header = buildToolHeaderLine(toolName, args);
441+ return header ? [header] : [];
487442 }
443+
488444 if (toolName === "edit") {
489- return renderEditToolCall(
445+ return buildEditToolCallLines(
490446 getToolArgString(args, "path"),
491447 getToolArgString(args, "oldText"),
492448 getToolArgString(args, "newText"),
493- isError,
494- resultText,
495- {
496- verbose: opts.verbose,
497- theme: opts.theme,
498- },
449+ verbose,
499450 );
500451 }
501- return renderGenericToolCall(toolName, resultText, isError, opts.theme);
502-}
503-
504-function buildPendingRunningLines(done: boolean): ToolRenderLine[] {
505- return done
506- ? []
507- : [
508- {
509- kind: "summary",
510- text: "Running...",
511- },
512- ];
513-}
514-
515-function buildToolHeader(
516- toolName: string,
517- args: Record<string, unknown>,
518-): ToolRenderLine {
519- if (toolName === "shell") {
520- const command = getToolArgString(args, "command");
521- if (command) {
522- return {
523- kind: "command",
524- text: `$ ${command}`,
525- };
526- }
527- }
528- if (toolName === "edit") {
529- const filePath = getToolArgString(args, "path");
530- if (filePath) {
531- return {
532- kind: "path",
533- text: `~ ${filePath}`,
534- };
535- }
536- }
537- return {
538- kind: "toolName",
539- text: toolName,
540- };
541-}
542452
543-function buildToolArgumentPreviewLines(
544- args: Record<string, unknown>,
545- verbose: boolean,
546-): ToolRenderLine[] {
547453 const text = JSON.stringify(args, null, 2);
548454 if (!text || text === "{}") {
549- return [];
455+ const header = buildToolHeaderLine(toolName, args);
456+ return header ? [header] : [];
550457 }
551458
552- return previewToolRenderLines(splitToolTextLines(text, "text"), verbose);
553-}
554-
555-function buildPendingToolHeader(toolCall: PendingToolCall): ToolRenderLine {
556- return buildToolHeader(toolCall.name, toolCall.args);
459+ return [
460+ { kind: "toolName", text: toolName },
461+ ...previewToolRenderLines(splitToolTextLines(text, "text"), verbose),
462+ ];
557463 }
558464
559-function renderStreamingToolCall(
465+function renderToolCall(
560466 toolCall: Extract<AssistantMessage["content"][number], { type: "toolCall" }>,
561467 opts: Pick<ConversationRenderOpts, "verbose" | "theme">,
562-): Node {
563- const header = buildToolHeader(toolCall.name, toolCall.arguments);
564- const lines: ToolRenderLine[] = [header];
565-
566- if (header.kind === "toolName") {
567- lines.push(
568- ...buildToolArgumentPreviewLines(toolCall.arguments, opts.verbose),
569- );
570- }
571-
572- lines.push({ kind: "summary", text: "Preparing..." });
573-
574- return renderToolBlock(lines, opts.theme);
468+): Node[] {
469+ const lines = buildToolCallLines(
470+ toolCall.name,
471+ toolCall.arguments,
472+ opts.verbose,
473+ );
474+ return lines.length > 0 ? [renderToolBlock(lines, opts.theme)] : [];
575475 }
576476
577-function buildPendingToolResultLines(
578- toolCall: PendingToolCall,
477+function buildReadImageToolLines(
478+ content: ToolResultMessage["content"],
479+ isError: boolean,
579480 verbose: boolean,
580481 ): ToolRenderLine[] {
581- if (toolCall.name === "shell") {
582- return buildShellToolLines(
583- getToolArgString(toolCall.args, "command"),
584- toolCall.resultText,
482+ if (isError) {
483+ return previewToolRenderLines(
484+ splitToolTextLines(getToolContentText(content), "error"),
585485 verbose,
586486 );
587487 }
588- if (toolCall.name === "edit") {
589- return [
590- buildPendingToolHeader(toolCall),
591- ...previewToolRenderLines(
592- splitToolTextLines(
593- toolCall.resultText,
594- toolCall.isError ? "error" : "text",
595- ),
596- verbose,
597- ),
598- ];
599- }
488+
489+ return [{ kind: "text", text: "Read image." }];
490+}
491+
492+function buildGenericToolLines(
493+ toolName: string,
494+ output: string,
495+ isError: boolean,
496+): ToolRenderLine[] {
600497 return [
601- buildPendingToolHeader(toolCall),
602- ...splitToolTextLines(
603- toolCall.resultText,
604- toolCall.isError ? "error" : "text",
605- ),
498+ { kind: "toolName", text: toolName },
499+ ...splitToolTextLines(output, isError ? "error" : "text"),
606500 ];
607501 }
608502
609-/** Render a pending tool call, including progressive output when available. */
610-function renderPendingToolCall(
611- toolCall: PendingToolCall,
503+function renderToolResultContent(
504+ toolName: string,
505+ args: Record<string, unknown>,
506+ content: ToolResultMessage["content"],
507+ isError: boolean,
612508 opts: Pick<ConversationRenderOpts, "verbose" | "theme">,
613509 ): Node {
614- const lines = toolCall.resultText
615- ? buildPendingToolResultLines(toolCall, opts.verbose)
616- : [buildPendingToolHeader(toolCall)];
510+ if (toolName === "shell") {
511+ return renderToolBlock(
512+ buildShellToolLines(getToolContentText(content), opts.verbose),
513+ opts.theme,
514+ );
515+ }
516+ if (toolName === "edit") {
517+ return renderToolBlock(
518+ buildEditToolLines(
519+ getToolArgString(args, "path"),
520+ getToolArgString(args, "oldText"),
521+ getToolArgString(args, "newText"),
522+ isError,
523+ getToolContentText(content),
524+ opts.verbose,
525+ ),
526+ opts.theme,
527+ );
528+ }
529+ if (toolName === "readImage") {
530+ return renderToolBlock(
531+ buildReadImageToolLines(content, isError, opts.verbose),
Cut short: this commit's diff is over 1000 lines.