@@ -3,7 +3,7 @@ import { homedir } from "node:os";
33
44 import * as c from "yoctocolors";
55 import type { TurnEvent } from "../llm-api/types.ts";
6-import { renderLine } from "./markdown.ts";
6+import { renderChunk } from "./markdown.ts";
77
88 const HOME = homedir();
99 const PACKAGE_VERSION = (() => {
@@ -450,67 +450,108 @@ export async function renderTurn(
450450 newMessages: import("../llm-api/turn.ts").CoreMessage[];
451451 }> {
452452 let inText = false;
453- // All source lines received so far (split on \n).
454- // The last element is the in-progress partial line (may be "").
455- const lines: string[] = [""];
456- // How many complete lines (index 0..flushedLines-1) have already been
457- // printed to stdout with a trailing \n.
458- let flushedLines = 0;
459- // Fence state at the start of lines[flushedLines] — updated as we flush.
453+ // Unprocessed raw text — only the portion from the last flush boundary
454+ // onward. Trimmed after each flush to keep memory constant.
455+ let rawBuffer = "";
456+ // Fence state at the start of rawBuffer — updated whenever we trim.
460457 let inFence = false;
461- // Whether the current partial line (lines[lines.length-1]) has been
462- // written to stdout (without a trailing \n, so \r can overwrite it).
463- let partialWritten = false;
458+ // ANSI-rendered characters waiting to be emitted one-by-one.
459+ let printQueue = "";
460+ // Next character index in printQueue to emit.
461+ let printPos = 0;
462+ // Handle for the active setImmediate ticker, or null if idle.
463+ let tickerHandle: ReturnType<typeof setImmediate> | null = null;
464+
464465 let inputTokens = 0;
465466 let outputTokens = 0;
466467 let contextTokens = 0;
467468 let newMessages: import("../llm-api/turn.ts").CoreMessage[] = [];
468469
469- // Flush all newly complete lines (everything up to the last \n).
470- // Each complete line is rendered exactly once via renderLine, keeping
471- // inFence state consistent across calls — O(N) total work.
472- // After flushing complete lines, write/overwrite the partial last line
473- // as raw text so the user sees content immediately.
474- function flushLines(): void {
475- const complete = lines.length - 1; // indices 0..complete-1 are complete
476- // Render and print any newly complete lines.
477- while (flushedLines < complete) {
478- const raw = lines[flushedLines] ?? "";
479- const result = renderLine(raw, inFence);
480- // If a partial line was already written on this terminal line, clear
481- // it first with \r before printing the final rendered version.
482- if (partialWritten) {
483- process.stdout.write("\r\x1B[2K");
484- partialWritten = false;
485- }
486- write(`${result.output}\n`);
470+ // Append rendered ANSI text to the print queue and start the ticker if
471+ // it is not already running.
472+ function enqueuePrint(ansi: string): void {
473+ printQueue += ansi;
474+ if (tickerHandle === null) {
475+ scheduleTick();
476+ }
477+ }
487478
488- inFence = result.inFence;
489- flushedLines++;
479+ // Emit one character from the print queue, then reschedule until drained.
480+ function tick(): void {
481+ tickerHandle = null;
482+ if (printPos < printQueue.length) {
483+ process.stdout.write(printQueue[printPos] as string);
484+ printPos++;
485+ scheduleTick();
486+ } else {
487+ // Queue fully drained — reclaim memory.
488+ printQueue = "";
489+ printPos = 0;
490490 }
491- // Write/overwrite the partial last line (no \n), rendered so inline
492- // spans (bold, code, italic) are visible as they stream in.
493- const partial = lines[lines.length - 1] ?? "";
494- if (partial) {
495- const rendered = renderLine(partial, inFence).output;
496- process.stdout.write(`\r${rendered}`);
497- partialWritten = true;
491+ }
492+
493+ function scheduleTick(): void {
494+ tickerHandle = setImmediate(tick);
495+ }
496+
497+ // Synchronously drain any remaining print queue — used when the turn ends
498+ // or a tool call interrupts the text stream.
499+ function drainQueue(): void {
500+ if (tickerHandle !== null) {
501+ clearImmediate(tickerHandle);
502+ tickerHandle = null;
503+ }
504+ if (printPos < printQueue.length) {
505+ process.stdout.write(printQueue.slice(printPos));
506+ }
507+ // Reclaim memory.
508+ printQueue = "";
509+ printPos = 0;
510+ }
511+
512+ // Render and enqueue a slice of rawBuffer, then trim rawBuffer to only
513+ // retain the unprocessed tail. inFence is updated to reflect the new head.
514+ function renderAndTrim(end: number): void {
515+ const chunk = rawBuffer.slice(0, end);
516+ const rendered = renderChunk(chunk, inFence);
517+ inFence = rendered.inFence;
518+ enqueuePrint(rendered.output);
519+ rawBuffer = rawBuffer.slice(end);
520+ }
521+
522+ // Flush complete chunks from rawBuffer. Strategy:
523+ // 1. If a \n\n boundary exists, flush everything up to and including it
524+ // as one paragraph chunk — preserving blank-line spacing.
525+ // 2. Otherwise, flush any complete lines (\n) one at a time so that
526+ // single-paragraph and list responses stream immediately rather than
527+ // waiting for a blank line.
528+ // The unprocessed tail (partial line) stays in rawBuffer.
529+ function flushChunks(): void {
530+ // Prefer paragraph-level boundaries first.
531+ let boundary = rawBuffer.indexOf("\n\n");
532+ if (boundary !== -1) {
533+ // Flush everything up to and including the blank line.
534+ renderAndTrim(boundary + 2);
535+ // After trimming, there may be more boundaries — recurse.
536+ flushChunks();
537+ return;
538+ }
539+ // No blank line yet: flush any complete lines individually so content
540+ // appears immediately rather than waiting for the next blank line.
541+ boundary = rawBuffer.lastIndexOf("\n");
542+ if (boundary !== -1) {
543+ // Include the trailing \n so each line ends correctly.
544+ renderAndTrim(boundary + 1);
498545 }
499546 }
500547
501- // Finalize: overwrite the partial line with its fully-rendered version.
502- // Callers are responsible for writing \n after this.
503- function flushText(): void {
504- const partial = lines[lines.length - 1] ?? "";
505- // Clear whatever is on-screen first — even if partial is now "" (e.g.
506- // stream ended with \n), partialWritten may be true and must be cleared.
507- if (partialWritten) {
508- process.stdout.write("\r\x1B[2K");
509- partialWritten = false;
548+ // Render everything remaining in rawBuffer (the final partial chunk),
549+ // enqueue it, then drain the entire queue synchronously.
550+ function flushAll(): void {
551+ if (rawBuffer) {
552+ renderAndTrim(rawBuffer.length);
510553 }
511- if (!partial) return;
512- const result = renderLine(partial, inFence);
513- if (result.output) write(result.output);
554+ drainQueue();
514555 }
515556
516557 for await (const event of events) {
@@ -521,23 +562,14 @@ export async function renderTurn(
521562 process.stdout.write(`${G.reply} `);
522563 inText = true;
523564 }
524- // Split the delta on newlines and append to our lines array.
525- // Each \n in the delta completes the current partial line and
526- // starts a new one.
527- const parts = event.delta.split("\n");
528- lines[lines.length - 1] =
529- (lines[lines.length - 1] ?? "") + (parts[0] ?? "");
530- for (let i = 1; i < parts.length; i++) {
531- lines.push(parts[i] ?? "");
532- }
533-
534- flushLines();
565+ rawBuffer += event.delta;
566+ flushChunks();
535567 break;
536568 }
537569
538570 case "tool-call-start": {
539571 if (inText) {
540- flushText();
572+ flushAll();
541573 writeln();
542574 inText = false;
543575 }
@@ -556,7 +588,7 @@ export async function renderTurn(
556588
557589 case "turn-complete": {
558590 if (inText) {
559- flushText();
591+ flushAll();
560592 writeln();
561593 inText = false;
562594 }
@@ -570,7 +602,7 @@ export async function renderTurn(
570602
571603 case "turn-error": {
572604 if (inText) {
573- flushText();
605+ flushAll();
574606 writeln();
575607 inText = false;
576608 }