@@ -15,6 +15,7 @@ import type { Session } from "../session.ts";
1515 import type { ToolName } from "../config.ts";
1616 import { Terminal, expandTabs, wrapLine, type Key } from "./term.ts";
1717 import { Editor } from "./editor.ts";
18+import { LineStream, TailStream, type BodyLine, type StreamRenderer } from "./stream.ts";
1819 import { cyan, dim, green, red } from "./styles.ts";
1920 import { contextUsageLine, estimateContextTokens } from "./usage.ts";
2021
@@ -45,19 +46,6 @@ const ERROR_PREFIX = " ! ";
4546 const EXIT_LINE = /^exit code: (.+)$/;
4647 const EDIT_HEADER = /^(Index: |={3,}$|--- |\+\+\+ )/;
4748
48-/** The text after the last newline: what is still incomplete. */
49-function incomplete(text: string): string {
50- const index = text.lastIndexOf("\n");
51- return index >= 0 ? text.slice(index + 1) : text;
52-}
53-
54-/** The lines completed by the newest text, excluding the incomplete tail. */
55-function completeLines(text: string): string[] {
56- const lines = text.split("\n");
57- lines.pop();
58- return lines;
59-}
60-
6149 function callSummary(name: string, args: JsonObject): string {
6250 if (name === "bash" && typeof args.command === "string") return args.command.replace(/\s*\n\s*/g, " ");
6351 if (name === "edit" && typeof args.path === "string") return args.path;
@@ -65,12 +53,6 @@ function callSummary(name: string, args: JsonObject): string {
6553 return JSON.stringify(args);
6654 }
6755
68-/** One display line: unwrapped text plus the style its wrapped rows inherit. */
69-interface BodyLine {
70- text: string;
71- style?: (text: string) => string;
72-}
73-
7456 /** Unified-diff color for one `edit` body line; file headers are stripped. */
7557 function diffStyle(line: string): ((text: string) => string) | undefined {
7658 if (line.startsWith("@@")) return cyan;
@@ -101,17 +83,21 @@ function resultLines(name: string, text: string, isError: boolean): BodyLine[] {
10183 }
10284
10385 /**
104- * Wraps plain text, then styles each row: `wrapLine` measures escapes as
105- * printable cells, so it must never see them. A continuation row carries no
106- * marker and inherits the style of its source line; the elision marker and
107- * empty rows stay unstyled.
86+ * Wraps plain text, then styles each row: styling after the break is what lets a
87+ * continuation row inherit its source line's style. A continuation row carries
88+ * no marker; empty rows stay unstyled.
10889 */
109-function bodyRows(lines: BodyLine[], width: number): string[] {
110- const rows = lines.flatMap((line) => {
90+function renderRows(lines: BodyLine[], width: number): string[] {
91+ return lines.flatMap((line) => {
11192 const style = line.style;
11293 const wrapped = wrapLine(expandTabs(line.text), width);
11394 return style === undefined ? wrapped : wrapped.map((row) => (row === "" ? row : style(row)));
11495 });
96+}
97+
98+/** `renderRows` plus the display-only elision applied to long tool bodies. */
99+function bodyRows(lines: BodyLine[], width: number): string[] {
100+ const rows = renderRows(lines, width);
115101 if (rows.length > MAX_BODY_ROWS) {
116102 const hidden = rows.length - ELIDED_HEAD - ELIDED_TAIL;
117103 return [
@@ -148,9 +134,14 @@ class LiveRegion {
148134 return out;
149135 }
150136
151- /** `lines` are already styled; the live region adds no attributes of its own. */
152- draw(lines: string[], cursorRow: number, cursorCol: number): string {
137+ /**
138+ * `lines` are already styled; the live region adds no attributes of its own.
139+ * `above` is written between the clear and the body, so scrollback lands
140+ * where the region was.
141+ */
142+ draw(lines: string[], cursorRow: number, cursorCol: number, above: string): string {
153143 let out = this.clear();
144+ out += above;
154145 for (let i = 0; i < lines.length; i++) {
155146 if (i > 0) out += "\r\n";
156147 out += lines[i];
@@ -192,8 +183,8 @@ class Tui {
192183 private separator = false;
193184
194185 // In-flight stream state, never persisted: all display-only.
195- private pending = "";
196- private preview = "";
186+ private readonly reply: StreamRenderer = new LineStream();
187+ private readonly activity: StreamRenderer = new TailStream();
197188 private pendingCalls: string[] = [];
198189 private streamed = "";
199190 private turnStart = 0;
@@ -369,50 +360,48 @@ class Tui {
369360 if (event.phase === "pausing") this.paused = true;
370361 break;
371362 case "text":
372- this.preview = "";
373- this.pending += event.delta;
363+ this.activity.reset();
374364 this.streamed += event.delta;
375- for (const line of completeLines(this.pending)) this.push(line);
376- this.pending = incomplete(this.pending);
365+ this.commitLines(this.reply.feed(event.delta));
377366 break;
378367 case "reasoning":
379- if (this.pending === "") this.preview = incomplete(this.preview + event.delta);
368+ if (this.reply.pending().length === 0) this.activity.feed(event.delta);
380369 break;
381370 case "toolCall":
382371 // Flush first so scrollback order matches execution order, then hold the
383372 // call line until its result arrives: a message may carry several calls,
384373 // all announced before any of them runs.
385- this.flushPending();
386- this.preview = "";
374+ this.commitLines(this.reply.flush());
375+ this.activity.reset();
387376 this.pendingCalls.push(`-> ${event.name} ${callSummary(event.name, event.arguments)}`);
388377 break;
389378 case "toolOutput":
390- this.preview = incomplete(this.preview + event.chunk);
379+ this.activity.feed(event.chunk);
391380 break;
392381 case "message":
393382 this.commitMessage(event.message);
394383 break;
395384 case "toolResult":
396- this.preview = "";
385+ this.activity.reset();
397386 this.commitToolResult(event.name, event.text, event.isError);
398387 break;
399388 case "error":
400389 this.finishTurn();
401- this.flushPending();
390+ this.commitLines(this.reply.flush());
402391 this.flushCalls();
403392 this.separator = true;
404393 this.push(`! ${event.message}`);
405394 break;
406395 case "cancelled":
407396 this.finishTurn();
408- this.flushPending();
397+ this.commitLines(this.reply.flush());
409398 this.flushCalls();
410399 this.separator = true;
411400 this.push("! cancelled");
412401 break;
413402 case "complete":
414403 this.finishTurn();
415- this.flushPending();
404+ this.commitLines(this.reply.flush());
416405 this.flushCalls();
417406 this.separator = true;
418407 this.push(dim(`[complete · ${this.elapsed()}s]`));
@@ -421,11 +410,12 @@ class Tui {
421410 this.render();
422411 }
423412
424- /** Terminal states clear the status row instead of lingering in it. */
413+ /** Terminal states clear the status row and any in-flight preview. */
425414 private finishTurn(): void {
426415 this.phase = "idle";
427416 this.detail = undefined;
428417 this.paused = false;
418+ this.activity.reset();
429419 }
430420
431421 private elapsed(): number {
@@ -434,20 +424,20 @@ class Tui {
434424
435425 private commitUser(text: string): void {
436426 this.separator = true;
437- for (const line of text.split("\n")) this.push(`> ${line}`);
427+ this.commitLines(text.split("\n").map((line) => ({ text: `> ${line}` })));
438428 this.separator = true;
439429 }
440430
441431 /** Commits a line the model emitted without streaming it, plus the in-flight tail. */
442432 private commitMessage(message: AssistantMessage): void {
443- this.preview = "";
444- this.flushPending();
433+ this.activity.reset();
434+ this.commitLines(this.reply.flush());
445435 const text = message.content
446436 .filter((block) => block.type === "text")
447437 .map((block) => block.text)
448438 .join("");
449439 if (text.trim() !== "" && !this.streamed.includes(text)) {
450- for (const line of text.trimEnd().split("\n")) this.push(line);
440+ this.commitLines(text.trimEnd().split("\n").map((line) => ({ text: line })));
451441 }
452442 this.streamed = "";
453443 }
@@ -474,11 +464,9 @@ class Tui {
474464 this.pendingCalls = [];
475465 }
476466
477- private flushPending(): void {
478- if (this.pending === "") return;
479- const line = this.pending;
480- this.pending = "";
481- this.push(line);
467+ /** Commits logical lines through the same wrap-and-style step tool bodies use. */
468+ private commitLines(lines: BodyLine[]): void {
469+ for (const row of renderRows(lines, Math.max(1, this.term.width))) this.push(row);
482470 }
483471
484472 /**
@@ -489,26 +477,15 @@ class Tui {
489477 const blank = line === "" || (this.separator && this.wrote);
490478 this.separator = false;
491479 if (blank && this.wrote && !this.lastBlank) {
492- this.scroll += "\n";
480+ this.scroll += "\r\n";
493481 this.lastBlank = true;
494482 }
495483 if (line !== "") {
496- this.scroll += `${line}\n`;
484+ this.scroll += `${line}\r\n`;
497485 this.wrote = true;
498486 this.lastBlank = false;
499487 }
500- this.flushScroll();
501- }
502-
503- /** Scrollback is written before the live region is redrawn, never after. */
504- private flushScroll(): void {
505- if (this.scroll === "") return;
506- // A commit on a region filling every row above the last scrolls the
507- // terminal and moves the anchor; re-anchor like SIGWINCH does.
508- if (this.live.height >= this.term.height - 1) this.reanchor = true;
509- const out = this.live.clear() + this.scroll;
510- this.scroll = "";
511- this.term.write(out);
488+ this.render();
512489 }
513490
514491 private render(): void {
@@ -520,10 +497,20 @@ class Tui {
520497 }, 16);
521498 }
522499
523- /** One dim row while a turn is active or paused; nothing when idle. */
524- private statusLine(): string | null {
525- if (this.paused || this.phase === "pausing") return "paused - type steering, Enter to submit";
526- if (!this.active || this.phase === "idle") return null;
500+ /**
501+ * The one row between the in-flight lines and the editor: the phase while a
502+ * turn is active, and the context readout always. The readout carries its own
503+ * emphasis, so only the phase half is dimmed.
504+ */
505+ private statusLine(): string {
506+ const usage = contextUsageLine(
507+ estimateContextTokens(this.messages, this.opts.systemPrompt, this.opts.tools),
508+ this.opts.model,
509+ );
510+ if (this.paused || this.phase === "pausing") {
511+ return `${dim("paused - type steering, Enter to submit")} · ${usage}`;
512+ }
513+ if (!this.active || this.phase === "idle") return usage;
527514 const label =
528515 this.phase === "preparing"
529516 ? "preparing"
@@ -532,43 +519,42 @@ class Tui {
532519 : this.phase === "streaming"
533520 ? "streaming"
534521 : `running ${this.detail ?? "tool"}`;
535- return `${SPINNER[this.frame % SPINNER.length]} ${label} · ${this.elapsed()}s`;
522+ return `${dim(`${SPINNER[this.frame % SPINNER.length]} ${label} · ${this.elapsed()}s`)} · ${usage}`;
536523 }
537524
538525 private draw(): void {
539526 if (this.closed) return;
540527 const width = Math.max(1, this.term.width);
541528 const height = Math.max(1, this.term.height - 1);
542- const status = this.statusLine();
543- const fixed = 1 + (status !== null ? 1 : 0);
544-
545- const pending = this.pending !== "" ? this.pending : this.preview;
546- const inflight: string[] = [];
547- if (pending !== "") {
548- const styled = this.pending === "" ? dim : (row: string) => row;
549- for (const row of wrapLine(expandTabs(pending), width)) inflight.push(styled(row));
550- }
529+
530+ const status = wrapLine(this.statusLine(), width);
531+
532+ let inflight = this.reply.pending();
533+ if (inflight.length === 0) inflight = this.activity.pending();
534+ const rows = renderRows(inflight, width);
551535
552536 // Short on space: clip the in-flight rows first, then the editor viewport,
553- // which never drops below one row. The context row is always kept.
554- const keep = Math.max(0, Math.min(inflight.length, height - fixed - 1));
555- const body = inflight.slice(inflight.length - keep);
556- const editor = this.editor.render(width, Math.max(1, height - fixed - body.length));
557-
558- const lines = [
559- contextUsageLine(
560- estimateContextTokens(this.messages, this.opts.systemPrompt, this.opts.tools),
561- this.opts.model,
562- ),
563- ...body,
564- ...(status !== null ? [dim(status)] : []),
565- ...editor.rows,
566- ];
567- let cursorRow = fixed + body.length + editor.cursorRow;
537+ // which never drops below one row. The status rows are always kept.
538+ const keep = Math.max(0, Math.min(rows.length, height - status.length - 1));
539+ const body = rows.slice(rows.length - keep);
540+ const editor = this.editor.render(width, Math.max(1, height - status.length - body.length));
541+
542+ const lines = [...body, ...status, ...editor.rows];
543+ let cursorRow = status.length + body.length + editor.cursorRow;
568544 if (cursorRow >= lines.length) cursorRow = lines.length - 1;
545+
546+ // Scrollback and the live region are written as one frame. Clearing the
547+ // region and restoring it in separate writes leaves it blank in between.
548+ // A commit on a region filling every row above the last scrolls the
549+ // terminal; the re-anchor newline goes after the scrollback, not before the
550+ // erase, because `clear()` measures from the previous frame's cursor and
551+ // moving the cursor down first lands the erase one row below the region.
552+ if (this.scroll !== "" && this.live.height >= this.term.height - 1) this.reanchor = true;
553+ const scroll = this.scroll;
554+ this.scroll = "";
569555 const prefix = this.reanchor ? "\r\n" : "";
570556 this.reanchor = false;
571- this.term.write(prefix + this.live.draw(lines, cursorRow, editor.cursorCol));
557+ this.term.write(this.live.draw(lines, cursorRow, editor.cursorCol, scroll + prefix));
572558 }
573559
574560 private exit(): void {
@@ -577,7 +563,9 @@ class Tui {
577563 this.abort?.abort();
578564 if (this.spinner) clearInterval(this.spinner);
579565 this.spinner = undefined;
580- this.term.write(this.live.clear());
566+ // Draws are deferred, so anything pushed since the last frame is still here.
567+ this.term.write(this.live.clear() + this.scroll);
568+ this.scroll = "";
581569 this.term.stop();
582570 this.opts.session.close();
583571 process.off("SIGINT", this.onSignal);