xonecas.io
64875
Mc

mini-coder / commit 20af7c0

fix(ui): stabilize turn-end assistant rendering

xonecas2026-04-07 20af7c0771681671f6f6399cb20b5663ffffcc1e parent e3037e6

5 files changed

TODO.md+0−2
@@ -9,8 +9,6 @@ The spec.md and code are the sources of truth, not this file, don't assume anyth
99
1010 ### Robustness
1111
12-- [ ] **Fix turn-end streaming/render mismatch** (`ui.ts`) — the streamed `Thinking... N lines.` placeholder disappears at turn end and the UI flashes because the in-progress render path does not match the final committed render. Debug the split-brain rendering and make turn completion visually stable.
13-
1412 - [ ] **Catch tool handler exceptions in the agent loop** (`agent.ts`) — if a built-in tool or future extension throws, the loop should convert that into an error tool result, still emit `tool_end`, append a `ToolResultMessage`, and continue or fail cleanly instead of crashing the loop.
1513
1614 - [ ] **Fix the `/undo` abort race** (`ui.ts`) — aborting an active run and undoing immediately can still race with the agent loop writing the aborted assistant message. Track the active loop promise and wait for it to settle before removing the last conversational turn.
src/agent.test.ts+14−0
@@ -326,6 +326,12 @@ describe("agent loop", () => {
326326
327327 const textDeltas = events.filter((e) => e.type === "text_delta");
328328 expect(textDeltas.length).toBeGreaterThan(0);
329+ const lastTextDelta = textDeltas.at(-1);
330+ expect(lastTextDelta).toBeDefined();
331+ if (!lastTextDelta || lastTextDelta.type !== "text_delta") {
332+ throw new Error("Expected a text delta event");
333+ }
334+ expect(lastTextDelta.content).toEqual([fauxText("Hello world")]);
329335
330336 const doneEvents = events.filter((e) => e.type === "done");
331337 expect(doneEvents).toHaveLength(1);
@@ -360,6 +366,14 @@ describe("agent loop", () => {
360366
361367 const thinkingDeltas = events.filter((e) => e.type === "thinking_delta");
362368 expect(thinkingDeltas.length).toBeGreaterThan(0);
369+ const lastThinkingDelta = thinkingDeltas.at(-1);
370+ expect(lastThinkingDelta).toBeDefined();
371+ if (!lastThinkingDelta || lastThinkingDelta.type !== "thinking_delta") {
372+ throw new Error("Expected a thinking delta event");
373+ }
374+ expect(lastThinkingDelta.content).toEqual([
375+ fauxThinking("Need to inspect the failing test."),
376+ ]);
363377 });
364378
365379 test("reconstructs thinking content when the final done message omits it", async () => {
src/agent.ts+34−4
@@ -46,8 +46,16 @@ export type { ToolExecResult };
4646
4747 /** Events emitted during the agent loop for UI updates. */
4848 export type AgentEvent =
49- | { type: "text_delta"; delta: string }
50- | { type: "thinking_delta"; delta: string }
49+ | {
50+ type: "text_delta";
51+ delta: string;
52+ content: AssistantMessage["content"];
53+ }
54+ | {
55+ type: "thinking_delta";
56+ delta: string;
57+ content: AssistantMessage["content"];
58+ }
5159 | { type: "assistant_message"; message: AssistantMessage }
5260 | {
5361 type: "tool_start";
@@ -110,6 +118,20 @@ export interface AgentLoopResult {
110118 stopReason: "stop" | "length" | "error" | "aborted";
111119 }
112120
121+function cloneAssistantContent(
122+ content: AssistantMessage["content"],
123+): AssistantMessage["content"] {
124+ return content.map((block) => {
125+ if (block.type === "toolCall") {
126+ return {
127+ ...block,
128+ arguments: structuredClone(block.arguments),
129+ };
130+ }
131+ return { ...block };
132+ });
133+}
134+
113135 /** Merge streamed partial assistant content into the final message content. */
114136 function mergeAssistantContent(
115137 partialContent: AssistantMessage["content"],
@@ -239,10 +261,18 @@ export async function runAgentLoop(
239261
240262 switch (event.type) {
241263 case "text_delta":
242- onEvent?.({ type: "text_delta", delta: event.delta });
264+ onEvent?.({
265+ type: "text_delta",
266+ delta: event.delta,
267+ content: cloneAssistantContent(event.partial.content),
268+ });
243269 break;
244270 case "thinking_delta":
245- onEvent?.({ type: "thinking_delta", delta: event.delta });
271+ onEvent?.({
272+ type: "thinking_delta",
273+ delta: event.delta,
274+ content: cloneAssistantContent(event.partial.content),
275+ });
246276 break;
247277 case "toolcall_end":
248278 // Tool calls are collected from the final assistant message
src/ui.test.ts+182−39
@@ -44,7 +44,6 @@ import {
4444 renderBaseLayout,
4545 renderInputArea,
4646 renderStatusBar,
47- renderStreamingResponse,
4847 renderToolResult,
4948 resetUiState,
5049 type ToolRenderLine,
@@ -321,7 +320,25 @@ describe("ui rendering", () => {
321320 expect(thinkingNode.props.fgColor).toBe("color03");
322321 });
323322
324- test("renderStreamingResponse keeps text and tool output inside one top-level container", () => {
323+ test("renderAssistantMessage shows a thinking line-count placeholder when reasoning is hidden", () => {
324+ const message = fauxAssistantMessage([
325+ fauxThinking("line one\nline two\nline three"),
326+ fauxText("Done."),
327+ ]);
328+
329+ const node = renderAssistantMessage(message, {
330+ ...RENDER_OPTS,
331+ showReasoning: false,
332+ });
333+ const text = collectText(node);
334+
335+ expect(text).toContain("Thinking... 3 lines.");
336+ expect(text).toContain("Done.");
337+ expect(text).not.toContain("line one");
338+ expect(text).not.toContain("line two");
339+ });
340+
341+ test("renderAssistantMessage keeps in-progress text and tool output inside one top-level container", () => {
325342 const pendingToolCalls: PendingToolCall[] = [
326343 {
327344 toolCallId: "tool-1",
@@ -333,10 +350,9 @@ describe("ui rendering", () => {
333350 },
334351 ];
335352
336- const node = renderStreamingResponse(
353+ const node = renderAssistantMessage(
337354 {
338- text: "Working...",
339- thinking: "",
355+ content: [fauxText("Working...")],
340356 pendingToolCalls,
341357 },
342358 RENDER_OPTS,
@@ -350,12 +366,10 @@ describe("ui rendering", () => {
350366 expect(node.children.length).toBeGreaterThanOrEqual(2);
351367 });
352368
353- test("renderStreamingResponse shows streaming thinking when reasoning is enabled", () => {
354- const node = renderStreamingResponse(
369+ test("renderAssistantMessage shows in-progress thinking when reasoning is enabled", () => {
370+ const node = renderAssistantMessage(
355371 {
356- text: "",
357- thinking: "Reasoning in progress",
358- pendingToolCalls: [],
372+ content: [fauxThinking("Reasoning in progress")],
359373 },
360374 {
361375 ...RENDER_OPTS,
@@ -367,32 +381,10 @@ describe("ui rendering", () => {
367381 expect(text).toContain("Reasoning in progress");
368382 });
369383
370- test("renderStreamingResponse shows line count indicator when reasoning is off", () => {
371- const node = renderStreamingResponse(
384+ test("renderAssistantMessage shows a 1-line thinking placeholder for in-progress content", () => {
385+ const node = renderAssistantMessage(
372386 {
373- text: "",
374- thinking: "line one\nline two\nline three",
375- pendingToolCalls: [],
376- },
377- {
378- ...RENDER_OPTS,
379- showReasoning: false,
380- },
381- );
382- const text = collectText(node);
383-
384- expect(text).toContain("Thinking... 3 lines.");
385- // Should NOT show actual reasoning content
386- expect(text).not.toContain("line one");
387- expect(text).not.toContain("line two");
388- });
389-
390- test("renderStreamingResponse shows 1 line when thinking has no newlines and reasoning is off", () => {
391- const node = renderStreamingResponse(
392- {
393- text: "",
394- thinking: "some thinking",
395- pendingToolCalls: [],
387+ content: [fauxThinking("some thinking")],
396388 },
397389 {
398390 ...RENDER_OPTS,
@@ -404,11 +396,10 @@ describe("ui rendering", () => {
404396 expect(text).toContain("Thinking... 1 line.");
405397 });
406398
407- test("renderStreamingResponse shows partial tool output before the tool finishes", () => {
408- const node = renderStreamingResponse(
399+ test("renderAssistantMessage shows partial tool output before the tool finishes", () => {
400+ const node = renderAssistantMessage(
409401 {
410- text: "",
411- thinking: "",
402+ content: [],
412403 pendingToolCalls: [
413404 {
414405 toolCallId: "tool-1",
@@ -429,6 +420,158 @@ describe("ui rendering", () => {
429420 expect(text).toContain("Running...");
430421 });
431422
423+ test("committing a streamed response preserves hidden reasoning placeholder order", async () => {
424+ const api = "ui-hidden-reasoning-order-test";
425+ const sourceId = "ui-hidden-reasoning-order-test-source";
426+ const model: Model<string> = {
427+ id: "ui-hidden-reasoning-order-model",
428+ name: "UI Hidden Reasoning Order Model",
429+ api,
430+ provider: "test",
431+ baseUrl: "http://localhost:0",
432+ reasoning: true,
433+ input: ["text"],
434+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
435+ contextWindow: 128000,
436+ maxTokens: 4096,
437+ };
438+
439+ const createFinalMessage = (): AssistantMessage => {
440+ const message = fauxAssistantMessage([
441+ fauxText("Before"),
442+ fauxThinking("line one\nline two"),
443+ fauxText("After"),
444+ ]);
445+ message.api = api;
446+ message.provider = model.provider;
447+ message.model = model.id;
448+ message.usage = {
449+ input: 0,
450+ output: 0,
451+ cacheRead: 0,
452+ cacheWrite: 0,
453+ totalTokens: 0,
454+ cost: {
455+ input: 0,
456+ output: 0,
457+ cacheRead: 0,
458+ cacheWrite: 0,
459+ total: 0,
460+ },
461+ };
462+ message.stopReason = "stop";
463+ message.timestamp = Date.now();
464+ return message;
465+ };
466+
467+ const buildProviderStream = () => {
468+ const stream = createAssistantMessageEventStream();
469+ const finalMessage = createFinalMessage();
470+
471+ queueMicrotask(() => {
472+ stream.push({
473+ type: "text_delta",
474+ contentIndex: 0,
475+ delta: "Before",
476+ partial: {
477+ ...finalMessage,
478+ content: [fauxText("Before")],
479+ },
480+ });
481+ stream.push({
482+ type: "thinking_delta",
483+ contentIndex: 1,
484+ delta: "line one\nline two",
485+ partial: {
486+ ...finalMessage,
487+ content: [fauxText("Before"), fauxThinking("line one\nline two")],
488+ },
489+ });
490+ stream.push({
491+ type: "text_delta",
492+ contentIndex: 2,
493+ delta: "After",
494+ partial: {
495+ ...finalMessage,
496+ content: [
497+ fauxText("Before"),
498+ fauxThinking("line one\nline two"),
499+ fauxText("After"),
500+ ],
501+ },
502+ });
503+ setTimeout(() => {
504+ stream.push({
505+ type: "done",
506+ reason: "stop",
507+ message: finalMessage,
508+ });
509+ stream.end(finalMessage);
510+ }, 50);
511+ });
512+
513+ return stream;
514+ };
515+
516+ registerApiProvider(
517+ {
518+ api,
519+ stream: (_model, _context, _options) => buildProviderStream(),
520+ streamSimple: (_model, _context, _options) => buildProviderStream(),
521+ },
522+ sourceId,
523+ );
524+
525+ const state = createTestState();
526+ state.cwd = process.cwd();
527+ state.canonicalCwd = process.cwd();
528+ state.model = model;
529+ state.showReasoning = false;
530+
531+ try {
532+ handleInput("hello", state);
533+
534+ const streamedLogText: string[] = [];
535+ await waitFor(() => {
536+ if (state.messages.some((message) => message.role === "assistant")) {
537+ return false;
538+ }
539+ const logText = collectText({
540+ type: "vstack",
541+ props: {},
542+ children: buildConversationLog(state),
543+ }).filter(Boolean);
544+ if (
545+ logText.includes("Thinking... 2 lines.") &&
546+ logText.join("").includes("Before") &&
547+ logText.join("").includes("After")
548+ ) {
549+ streamedLogText.splice(0, streamedLogText.length, ...logText);
550+ return true;
551+ }
552+ return false;
553+ });
554+
555+ const streamedText = streamedLogText.join("\n");
556+ expect(streamedText).toBe("hello\nBefore\nThinking... 2 lines.\nAfter");
557+
558+ await waitFor(() =>
559+ state.messages.some((message) => message.role === "assistant"),
560+ );
561+
562+ const committedLogText = collectText({
563+ type: "vstack",
564+ props: {},
565+ children: buildConversationLog(state),
566+ }).filter(Boolean);
567+ expect(committedLogText.join("\n")).toBe(streamedText);
568+ } finally {
569+ await stopRunningTurn(state);
570+ unregisterApiProviders(sourceId);
571+ state.db.close();
572+ }
573+ });
574+
432575 test("/help before the first user message does not create a session", () => {
433576 const state = createTestState();
434577
src/ui.ts+68−101
@@ -27,7 +27,6 @@ import type {
2727 AssistantMessage,
2828 Message,
2929 TextContent,
30- ThinkingContent,
3130 ThinkingLevel,
3231 ToolCall,
3332 UserMessage,
@@ -108,11 +107,8 @@ let dividerTick = 0;
108107 /** Divider animation timer handle. */
109108 let dividerTimer: ReturnType<typeof setInterval> | null = null;
110109
111-/** Streaming text buffer for the current assistant response. */
112-let streamingText = "";
113-
114-/** Streaming thinking buffer for the current assistant response. */
115-let streamingThinking = "";
110+/** Streaming assistant content for the current response. */
111+let streamingContent: AssistantMessage["content"] = [];
116112
117113 /** Whether we are currently streaming a response. */
118114 let isStreaming = false;
@@ -139,7 +135,7 @@ export interface PendingToolCall {
139135 done: boolean;
140136 }
141137
142-/** Render options shared by completed and streaming assistant content. */
138+/** Render options shared by completed and in-progress assistant content. */
143139 export interface ConversationRenderOpts {
144140 /** Whether reasoning blocks are visible. */
145141 showReasoning: boolean;
@@ -149,14 +145,14 @@ export interface ConversationRenderOpts {
149145 theme: Theme;
150146 }
151147
152-/** Display-only assistant content that is still streaming. */
153-export interface StreamingRenderState {
154- /** Streamed markdown text so far. */
155- text: string;
156- /** Streamed thinking text so far. */
157- thinking: string;
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"];
158152 /** Tool calls observed in the current streaming turn. */
159- pendingToolCalls: PendingToolCall[];
153+ pendingToolCalls?: PendingToolCall[];
154+ /** Optional error text appended below the assistant content. */
155+ errorMessage?: string;
160156 }
161157
162158 /** Semantic line kinds used when rendering tool output in the log. */
@@ -211,8 +207,7 @@ export function resetUiState(): void {
211207 inputFocused = true;
212208 dividerTick = 0;
213209 stopDividerAnimation();
214- streamingText = "";
215- streamingThinking = "";
210+ streamingContent = [];
216211 isStreaming = false;
217212 pendingToolCalls = [];
218213 activeOverlay = null;
@@ -486,36 +481,64 @@ function renderMarkdownContent(content: string): Node[] {
486481 });
487482 }
488483
489-/** Render a completed assistant message from history. */
484+/** Render a completed or in-progress assistant response. */
490485 export function renderAssistantMessage(
491- msg: AssistantMessage,
486+ assistant: AssistantMessage | AssistantRenderState,
492487 opts: ConversationRenderOpts,
493488 ): Node | null {
489+ const errorMessage =
490+ "role" in assistant
491+ ? assistant.stopReason === "error"
492+ ? assistant.errorMessage
493+ : undefined
494+ : assistant.errorMessage;
495+ const pendingToolCalls =
496+ "role" in assistant ? [] : (assistant.pendingToolCalls ?? []);
494497 const children: Node[] = [];
495498
496- for (const block of msg.content) {
497- if (block.type === "text" && (block as TextContent).text) {
498- children.push(...renderMarkdownContent((block as TextContent).text));
499- } else if (block.type === "thinking" && opts.showReasoning) {
500- const thinking = (block as ThinkingContent).thinking;
501- if (thinking) {
502- children.push(
503- VStack({ padding: { x: 1 } }, [
504- Text(thinking, {
505- wrap: "word",
506- fgColor: opts.theme.mutedText,
507- italic: true,
508- }),
509- ]),
510- );
511- }
499+ for (const block of assistant.content) {
500+ if (block.type === "text" && block.text) {
501+ children.push(...renderMarkdownContent(block.text));
502+ continue;
503+ }
504+
505+ if (block.type !== "thinking" || !block.thinking) {
506+ continue;
507+ }
508+
509+ if (opts.showReasoning) {
510+ children.push(
511+ VStack({ padding: { x: 1 } }, [
512+ Text(block.thinking, {
513+ wrap: "word",
514+ fgColor: opts.theme.mutedText,
515+ italic: true,
516+ }),
517+ ]),
518+ );
519+ continue;
512520 }
521+
522+ const lineCount = block.thinking.split("\n").length;
523+ const unit = lineCount === 1 ? "line" : "lines";
524+ children.push(
525+ VStack({ padding: { x: 1 } }, [
526+ Text(`Thinking... ${lineCount} ${unit}.`, {
527+ fgColor: opts.theme.mutedText,
528+ italic: true,
529+ }),
530+ ]),
531+ );
532+ }
533+
534+ for (const toolCall of pendingToolCalls) {
535+ children.push(renderPendingToolCall(toolCall, opts));
513536 }
514537
515- if (msg.stopReason === "error" && msg.errorMessage) {
538+ if (errorMessage) {
516539 children.push(
517540 VStack({ padding: { x: 1 } }, [
518- Text(`Error: ${msg.errorMessage}`, {
541+ Text(`Error: ${errorMessage}`, {
519542 fgColor: opts.theme.error,
520543 }),
521544 ]),
@@ -782,7 +805,7 @@ export function renderToolResult(
782805 }
783806
784807 // ---------------------------------------------------------------------------
785-// Streaming response rendering
808+// Streaming tool-call rendering
786809 // ---------------------------------------------------------------------------
787810
788811 /** Render a pending tool call, including progressive output when available. */
@@ -864,57 +887,6 @@ function renderPendingToolCall(
864887 );
865888 }
866889
867-/**
868- * Render the in-progress streaming response.
869- *
870- * Shows thinking (if enabled), streamed markdown, and pending tool calls.
871- */
872-export function renderStreamingResponse(
873- streaming: StreamingRenderState,
874- opts: ConversationRenderOpts,
875-): Node | null {
876- const children: Node[] = [];
877-
878- if (streaming.thinking) {
879- if (opts.showReasoning) {
880- children.push(
881- VStack({ padding: { x: 1 } }, [
882- Text(streaming.thinking, {
883- wrap: "word",
884- fgColor: opts.theme.mutedText,
885- italic: true,
886- }),
887- ]),
888- );
889- } else {
890- const lineCount = streaming.thinking.split("\n").length;
891- const unit = lineCount === 1 ? "line" : "lines";
892- children.push(
893- VStack({ padding: { x: 1 } }, [
894- Text(`Thinking... ${lineCount} ${unit}.`, {
895- fgColor: opts.theme.mutedText,
896- italic: true,
897- }),
898- ]),
899- );
900- }
901- }
902-
903- if (streaming.text) {
904- children.push(...renderMarkdownContent(streaming.text));
905- }
906-
907- for (const toolCall of streaming.pendingToolCalls) {
908- children.push(renderPendingToolCall(toolCall, opts));
909- }
910-
911- if (children.length === 0) {
912- return null;
913- }
914-
915- return VStack({}, children);
916-}
917-
918890 // ---------------------------------------------------------------------------
919891 // Conversation log
920892 // ---------------------------------------------------------------------------
@@ -982,10 +954,9 @@ export function buildConversationLog(state: AppState): Node[] {
982954 // Append in-progress streaming response
983955 if (isStreaming) {
984956 pushConversationNode(
985- renderStreamingResponse(
957+ renderAssistantMessage(
986958 {
987- text: streamingText,
988- thinking: streamingThinking,
959+ content: streamingContent,
989960 pendingToolCalls,
990961 },
991962 renderOpts,
@@ -2065,8 +2036,7 @@ async function submitMessage(
20652036 state.running = true;
20662037 state.abortController = new AbortController();
20672038 isStreaming = true;
2068- streamingText = "";
2069- streamingThinking = "";
2039+ streamingContent = [];
20702040 pendingToolCalls = [];
20712041 startDividerAnimation();
20722042 cel.render();
@@ -2093,8 +2063,7 @@ async function submitMessage(
20932063 state.running = false;
20942064 state.abortController = null;
20952065 isStreaming = false;
2096- streamingText = "";
2097- streamingThinking = "";
2066+ streamingContent = [];
20982067 pendingToolCalls = [];
20992068 stopDividerAnimation();
21002069 cel.render();
@@ -2105,13 +2074,13 @@ async function submitMessage(
21052074 function handleAgentEvent(event: AgentEvent, state: AppState): void {
21062075 switch (event.type) {
21072076 case "text_delta":
2108- streamingText += event.delta;
2077+ streamingContent = event.content;
21092078 stickToBottom = true;
21102079 cel.render();
21112080 break;
21122081
21132082 case "thinking_delta":
2114- streamingThinking += event.delta;
2083+ streamingContent = event.content;
21152084 stickToBottom = true;
21162085 cel.render();
21172086 break;
@@ -2119,8 +2088,7 @@ function handleAgentEvent(event: AgentEvent, state: AppState): void {
21192088 case "assistant_message":
21202089 state.messages.push(event.message);
21212090 state.stats = computeStats(state.messages);
2122- streamingText = "";
2123- streamingThinking = "";
2091+ streamingContent = [];
21242092 stickToBottom = true;
21252093 cel.render();
21262094 break;
@@ -2177,8 +2145,7 @@ function handleAgentEvent(event: AgentEvent, state: AppState): void {
21772145 case "done":
21782146 case "error":
21792147 case "aborted":
2180- streamingText = "";
2181- streamingThinking = "";
2148+ streamingContent = [];
21822149 pendingToolCalls = [];
21832150 isStreaming = false;
21842151 stickToBottom = true;