xonecas.io
64875
Mc

mini-coder / commit 6208adb

fix: stream tool output updates in tui

xonecas2026-04-06 6208adb252e383e1c592b56f751e1370caddd4aa parent 32f0405

9 files changed

AGENTS.md+1−0
@@ -51,6 +51,7 @@
5151 - **Display-only state must not leak into model context.** Info messages (login progress, fork confirmation) belong in a separate display array, not `state.messages`. Anything in `state.messages` gets sent to the LLM as conversation history.
5252 - **Compatibility policy is a product decision.** Before 1.0, prefer correct, simple semantics over speculative backward-compatibility shims. If a change may affect existing data or behavior, raise it explicitly, but do not implement migrations or compatibility layers unless the spec or user asks for them.
5353 - **Breaking changes still need to be called out.** Pre-1.0 is not a license to surprise the user. If a change intentionally trades compatibility for correctness or simplicity, say so explicitly in discussion and keep TODO/release notes aligned.
54+- **TUI changes need real terminal validation.** For rendering, streaming, scrolling, resize, focus, or input changes, passing tests is not enough. Validate the behavior manually in `tmux` before calling the change done.
5455
5556 ## Testing strategy
5657
TODO.md+5−4
@@ -1,11 +1,14 @@
11 # TODO
22
3+Keep this always update so work can continue accross sessions.
4+Don't keep completed items bloating the file.
5+Keep the file strucured and minimal.
6+The spec.md and code are the sources of truth, not this file, don't assume anything because it's documented here.
7+
38 ## Bugs — from code review
49
510 ### MUST FIX
611
7-- [ ] **Tool outputs are not streamed into the UI** (`agent.ts` / `ui.ts`) — shell/edit/plugin tool results only become visible on `tool_end`, so long-running tools make the UI feel stalled instead of progressively updating. This conflicts with the spec's emphasis on speed and streaming feel. Fix: design a streaming/partial tool-output path (or explicit progressive status model) so tool execution remains visibly active before the final result lands.
8-
912 - [ ] **TextInput cursor is off by one after line wrapping** (`ui.ts` / cel-tui TextInput integration) — when the input wraps onto a new line, the visual cursor position drifts by one column from the actual insertion point. My current suspicion is that wrapping is happening at the cell level, but the cursor position is being computed against the logical text position without staying in sync with where the wrapped cell actually lands on the next line. That makes editing long prompts confusing a …
1013
1114 - [ ] **Streaming Markdown wraps can corrupt the UI until the turn finishes** (`ui.ts` / cel-tui Markdown integration) — some styled Markdown lines break badly at wrap boundaries during streaming, causing duplicated/corrupted rendering in the conversation log. The corruption clears itself once the assistant turn completes, which suggests a bug in the incremental render path around wrapped styled content rather than persisted message rendering. Fix: reproduce with a regression test and adjust t …
@@ -28,8 +31,6 @@
2831
2932 ### Medium
3033
31-- [ ] **Fragile `tool_end` matching** (`ui.ts`/`agent.ts`) — `tool_end` events match pending tool calls by name + null resultText. Two calls to the same tool in one response (e.g., two `shell` calls) rely on sequential execution order. Fix: add `toolCallId` to `tool_start`/`tool_end` `AgentEvent` types, emit from `agent.ts`, match by id in `ui.ts`.
32-
3334 - [ ] **Stale plugin `AgentContext.messages`** (`index.ts`) — `AgentContext.messages` is the same array ref as `state.messages`, which gets reassigned on `/new`, `/session`, `/fork`, `/undo`. Plugins holding the original reference see stale data. Fix: use a getter (`get messages() { return state.messages; }`).
3435
3536 - [ ] **OAuth credential reference comparison** (`index.ts`) — `result.newCredentials !== oauthCredentials[oauthProvider.id]` compares by reference, not value. Causes unnecessary disk writes on every startup if `getOAuthApiKey` returns a new object. Fix: unconditionally assign when result is present, or compare serialized form.
src/agent.test.ts+82−2
@@ -73,8 +73,11 @@ function builtinToolHandlers(): Map<string, ToolHandler> {
7373 return new Map<string, ToolHandler>([
7474 [
7575 "shell",
76- async (args, cwd) =>
77- executeShell({ command: args.command as string }, cwd),
76+ async (args, cwd, signal, onUpdate) =>
77+ executeShell({ command: args.command as string }, cwd, {
78+ ...(signal ? { signal } : {}),
79+ ...(onUpdate ? { onUpdate } : {}),
80+ }),
7881 ],
7982 [
8083 "edit",
@@ -532,6 +535,83 @@ describe("agent loop", () => {
532535 expect(toolEnds).toHaveLength(1);
533536 });
534537
538+ test("emits tool delta events during tool execution", async () => {
539+ faux.setResponses([
540+ fauxAssistantMessage([fauxToolCall("shell", { command: "echo test" })], {
541+ stopReason: "toolUse",
542+ }),
543+ fauxAssistantMessage("Done."),
544+ ]);
545+
546+ const events: AgentEvent[] = [];
547+ const toolHandlers = new Map<string, ToolHandler>([
548+ [
549+ "shell",
550+ async (_args, _cwd, _signal, onUpdate) => {
551+ onUpdate?.({
552+ content: [{ type: "text", text: "partial output" }],
553+ isError: false,
554+ });
555+ return {
556+ content: [{ type: "text", text: "final output" }],
557+ isError: false,
558+ };
559+ },
560+ ],
561+ ]);
562+
563+ const session = createSession(db, { cwd: tmp });
564+ const userMsg = makeUser("go");
565+ const turn = appendMessage(db, session.id, userMsg);
566+
567+ await runAgentLoop({
568+ db,
569+ sessionId: session.id,
570+ turn,
571+ model: faux.getModel(),
572+ systemPrompt: "Test",
573+ tools: builtinToolDefs(),
574+ toolHandlers,
575+ messages: [userMsg],
576+ cwd: tmp,
577+ onEvent: (e) => events.push(e),
578+ });
579+
580+ const toolStart = events.find((event) => event.type === "tool_start");
581+ const toolDelta = events.find((event) => event.type === "tool_delta");
582+ const toolEnd = events.find((event) => event.type === "tool_end");
583+
584+ expect(toolStart).toBeDefined();
585+ expect(toolDelta).toBeDefined();
586+ expect(toolEnd).toBeDefined();
587+
588+ if (
589+ !toolStart ||
590+ toolStart.type !== "tool_start" ||
591+ !toolDelta ||
592+ toolDelta.type !== "tool_delta" ||
593+ !toolEnd ||
594+ toolEnd.type !== "tool_end"
595+ ) {
596+ throw new Error("Expected tool start, delta, and end events");
597+ }
598+
599+ expect(toolDelta.toolCallId).toBe(toolStart.toolCallId);
600+ expect(toolEnd.toolCallId).toBe(toolStart.toolCallId);
601+ expect(toolDelta.result.content).toEqual([
602+ { type: "text", text: "partial output" },
603+ ]);
604+ expect(toolEnd.result.content).toEqual([
605+ { type: "text", text: "final output" },
606+ ]);
607+
608+ const startIndex = events.findIndex((event) => event.type === "tool_start");
609+ const deltaIndex = events.findIndex((event) => event.type === "tool_delta");
610+ const endIndex = events.findIndex((event) => event.type === "tool_end");
611+ expect(startIndex).toBeLessThan(deltaIndex);
612+ expect(deltaIndex).toBeLessThan(endIndex);
613+ });
614+
535615 test("interrupt preserves partial response", async () => {
536616 faux.setResponses([
537617 fauxAssistantMessage("This response will be interrupted"),
src/agent.ts+37−4
@@ -32,10 +32,14 @@ import type { ToolExecResult } from "./tools.ts";
3232 * Called by the agent loop when the model invokes a tool. Arguments are
3333 * the JSON object parsed by pi-ai from the model's tool call.
3434 */
35+/** Callback used by tool handlers to report progressive output updates. */
36+export type ToolUpdateCallback = (result: ToolExecResult) => void;
37+
3538 export type ToolHandler = (
3639 args: Record<string, unknown>,
3740 cwd: string,
3841 signal?: AbortSignal,
42+ onUpdate?: ToolUpdateCallback,
3943 ) => Promise<ToolExecResult> | ToolExecResult;
4044
4145 export type { ToolExecResult };
@@ -44,8 +48,24 @@ export type { ToolExecResult };
4448 export type AgentEvent =
4549 | { type: "text_delta"; delta: string }
4650 | { type: "thinking_delta"; delta: string }
47- | { type: "tool_start"; name: string; args: Record<string, unknown> }
48- | { type: "tool_end"; name: string; result: ToolExecResult }
51+ | {
52+ type: "tool_start";
53+ toolCallId: string;
54+ name: string;
55+ args: Record<string, unknown>;
56+ }
57+ | {
58+ type: "tool_delta";
59+ toolCallId: string;
60+ name: string;
61+ result: ToolExecResult;
62+ }
63+ | {
64+ type: "tool_end";
65+ toolCallId: string;
66+ name: string;
67+ result: ToolExecResult;
68+ }
4969 | { type: "done"; message: AssistantMessage }
5070 | { type: "error"; message: AssistantMessage }
5171 | { type: "aborted"; message: AssistantMessage };
@@ -286,13 +306,26 @@ export async function runAgentLoop(
286306 } else {
287307 onEvent?.({
288308 type: "tool_start",
309+ toolCallId: toolCall.id,
289310 name: toolCall.name,
290311 args: toolCall.arguments,
291312 });
292313
293- result = await handler(toolCall.arguments, cwd, signal);
314+ result = await handler(toolCall.arguments, cwd, signal, (partial) => {
315+ onEvent?.({
316+ type: "tool_delta",
317+ toolCallId: toolCall.id,
318+ name: toolCall.name,
319+ result: partial,
320+ });
321+ });
294322
295- onEvent?.({ type: "tool_end", name: toolCall.name, result });
323+ onEvent?.({
324+ type: "tool_end",
325+ toolCallId: toolCall.id,
326+ name: toolCall.name,
327+ result,
328+ });
296329 }
297330
298331 const toolResultMessage: ToolResultMessage = {
src/index.ts+5−6
@@ -198,12 +198,11 @@ const BUILTIN_HANDLERS: Record<string, ToolHandler> = {
198198 },
199199 cwd,
200200 ),
201- shell: (args, cwd, signal) =>
202- executeShell(
203- { command: args.command as string },
204- cwd,
205- signal ? { signal } : undefined,
206- ),
201+ shell: (args, cwd, signal, onUpdate) =>
202+ executeShell({ command: args.command as string }, cwd, {
203+ ...(signal ? { signal } : {}),
204+ ...(onUpdate ? { onUpdate } : {}),
205+ }),
207206 readImage: (args, cwd) =>
208207 executeReadImage({ path: args.path as string }, cwd),
209208 };
src/tools.test.ts+21−0
@@ -256,6 +256,27 @@ describe("shell", () => {
256256 expect(text).toContain("out");
257257 expect(text).toContain("err");
258258 });
259+
260+ test("reports progressive output updates while a command runs", async () => {
261+ const updates: string[] = [];
262+
263+ const result = await executeShell(
264+ {
265+ command: "printf 'first\n'; sleep 0.05; printf 'second\n'",
266+ },
267+ tmp,
268+ {
269+ onUpdate: (partial) => {
270+ updates.push(resultText(partial));
271+ },
272+ },
273+ );
274+
275+ expect(result.isError).toBe(false);
276+ expect(updates.length).toBeGreaterThan(0);
277+ expect(updates.some((text) => text.includes("first"))).toBe(true);
278+ expect(updates.at(-1)).toContain("second");
279+ });
259280 });
260281
261282 // ---------------------------------------------------------------------------
src/tools.ts+64−18
@@ -13,6 +13,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
1313 import { dirname, extname, isAbsolute, join } from "node:path";
1414 import type { ImageContent, TextContent, Tool } from "@mariozechner/pi-ai";
1515 import { Type } from "@mariozechner/pi-ai";
16+import type { ToolUpdateCallback } from "./agent.ts";
1617
1718 // ---------------------------------------------------------------------------
1819 // Result type
@@ -125,10 +126,48 @@ export interface ShellOpts {
125126 maxLines?: number;
126127 /** Abort signal to cancel the command. */
127128 signal?: AbortSignal;
129+ /** Callback for progressive output updates while the command is running. */
130+ onUpdate?: ToolUpdateCallback;
128131 }
129132
130133 const DEFAULT_MAX_LINES = 1000;
131134
135+/** Format combined stdout/stderr for display in tool results. */
136+function formatShellOutput(stdout: string, stderr: string): string {
137+ if (stdout && stderr) {
138+ return `${stdout}\n\n[stderr]\n${stderr}`;
139+ }
140+ if (stdout) {
141+ return stdout;
142+ }
143+ if (stderr) {
144+ return `[stderr]\n${stderr}`;
145+ }
146+ return "";
147+}
148+
149+/** Read a spawned shell stream into a string, reporting progressive updates. */
150+async function consumeShellStream(
151+ stream: ReadableStream<Uint8Array>,
152+ onChunk: (chunk: string) => void,
153+): Promise<string> {
154+ const reader = stream.getReader();
155+ const decoder = new TextDecoder();
156+ let output = "";
157+
158+ while (true) {
159+ const { done, value } = await reader.read();
160+ if (done) {
161+ output += decoder.decode();
162+ return output;
163+ }
164+
165+ const chunk = decoder.decode(value, { stream: true });
166+ output += chunk;
167+ onChunk(chunk);
168+ }
169+}
170+
132171 /**
133172 * Run a command in the user's shell.
134173 *
@@ -138,7 +177,7 @@ const DEFAULT_MAX_LINES = 1000;
138177 *
139178 * @param args - Shell arguments (command).
140179 * @param cwd - Working directory to run the command in.
141- * @param opts - Optional execution options (maxLines, signal).
180+ * @param opts - Optional execution options (maxLines, signal, onUpdate).
142181 * @returns A {@link ToolExecResult} with the command output.
143182 */
144183 export async function executeShell(
@@ -158,25 +197,32 @@ export async function executeShell(
158197 if (opts?.signal) spawnOpts.signal = opts.signal;
159198 const proc = Bun.spawn([shell, "-c", args.command], spawnOpts);
160199
161- const [stdoutBuf, stderrBuf] = await Promise.all([
162- new Response(proc.stdout as ReadableStream).text(),
163- new Response(proc.stderr as ReadableStream).text(),
200+ let stdoutBuf = "";
201+ let stderrBuf = "";
202+ const reportUpdate = (): void => {
203+ const output = formatShellOutput(stdoutBuf, stderrBuf);
204+ if (!output) {
205+ return;
206+ }
207+ opts?.onUpdate?.(textResult(output, false));
208+ };
209+
210+ const [stdout, stderr, exitCode] = await Promise.all([
211+ consumeShellStream(proc.stdout as ReadableStream<Uint8Array>, (chunk) => {
212+ stdoutBuf += chunk;
213+ reportUpdate();
214+ }),
215+ consumeShellStream(proc.stderr as ReadableStream<Uint8Array>, (chunk) => {
216+ stderrBuf += chunk;
217+ reportUpdate();
218+ }),
219+ proc.exited,
164220 ]);
165- const exitCode = await proc.exited;
166-
167- const stdout = stdoutBuf.trimEnd();
168- const stderr = stderrBuf.trimEnd();
169-
170- let output = "";
171- if (stdout && stderr) {
172- output = `${stdout}\n\n[stderr]\n${stderr}`;
173- } else if (stdout) {
174- output = stdout;
175- } else if (stderr) {
176- output = `[stderr]\n${stderr}`;
177- }
178221
179- output = truncateOutput(output, maxLines);
222+ const output = truncateOutput(
223+ formatShellOutput(stdout.trimEnd(), stderr.trimEnd()),
224+ maxLines,
225+ );
180226
181227 const isError = exitCode !== 0;
182228 const prefix = isError ? `Command failed with exit code ${exitCode}\n` : "";
src/ui.test.ts+77−1
@@ -4,13 +4,14 @@ import {
44 fauxAssistantMessage,
55 fauxText,
66 fauxThinking,
7+ registerFauxProvider,
78 } from "@mariozechner/pi-ai";
89 import {
910 type AppState,
1011 DEFAULT_SHOW_REASONING,
1112 DEFAULT_VERBOSE,
1213 } from "./index.ts";
13-import { createSession, openDatabase } from "./session.ts";
14+import { createSession, loadMessages, openDatabase } from "./session.ts";
1415 import { DEFAULT_THEME } from "./theme.ts";
1516 import {
1617 buildConversationLog,
@@ -71,6 +72,20 @@ function createTestState(): AppState {
7172 };
7273 }
7374
75+async function waitFor(
76+ predicate: () => boolean,
77+ timeoutMs = 1_000,
78+): Promise<void> {
79+ const deadline = Date.now() + timeoutMs;
80+ while (Date.now() < deadline) {
81+ if (predicate()) {
82+ return;
83+ }
84+ await Bun.sleep(10);
85+ }
86+ throw new Error("Timed out waiting for condition");
87+}
88+
7489 describe("ui rendering", () => {
7590 test("reasoning defaults on and verbose defaults off", () => {
7691 expect(DEFAULT_SHOW_REASONING).toBe(true);
@@ -109,10 +124,12 @@ describe("ui rendering", () => {
109124 test("renderStreamingResponse keeps text and tool output inside one top-level container", () => {
110125 const pendingToolCalls: PendingToolCall[] = [
111126 {
127+ toolCallId: "tool-1",
112128 name: "shell",
113129 args: { command: "echo hi" },
114130 resultText: "hi",
115131 isError: false,
132+ done: true,
116133 },
117134 ];
118135
@@ -150,6 +167,31 @@ describe("ui rendering", () => {
150167 expect(text).toContain("Reasoning in progress");
151168 });
152169
170+ test("renderStreamingResponse shows partial tool output before the tool finishes", () => {
171+ const node = renderStreamingResponse(
172+ {
173+ text: "",
174+ thinking: "",
175+ pendingToolCalls: [
176+ {
177+ toolCallId: "tool-1",
178+ name: "shell",
179+ args: { command: "echo hi" },
180+ resultText: "partial output",
181+ isError: false,
182+ done: false,
183+ },
184+ ],
185+ },
186+ RENDER_OPTS,
187+ );
188+ const text = collectText(node);
189+
190+ expect(text).toContain("$ echo hi");
191+ expect(text).toContain("partial output");
192+ expect(text).toContain("Running...");
193+ });
194+
153195 test("/help appends a persisted UI message to the conversation log", () => {
154196 const state = createTestState();
155197
@@ -169,6 +211,40 @@ describe("ui rendering", () => {
169211 }
170212 });
171213
214+ test("completed assistant messages remain visible after a turn finishes", async () => {
215+ const faux = registerFauxProvider();
216+ const state = createTestState();
217+ const originalPath = process.env.PATH;
218+ process.env.PATH = `${process.env.PATH ?? ""}:/usr/bin:/bin`;
219+ state.cwd = process.cwd();
220+ state.canonicalCwd = process.cwd();
221+ state.model = faux.getModel();
222+ faux.setResponses([fauxAssistantMessage("Done.")]);
223+
224+ try {
225+ handleInput("hello", state);
226+ await waitFor(() =>
227+ loadMessages(state.db, state.session.id).some(
228+ (message) => message.role === "assistant",
229+ ),
230+ );
231+
232+ expect(
233+ state.messages.some((message) => message.role === "assistant"),
234+ ).toBe(true);
235+ const logText = collectText({
236+ type: "vstack",
237+ props: {},
238+ children: buildConversationLog(state),
239+ });
240+ expect(logText).toContain("Done.");
241+ } finally {
242+ process.env.PATH = originalPath;
243+ faux.unregister();
244+ state.db.close();
245+ }
246+ });
247+
172248 test("buildHelpText includes current reasoning and verbose state", () => {
173249 const helpState: HelpRenderState = {
174250 providers: new Map(),
src/ui.ts+119−32
@@ -105,19 +105,23 @@ let isStreaming = false;
105105 /**
106106 * A tool call observed during streaming, before it lands in history.
107107 *
108- * Stores the tool name and arguments from `tool_start`, and the
109- * result text from `tool_end` (filled in when the tool finishes).
108+ * Stores the tool name and arguments from `tool_start`, progressive
109+ * text updates from `tool_delta`, and the final result from `tool_end`.
110110 */
111111 /** A pending tool call shown in the streaming tail. */
112112 export interface PendingToolCall {
113+ /** Tool call id from the assistant message. */
114+ toolCallId: string;
113115 /** Tool name. */
114116 name: string;
115117 /** Tool call arguments. */
116118 args: Record<string, unknown>;
117- /** Text result, or `null` while still running. */
118- resultText: string | null;
119+ /** Progressive text output captured so far. */
120+ resultText: string;
119121 /** Whether the tool result was an error. */
120122 isError: boolean;
123+ /** Whether the tool has finished. */
124+ done: boolean;
121125 }
122126
123127 /** Render options shared by completed and streaming assistant content. */
@@ -536,6 +540,16 @@ function renderToolBlock(lines: readonly ToolRenderLine[], theme: Theme): Node {
536540 ]);
537541 }
538542
543+/** Extract text blocks from a tool result for UI rendering. */
544+function getToolResultText(
545+ result: Extract<AgentEvent, { type: "tool_delta" | "tool_end" }>["result"],
546+): string {
547+ return result.content
548+ .filter((content): content is TextContent => content.type === "text")
549+ .map((content) => content.text)
550+ .join("\n");
551+}
552+
539553 /** Render a shell tool call with left border. */
540554 function renderShellToolCall(
541555 command: string,
@@ -629,6 +643,85 @@ export function renderToolResult(
629643 // Streaming response rendering
630644 // ---------------------------------------------------------------------------
631645
646+/** Render a pending tool call, including progressive output when available. */
647+function renderPendingToolCall(
648+ toolCall: PendingToolCall,
649+ opts: Pick<ConversationRenderOpts, "verbose" | "theme">,
650+): Node {
651+ const runningLine: ToolRenderLine = {
652+ kind: "summary",
653+ text: "Running...",
654+ };
655+
656+ if (toolCall.resultText) {
657+ if (toolCall.name === "shell") {
658+ return renderToolBlock(
659+ [
660+ ...buildShellToolLines(
661+ toolCall.args.command as string,
662+ toolCall.resultText,
663+ opts.verbose,
664+ ),
665+ ...(toolCall.done ? [] : [runningLine]),
666+ ],
667+ opts.theme,
668+ );
669+ }
670+
671+ if (toolCall.name === "edit") {
672+ return renderToolBlock(
673+ [
674+ { kind: "path", text: `~ ${String(toolCall.args.path ?? "")}` },
675+ ...previewToolRenderLines(
676+ splitToolTextLines(
677+ toolCall.resultText,
678+ toolCall.isError ? "error" : "text",
679+ ),
680+ opts.verbose,
681+ ),
682+ ...(toolCall.done ? [] : [runningLine]),
683+ ],
684+ opts.theme,
685+ );
686+ }
687+
688+ return renderToolBlock(
689+ [
690+ { kind: "toolName", text: toolCall.name },
691+ ...splitToolTextLines(
692+ toolCall.resultText,
693+ toolCall.isError ? "error" : "text",
694+ ),
695+ ...(toolCall.done ? [] : [runningLine]),
696+ ],
697+ opts.theme,
698+ );
699+ }
700+
701+ const label =
702+ toolCall.name === "shell"
703+ ? `$ ${toolCall.args.command ?? ""}`
704+ : toolCall.name === "edit"
705+ ? `~ ${toolCall.args.path ?? ""}`
706+ : toolCall.name;
707+
708+ return renderToolBlock(
709+ [
710+ {
711+ kind:
712+ toolCall.name === "shell"
713+ ? "command"
714+ : toolCall.name === "edit"
715+ ? "path"
716+ : "toolName",
717+ text: label,
718+ },
719+ ...(toolCall.done ? [] : [runningLine]),
720+ ],
721+ opts.theme,
722+ );
723+}
724+
632725 /**
633726 * Render the in-progress streaming response.
634727 *
@@ -656,28 +749,8 @@ export function renderStreamingResponse(
656749 children.push(...renderMarkdownContent(streaming.text));
657750 }
658751
659- for (const tc of streaming.pendingToolCalls) {
660- if (tc.resultText !== null) {
661- children.push(
662- renderToolResult(tc.name, tc.args, tc.resultText, tc.isError, opts),
663- );
664- } else {
665- // Tool still running — show indicator
666- const label =
667- tc.name === "shell"
668- ? `$ ${tc.args.command ?? ""}…`
669- : tc.name === "edit"
670- ? `~ ${tc.args.path ?? ""}…`
671- : `${tc.name}…`;
672- children.push(
673- HStack({ padding: { x: 1 } }, [
674- Text("│ ", { fgColor: opts.theme.toolBorder }),
675- VStack({ flex: 1 }, [
676- Text(label, { fgColor: "color06", italic: true }),
677- ]),
678- ]),
679- );
680- }
752+ for (const toolCall of streaming.pendingToolCalls) {
753+ children.push(renderPendingToolCall(toolCall, opts));
681754 }
682755
683756 if (children.length === 0) {
@@ -1439,6 +1512,7 @@ async function submitMessage(text: string, state: AppState): Promise<void> {
14391512 signal: state.abortController.signal,
14401513 onEvent: (event) => handleAgentEvent(event, state),
14411514 });
1515+ state.messages = loadMessages(state.db, state.session.id);
14421516 state.stats = computeStats(state.messages);
14431517 } finally {
14441518 state.running = false;
@@ -1475,25 +1549,38 @@ function handleAgentEvent(event: AgentEvent, state: AppState): void {
14751549 streamingText = "";
14761550 streamingThinking = "";
14771551 pendingToolCalls.push({
1552+ toolCallId: event.toolCallId,
14781553 name: event.name,
14791554 args: event.args,
1480- resultText: null,
1555+ resultText: "",
14811556 isError: false,
1557+ done: false,
14821558 });
14831559 stickToBottom = true;
14841560 cel.render();
14851561 break;
14861562
1563+ case "tool_delta": {
1564+ const pending = pendingToolCalls.find(
1565+ (toolCall) => toolCall.toolCallId === event.toolCallId,
1566+ );
1567+ if (pending) {
1568+ pending.resultText = getToolResultText(event.result);
1569+ pending.isError = event.result.isError;
1570+ }
1571+ stickToBottom = true;
1572+ cel.render();
1573+ break;
1574+ }
1575+
14871576 case "tool_end": {
14881577 const pending = pendingToolCalls.find(
1489- (tc) => tc.name === event.name && tc.resultText === null,
1578+ (toolCall) => toolCall.toolCallId === event.toolCallId,
14901579 );
14911580 if (pending) {
1492- pending.resultText = event.result.content
1493- .filter((c) => c.type === "text")
1494- .map((c) => (c as TextContent).text)
1495- .join("\n");
1581+ pending.resultText = getToolResultText(event.result);
14961582 pending.isError = event.result.isError;
1583+ pending.done = true;
14971584 }
14981585 stickToBottom = true;
14991586 cel.render();