@@ -2,20 +2,13 @@ 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 { renderLine } from "./markdown.ts";
6-import { G, RenderedError, renderError, write, writeln } from "./output.ts";
5+import { G, RenderedError, renderError, writeln } from "./output.ts";
76 import {
87 normalizeReasoningDelta,
98 normalizeReasoningText,
109 } from "./reasoning.ts";
1110 import type { Spinner } from "./spinner.ts";
12-import {
13- buildClearPartialPreview,
14- createPartialPreviewTracker,
15- resetPartialPreviewTracker,
16- setStreamPreviewPrefix,
17- streamPartialPreviewDelta,
18-} from "./stream-preview.ts";
11+import { StreamRenderContent } from "./stream-render-content.ts";
1912 import { renderToolCall, renderToolResult } from "./tool-render.ts";
2013
2114 export async function renderTurn(
@@ -30,20 +23,7 @@ export async function renderTurn(
3023 reasoningText: string;
3124 }> {
3225 const showReasoning = opts?.showReasoning ?? true;
33- let inText = false;
34- let inReasoning = false;
35- // rawBuffer holds the current incomplete (no trailing \n) line being built.
36- let rawBuffer = "";
37- // Prefix prepended when overwriting the raw partial with the styled complete
38- // line. For text replies: "◆ " (renderSingleLine output doesn't include it).
39- // For reasoning: "" (renderSingleLine already includes "│ " in its output).
40- let styledPrefix = "";
41- const partialPreview = createPartialPreviewTracker();
42- let accumulatedText = "";
43- let accumulatedReasoning = "";
44-
45- let inFence = false;
46- let reasoningBlankLineRun = 0;
26+ const content = new StreamRenderContent(spinner);
4727
4828 let inputTokens = 0;
4929 let outputTokens = 0;
@@ -51,176 +31,15 @@ export async function renderTurn(
5131 let newMessages: CoreMessage[] = [];
5232 const startedToolCalls = new Set<string>();
5333
54- /**
55- * Render a single raw line, updating shared fence/blank-run state.
56- * Returns the rendered string, or null if the line should be suppressed
57- * (e.g. a second consecutive blank line inside a reasoning block).
58- */
59- function renderSingleLine(raw: string): string | null {
60- const source = inReasoning ? raw.replace(/[ \t]+$/g, "") : raw;
61- if (inReasoning && source.trim() === "") {
62- reasoningBlankLineRun += 1;
63- if (reasoningBlankLineRun > 1) return null;
64- } else if (inReasoning) {
65- reasoningBlankLineRun = 0;
66- }
67-
68- if (inReasoning) {
69- return ` ${c.dim(c.italic(source))}`;
70- }
71- const rendered = renderLine(source, inFence);
72- inFence = rendered.inFence;
73- return rendered.output;
74- }
75-
76- // Reset per-line partial-preview tracking. styledPrefix is intentionally
77- // excluded — it is turn-level state (◆ for text, "" for reasoning) and must
78- // persist across lines within the same turn.
79- function resetLineState(): void {
80- resetPartialPreviewTracker(partialPreview);
81- }
82-
83- /**
84- * Flush the trailing partial line (rawBuffer) and write a newline.
85- * If a partial-line preview was already written to the terminal, overwrite
86- * it with the properly markdown-rendered version first.
87- */
88- function flushAnyText(): void {
89- if (!inText && !inReasoning) return;
90-
91- if (rawBuffer) {
92- spinner.stop();
93- const out = renderSingleLine(rawBuffer);
94- rawBuffer = "";
95- if (partialPreview.partialWritten > 0) {
96- // Raw partial content is on the terminal — clear wrapped rows and
97- // replace it with the properly styled version.
98- const clearSeq = buildClearPartialPreview(
99- partialPreview,
100- process.stdout.columns ?? 0,
101- );
102- if (out !== null) write(`${clearSeq}${styledPrefix}${out}`);
103- else write(clearSeq);
104- } else {
105- if (out !== null) write(out);
106- }
107- }
108- writeln();
109- inText = false;
110- inReasoning = false;
111- inFence = false; // reasoning is never markdown; reset fence state at boundary
112- reasoningBlankLineRun = 0;
113- styledPrefix = "";
114- resetLineState();
115- }
116-
117- /**
118- * Process rawBuffer: render and output all complete (newline-terminated)
119- * lines; leave any trailing partial in rawBuffer.
120- * If a partial-line preview was already written, the first complete line
121- * clears it before writing styled content.
122- */
123- function flushCompleteLines(): void {
124- // Use an index cursor instead of repeatedly slicing rawBuffer after each
125- // line — O(n) single scan, single slice at the end.
126- let start = 0;
127- let boundary = rawBuffer.indexOf("\n", start);
128- if (boundary === -1) return;
129-
130- spinner.stop();
131- let batchOutput = "";
132- let firstLine = true;
133-
134- while (boundary !== -1) {
135- const raw = rawBuffer.slice(start, boundary);
136- start = boundary + 1;
137- boundary = rawBuffer.indexOf("\n", start);
138-
139- const out = renderSingleLine(raw);
140- // If raw partial content was already streamed to the terminal, clear it
141- // and replace with the properly styled complete-line render.
142- if (firstLine && partialPreview.partialWritten > 0) {
143- const clearSeq = buildClearPartialPreview(
144- partialPreview,
145- process.stdout.columns ?? 0,
146- );
147- if (out !== null) batchOutput += `${clearSeq}${styledPrefix}${out}\n`;
148- else batchOutput += `${clearSeq}\n`;
149- } else if (out !== null) {
150- batchOutput += `${out}\n`;
151- }
152- firstLine = false;
153- }
154-
155- rawBuffer = start > 0 ? rawBuffer.slice(start) : rawBuffer;
156- // rawBuffer now holds a fresh partial line. Reset per-line tracking.
157- // styledPrefix is also cleared: the reply glyph only prefixes the first
158- // line of a turn; continuation lines have no prefix.
159- styledPrefix = "";
160- resetLineState();
161- if (batchOutput) write(batchOutput);
162- }
163-
164- /**
165- * Write any new characters in rawBuffer that haven't been streamed yet,
166- * giving the user immediate visual feedback before the line is complete.
167- * Emits streamPrefix before the first characters of each new line when
168- * it hasn't been written yet (e.g. "│ " gutter for reasoning).
169- */
170- function streamPartialLine(): void {
171- const out = streamPartialPreviewDelta(partialPreview, rawBuffer);
172- if (!out) return;
173- spinner.stop();
174- write(out);
175- }
176-
17734 for await (const event of events) {
17835 switch (event.type) {
17936 case "text-delta": {
180- if (inReasoning) {
181- flushAnyText();
182- }
183- if (!inText) {
184- spinner.stop();
185- write(`${G.reply} `);
186- // "◆ " is already on the terminal. Record it for overwrite
187- // restoration and count it toward wrapped-row clearing.
188- setStreamPreviewPrefix(partialPreview, `${G.reply} `, true);
189- styledPrefix = `${G.reply} `;
190- inText = true;
191- }
192- rawBuffer += event.delta;
193- accumulatedText += event.delta;
194-
195- flushCompleteLines();
196- // Stream any new partial-line content immediately so the user sees
197- // output without waiting for the next newline.
198- streamPartialLine();
37+ content.appendTextDelta(event.delta);
19938 break;
20039 }
20140 case "reasoning-delta": {
20241 const delta = normalizeReasoningDelta(event.delta);
203- accumulatedReasoning += delta;
204- if (!showReasoning) {
205- break;
206- }
207- if (!inReasoning) {
208- if (inText) {
209- flushAnyText();
210- }
211- spinner.stop();
212- writeln(`${G.info} ${c.dim("reasoning")}`);
213- inReasoning = true;
214- inFence = false; // reasoning is never markdown; reset fence state at boundary
215- // streamPrefix provides the 2-space indent for the raw partial
216- // preview; renderSingleLine applies the same indent for completed lines.
217- setStreamPreviewPrefix(partialPreview, " ", false);
218- styledPrefix = "";
219- }
220- rawBuffer += delta;
221- flushCompleteLines();
222- // Stream any new partial-line content immediately.
223- streamPartialLine();
42+ content.appendReasoningDelta(delta, showReasoning);
22443 break;
22544 }
22645
@@ -229,7 +48,7 @@ export async function renderTurn(
22948 break;
23049 }
23150 startedToolCalls.add(event.toolCallId);
232- flushAnyText();
51+ content.flushOpenContent();
23352 spinner.stop();
23453 renderToolCall(event.toolName, event.args);
23554
@@ -247,7 +66,7 @@ export async function renderTurn(
24766 }
24867
24968 case "context-pruned": {
250- flushAnyText();
69+ content.flushOpenContent();
25170 spinner.stop();
25271 const removedKb = (event.removedBytes / 1024).toFixed(1);
25372 writeln(
@@ -257,8 +76,8 @@ export async function renderTurn(
25776 }
25877
25978 case "turn-complete": {
260- const hadContent = inText || inReasoning;
261- flushAnyText();
79+ const hadContent = content.hasOpenContent();
80+ content.flushOpenContent();
26281 spinner.stop();
26382 if (!hadContent) writeln();
26483 inputTokens = event.inputTokens;
@@ -269,12 +88,12 @@ export async function renderTurn(
26988 }
27089
27190 case "turn-error": {
272- flushAnyText();
91+ content.flushOpenContent();
27392 spinner.stop();
27493 if (isAbortError(event.error)) {
27594 newMessages = buildAbortMessages(
27695 event.partialMessages,
277- accumulatedText,
96+ content.getText(),
27897 );
27998 } else {
28099 renderError(event.error, "turn");
@@ -290,6 +109,6 @@ export async function renderTurn(
290109 outputTokens,
291110 contextTokens,
292111 newMessages,
293- reasoningText: normalizeReasoningText(accumulatedReasoning),
112+ reasoningText: normalizeReasoningText(content.getReasoning()),
294113 };
295114 }