xonecas.io
64875
Mc

mini-coder / commit 8a9b99d

fix: stream reasoning chronologically

xonecas2026-03-14 8a9b99d5a892ce9846772c72fd5b43fc80e8763a parent e38d798

5 files changed

TODO.md+2−0
@@ -9,6 +9,8 @@ Update: reasoning is now all dumped at turn end.
99 The issue is not fixed, it's just suppressed.
1010 This seems like an issue on how we are parsing stream events, and not recognzing tool calls from other events.
1111
12+neither pi or opencode have this bug with the same provider, and opencode uses the same sdks as we do
13+
1214 Relevant reasoning output:
1315
1416 ```
src/cli/live-reasoning.ts+42−0
@@ -0,0 +1,42 @@
1+import * as c from "yoctocolors";
2+import { G, writeln } from "./output.ts";
3+
4+export class LiveReasoningBlock {
5+ private blockOpen = false;
6+ private pending = "";
7+
8+ append(delta: string): void {
9+ if (!delta) return;
10+ this.openBlock();
11+ this.pending += delta;
12+ this.flushCompleteLines();
13+ }
14+
15+ finish(): void {
16+ if (!this.blockOpen) return;
17+ if (this.pending.length > 0) {
18+ this.writeLine(this.pending);
19+ this.pending = "";
20+ }
21+ this.blockOpen = false;
22+ }
23+
24+ private openBlock(): void {
25+ if (this.blockOpen) return;
26+ writeln(`${G.info} ${c.dim("reasoning")}`);
27+ this.blockOpen = true;
28+ }
29+
30+ private flushCompleteLines(): void {
31+ let boundary = this.pending.indexOf("\n");
32+ while (boundary !== -1) {
33+ this.writeLine(this.pending.slice(0, boundary));
34+ this.pending = this.pending.slice(boundary + 1);
35+ boundary = this.pending.indexOf("\n");
36+ }
37+ }
38+
39+ private writeLine(line: string): void {
40+ writeln(` ${c.dim(line)}`);
41+ }
42+}
src/cli/stream-render-content.ts+6−4
@@ -36,16 +36,18 @@ export class StreamRenderContent {
3636 this.streamPartialRemainder();
3737 }
3838
39- appendReasoningDelta(delta: string): void {
40- if (!delta) return;
39+ appendReasoningDelta(delta: string): string {
40+ if (!delta) return "";
41+ let appended = delta;
4142 if (
4243 this.accumulatedReasoning.endsWith("**") &&
4344 delta.startsWith("**") &&
4445 !this.accumulatedReasoning.endsWith("\n")
4546 ) {
46- this.accumulatedReasoning += "\n";
47+ appended = `\n${delta}`;
4748 }
48- this.accumulatedReasoning += delta;
49+ this.accumulatedReasoning += appended;
50+ return appended;
4951 }
5052
5153 flushOpenContent(): void {
src/cli/stream-render.test.ts+42−5
@@ -308,7 +308,7 @@ describe("renderTurn", () => {
308308 expect(result.reasoningText).toBe(" hello\n\nworld");
309309 });
310310
311- test("renders reasoning in a structured block and accumulates it", async () => {
311+ test("streams reasoning in a structured block and accumulates it", async () => {
312312 captureStdout();
313313
314314 const result = await renderTurn(
@@ -316,8 +316,6 @@ describe("renderTurn", () => {
316316 new Spinner(),
317317 );
318318
319- // The partial reasoning text is streamed raw and then overwritten on
320- // turn-end with the properly styled (dimmed) version.
321319 expect(simulateTerminal(stdout)).toBe("· reasoning\n thinking\n");
322320 expect(hasAnsi(stdout, "[2m")).toBe(true);
323321 expect(result.reasoningText).toBe("thinking");
@@ -341,7 +339,7 @@ describe("renderTurn", () => {
341339 expect(result.reasoningText).toBe("**Planning**\n**Confirming**");
342340 });
343341
344- test("renders reasoning after assistant text for a stable final layout", async () => {
342+ test("renders reasoning before assistant text to preserve chronology", async () => {
345343 captureStdout();
346344
347345 await renderTurn(
@@ -353,7 +351,46 @@ describe("renderTurn", () => {
353351 new Spinner(),
354352 );
355353
356- expect(simulateTerminal(stdout)).toBe("◆ answer\n· reasoning\n step\n");
354+ expect(simulateTerminal(stdout)).toBe("· reasoning\n step\n◆ answer\n");
355+ });
356+
357+ test("starts a new reasoning block after tool activity", async () => {
358+ captureStdout();
359+
360+ await renderTurn(
361+ eventsFrom([
362+ { type: "reasoning-delta", delta: "plan" },
363+ {
364+ type: "tool-call-start",
365+ toolName: "shell",
366+ toolCallId: "tool-1",
367+ args: { command: "echo hi" },
368+ },
369+ {
370+ type: "tool-result",
371+ toolName: "shell",
372+ toolCallId: "tool-1",
373+ isError: false,
374+ result: {
375+ stdout: "hi",
376+ stderr: "",
377+ exitCode: 0,
378+ success: true,
379+ timedOut: false,
380+ streamedOutput: false,
381+ },
382+ },
383+ { type: "reasoning-delta", delta: "done" },
384+ done(),
385+ ]),
386+ new Spinner(),
387+ );
388+
389+ const plain = strip(stdout);
390+ expect(countOccurrences(plain, "· reasoning")).toBe(2);
391+ expect(plain).toContain("plan");
392+ expect(plain).toContain("$ echo hi");
393+ expect(plain).toContain("done");
357394 });
358395
359396 test("stops spinner defensively before each rendered line", async () => {
src/cli/stream-render.ts+23−16
@@ -2,6 +2,7 @@ import * as c from "yoctocolors";
22 import { buildAbortMessages, isAbortError } from "../agent/agent-helpers.ts";
33 import type { CoreMessage } from "../llm-api/turn.ts";
44 import type { TurnEvent } from "../llm-api/types.ts";
5+import { LiveReasoningBlock } from "./live-reasoning.ts";
56 import { G, RenderedError, renderError, writeln } from "./output.ts";
67 import {
78 normalizeReasoningDelta,
@@ -24,12 +25,14 @@ export async function renderTurn(
2425 }> {
2526 const showReasoning = opts?.showReasoning ?? true;
2627 const content = new StreamRenderContent(spinner);
28+ const liveReasoning = new LiveReasoningBlock();
2729
2830 let inputTokens = 0;
2931 let outputTokens = 0;
3032 let contextTokens = 0;
3133 let newMessages: CoreMessage[] = [];
3234 const startedToolCalls = new Set<string>();
35+ let renderedVisibleOutput = false;
3336
3437 let reasoningComputed = false;
3538 let reasoningText = "";
@@ -41,27 +44,25 @@ export async function renderTurn(
4144 return reasoningText;
4245 };
4346
44- const renderReasoningBlock = (): boolean => {
45- if (!showReasoning) return false;
46- const text = getReasoningText();
47- if (!text) return false;
48- writeln(`${G.info} ${c.dim("reasoning")}`);
49- for (const line of text.split("\n")) {
50- writeln(` ${c.dim(line)}`);
51- }
52- return true;
53- };
54-
5547 for await (const event of events) {
5648 switch (event.type) {
5749 case "text-delta": {
50+ liveReasoning.finish();
5851 content.appendTextDelta(event.delta);
52+ if (event.delta) renderedVisibleOutput = true;
5953 break;
6054 }
6155 case "reasoning-delta": {
62- const delta = normalizeReasoningDelta(event.delta);
63- content.appendReasoningDelta(delta);
56+ content.flushOpenContent();
57+ const delta = content.appendReasoningDelta(
58+ normalizeReasoningDelta(event.delta),
59+ );
6460 reasoningComputed = false;
61+ if (showReasoning && delta) {
62+ spinner.stop();
63+ liveReasoning.append(delta);
64+ renderedVisibleOutput = true;
65+ }
6566 break;
6667 }
6768
@@ -70,9 +71,11 @@ export async function renderTurn(
7071 break;
7172 }
7273 startedToolCalls.add(event.toolCallId);
74+ liveReasoning.finish();
7375 content.flushOpenContent();
7476 spinner.stop();
7577 renderToolCall(event.toolName, event.args);
78+ renderedVisibleOutput = true;
7679
7780 spinner.start(event.toolName);
7881 break;
@@ -80,29 +83,32 @@ export async function renderTurn(
8083
8184 case "tool-result": {
8285 startedToolCalls.delete(event.toolCallId);
86+ liveReasoning.finish();
8387 spinner.stop();
8488 renderToolResult(event.toolName, event.result, event.isError);
89+ renderedVisibleOutput = true;
8590
8691 spinner.start("thinking");
8792 break;
8893 }
8994
9095 case "context-pruned": {
96+ liveReasoning.finish();
9197 content.flushOpenContent();
9298 spinner.stop();
9399 const removedKb = (event.removedBytes / 1024).toFixed(1);
94100 writeln(
95101 `${G.info} ${c.dim("context pruned")} ${c.dim(event.mode)} ${c.dim(`–${event.removedMessageCount} messages`)} ${c.dim(`–${removedKb} KB`)}`,
96102 );
103+ renderedVisibleOutput = true;
97104 break;
98105 }
99106
100107 case "turn-complete": {
101- const hadContent = content.hasOpenContent();
108+ liveReasoning.finish();
102109 content.flushOpenContent();
103110 spinner.stop();
104- const renderedReasoning = renderReasoningBlock();
105- if (!hadContent && !renderedReasoning) writeln();
111+ if (!renderedVisibleOutput) writeln();
106112 inputTokens = event.inputTokens;
107113 outputTokens = event.outputTokens;
108114 contextTokens = event.contextTokens;
@@ -111,6 +117,7 @@ export async function renderTurn(
111117 }
112118
113119 case "turn-error": {
120+ liveReasoning.finish();
114121 content.flushOpenContent();
115122 spinner.stop();
116123 if (isAbortError(event.error)) {