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