@@ -1,7 +1,7 @@
11 import { homedir } from "node:os";
22 import * as c from "yoctocolors";
33 import type { TurnEvent } from "../llm-api/types.ts";
4-import { renderMarkdown } from "./markdown.ts";
4+import { renderLine } from "./markdown.ts";
55
66 const HOME = homedir();
77
@@ -436,37 +436,67 @@ export async function renderTurn(
436436 newMessages: import("../llm-api/turn.ts").CoreMessage[];
437437 }> {
438438 let inText = false;
439- // Full text accumulated so far — needed for correct markdown context
440- // (e.g. knowing whether we're inside a fenced code block).
441- let textBuffer = "";
442- // Tracks how many characters of textBuffer have already been written to
443- // stdout so we only write new content on each delta.
444- let writtenLen = 0;
439+ // All source lines received so far (split on \n).
440+ // The last element is the in-progress partial line (may be "").
441+ const lines: string[] = [""];
442+ // How many complete lines (index 0..flushedLines-1) have already been
443+ // printed to stdout with a trailing \n.
444+ let flushedLines = 0;
445+ // Fence state at the start of lines[flushedLines] — updated as we flush.
446+ let inFence = false;
447+ // Whether the current partial line (lines[lines.length-1]) has been
448+ // written to stdout (without a trailing \n, so \r can overwrite it).
449+ let partialWritten = false;
445450 let inputTokens = 0;
446451 let outputTokens = 0;
447452 let contextTokens = 0;
448453 let newMessages: import("../llm-api/turn.ts").CoreMessage[] = [];
449454
450- // Flush all completed lines (everything up to the last newline) through
451- // renderMarkdown and write only the newly rendered portion to stdout.
455+ // Flush all newly complete lines (everything up to the last \n).
456+ // Each complete line is rendered exactly once via renderLine, keeping
457+ // inFence state consistent across calls — O(N) total work.
458+ // After flushing complete lines, write/overwrite the partial last line
459+ // as raw text so the user sees content immediately.
452460 function flushLines(): void {
453- const lastNl = textBuffer.lastIndexOf("\n");
454- if (lastNl < writtenLen) return; // no new complete lines
455- const fullRendered = renderMarkdown(textBuffer.slice(0, lastNl + 1));
456- const alreadyRendered = renderMarkdown(textBuffer.slice(0, writtenLen));
457- const newOutput = fullRendered.slice(alreadyRendered.length);
458- if (newOutput) write(newOutput);
459- writtenLen = lastNl + 1;
461+ const complete = lines.length - 1; // indices 0..complete-1 are complete
462+ // Render and print any newly complete lines.
463+ while (flushedLines < complete) {
464+ const raw = lines[flushedLines] ?? "";
465+ const result = renderLine(raw, inFence);
466+ // If a partial line was already written on this terminal line, clear
467+ // it first with \r before printing the final rendered version.
468+ if (partialWritten) {
469+ process.stdout.write("\r\x1B[2K");
470+ partialWritten = false;
471+ }
472+ write(`${result.output}\n`);
473+
474+ inFence = result.inFence;
475+ flushedLines++;
476+ }
477+ // Write/overwrite the partial last line (no \n), rendered so inline
478+ // spans (bold, code, italic) are visible as they stream in.
479+ const partial = lines[lines.length - 1] ?? "";
480+ if (partial) {
481+ const rendered = renderLine(partial, inFence).output;
482+ process.stdout.write(`\r${rendered}`);
483+ partialWritten = true;
484+ }
460485 }
461486
462- // Flush any remaining buffered text (including incomplete last line).
487+ // Finalize: overwrite the partial line with its fully-rendered version.
488+ // Callers are responsible for writing \n after this.
463489 function flushText(): void {
464- if (writtenLen >= textBuffer.length) return;
465- const fullRendered = renderMarkdown(textBuffer);
466- const alreadyRendered = renderMarkdown(textBuffer.slice(0, writtenLen));
467- const newOutput = fullRendered.slice(alreadyRendered.length);
468- if (newOutput) write(newOutput);
469- writtenLen = textBuffer.length;
490+ const partial = lines[lines.length - 1] ?? "";
491+ // Clear whatever is on-screen first — even if partial is now "" (e.g.
492+ // stream ended with \n), partialWritten may be true and must be cleared.
493+ if (partialWritten) {
494+ process.stdout.write("\r\x1B[2K");
495+ partialWritten = false;
496+ }
497+ if (!partial) return;
498+ const result = renderLine(partial, inFence);
499+ if (result.output) write(result.output);
470500 }
471501
472502 for await (const event of events) {
@@ -477,7 +507,16 @@ export async function renderTurn(
477507 process.stdout.write(`${G.reply} `);
478508 inText = true;
479509 }
480- textBuffer += event.delta;
510+ // Split the delta on newlines and append to our lines array.
511+ // Each \n in the delta completes the current partial line and
512+ // starts a new one.
513+ const parts = event.delta.split("\n");
514+ lines[lines.length - 1] =
515+ (lines[lines.length - 1] ?? "") + (parts[0] ?? "");
516+ for (let i = 1; i < parts.length; i++) {
517+ lines.push(parts[i] ?? "");
518+ }
519+
481520 flushLines();
482521 break;
483522 }