xonecas.io
64875
Mc

mini-coder / commit efbe0e7

refactor(cli): simplify stream output rendering

xonecas2026-03-14 efbe0e741da829f1040b9a518d52db20df013be7 parent 05e167e

4 files changed

src/cli/stream-preview.ts+0−83
@@ -1,83 +0,0 @@
1-import { visibleLength } from "./terminal-width.ts";
2-
3-interface PartialPreviewTracker {
4- partialWritten: number;
5- partialVisibleChars: number;
6- streamPrefix: string;
7- streamPrefixWritten: boolean;
8-}
9-
10-export function createPartialPreviewTracker(): PartialPreviewTracker {
11- return {
12- partialWritten: 0,
13- partialVisibleChars: 0,
14- streamPrefix: "",
15- streamPrefixWritten: false,
16- };
17-}
18-
19-export function resetPartialPreviewTracker(
20- tracker: PartialPreviewTracker,
21-): void {
22- tracker.partialWritten = 0;
23- tracker.partialVisibleChars = 0;
24- tracker.streamPrefix = "";
25- tracker.streamPrefixWritten = false;
26-}
27-
28-export function setStreamPreviewPrefix(
29- tracker: PartialPreviewTracker,
30- prefix: string,
31- written: boolean,
32-): void {
33- tracker.streamPrefix = prefix;
34- tracker.streamPrefixWritten = written;
35- if (written && prefix) {
36- tracker.partialVisibleChars += visibleLength(prefix);
37- }
38-}
39-
40-function estimateWrappedRows(
41- visibleChars: number,
42- terminalColumns: number,
43-): number {
44- if (visibleChars <= 0) return 1;
45- if (terminalColumns <= 0) return 1;
46- return Math.max(1, Math.ceil(visibleChars / terminalColumns));
47-}
48-
49-export function buildClearPartialPreview(
50- tracker: PartialPreviewTracker,
51- terminalColumns: number,
52-): string {
53- if (tracker.partialWritten <= 0) return "";
54- const rows = estimateWrappedRows(
55- tracker.partialVisibleChars,
56- terminalColumns,
57- );
58- let seq = "\r\x1b[2K";
59- for (let i = 1; i < rows; i++) {
60- seq += "\x1b[1A\r\x1b[2K";
61- }
62- return seq;
63-}
64-
65-export function streamPartialPreviewDelta(
66- tracker: PartialPreviewTracker,
67- rawBuffer: string,
68-): string {
69- if (rawBuffer.length <= tracker.partialWritten) return "";
70-
71- let out = "";
72- if (!tracker.streamPrefixWritten && tracker.streamPrefix) {
73- out += tracker.streamPrefix;
74- tracker.streamPrefixWritten = true;
75- tracker.partialVisibleChars += visibleLength(tracker.streamPrefix);
76- }
77-
78- const delta = rawBuffer.slice(tracker.partialWritten);
79- out += delta;
80- tracker.partialVisibleChars += visibleLength(delta);
81- tracker.partialWritten = rawBuffer.length;
82- return out;
83-}
src/cli/stream-render-content.ts+36−85
@@ -2,21 +2,12 @@ import * as c from "yoctocolors";
22 import { renderLine } from "./markdown.ts";
33 import { G, write, writeln } from "./output.ts";
44 import type { Spinner } from "./spinner.ts";
5-import {
6- buildClearPartialPreview,
7- createPartialPreviewTracker,
8- resetPartialPreviewTracker,
9- setStreamPreviewPrefix,
10- streamPartialPreviewDelta,
11-} from "./stream-preview.ts";
12-import { terminal } from "./terminal-io.ts";
135
146 export class StreamRenderContent {
157 private inText = false;
168 private inReasoning = false;
179 private rawBuffer = "";
18- private styledPrefix = "";
19- private partialPreview = createPartialPreviewTracker();
10+ private streamedChars = 0;
2011 private inFence = false;
2112 private reasoningBlankLineRun = 0;
2213 private accumulatedText = "";
@@ -43,15 +34,12 @@ export class StreamRenderContent {
4334 if (!this.inText) {
4435 this.spinner.stop();
4536 write(`${G.reply} `);
46- setStreamPreviewPrefix(this.partialPreview, `${G.reply} `, true);
47- this.styledPrefix = `${G.reply} `;
4837 this.inText = true;
4938 }
5039 this.rawBuffer += delta;
5140 this.accumulatedText += delta;
52-
5341 this.flushCompleteLines();
54- this.streamPartialLine();
42+ this.streamPartialRemainder();
5543 }
5644
5745 appendReasoningDelta(delta: string, showReasoning: boolean): void {
@@ -66,50 +54,22 @@ export class StreamRenderContent {
6654 writeln(`${G.info} ${c.dim("reasoning")}`);
6755 this.inReasoning = true;
6856 this.inFence = false;
69- setStreamPreviewPrefix(this.partialPreview, " ", false);
70- this.styledPrefix = "";
7157 }
7258 this.rawBuffer += delta;
7359 this.flushCompleteLines();
74- this.streamPartialLine();
60+ this.streamPartialRemainder();
7561 }
7662
7763 flushOpenContent(): void {
7864 if (!this.inText && !this.inReasoning) return;
79-
80- if (this.rawBuffer) {
81- this.spinner.stop();
82- const raw = this.rawBuffer;
83- const out = this.renderSingleLine(raw);
84- this.rawBuffer = "";
85- if (this.partialPreview.partialWritten > 0) {
86- if (!this.canKeepStreamedPartial(raw, out)) {
87- const clearSeq = buildClearPartialPreview(
88- this.partialPreview,
89- terminal.stdoutColumns,
90- );
91- if (out !== null) write(`${clearSeq}${this.styledPrefix}${out}`);
92- else write(clearSeq);
93- }
94- } else if (out !== null) {
95- write(out);
96- }
97- }
65+ this.streamPartialRemainder();
9866 writeln();
9967 this.inText = false;
10068 this.inReasoning = false;
10169 this.inFence = false;
10270 this.reasoningBlankLineRun = 0;
103- this.styledPrefix = "";
104- this.resetLineState();
105- }
106-
107- private canKeepStreamedPartial(raw: string, out: string | null): boolean {
108- return (
109- this.inText &&
110- out === raw &&
111- this.partialPreview.partialWritten === raw.length
112- );
71+ this.rawBuffer = "";
72+ this.streamedChars = 0;
11373 }
11474
11575 private renderSingleLine(raw: string): string | null {
@@ -129,55 +89,46 @@ export class StreamRenderContent {
12989 return rendered.output;
13090 }
13191
132- private resetLineState(): void {
133- resetPartialPreviewTracker(this.partialPreview);
134- }
135-
13692 private flushCompleteLines(): void {
137- let start = 0;
138- let boundary = this.rawBuffer.indexOf("\n", start);
93+ let boundary = this.rawBuffer.indexOf("\n");
13994 if (boundary === -1) return;
140-
14195 this.spinner.stop();
142- let batchOutput = "";
143- let firstLine = true;
14496
14597 while (boundary !== -1) {
146- const raw = this.rawBuffer.slice(start, boundary);
147- start = boundary + 1;
148- boundary = this.rawBuffer.indexOf("\n", start);
149-
150- const out = this.renderSingleLine(raw);
151- if (firstLine && this.partialPreview.partialWritten > 0) {
152- if (this.canKeepStreamedPartial(raw, out)) {
153- batchOutput += "\n";
154- } else {
155- const clearSeq = buildClearPartialPreview(
156- this.partialPreview,
157- terminal.stdoutColumns,
158- );
159- if (out !== null) {
160- batchOutput += `${clearSeq}${this.styledPrefix}${out}\n`;
161- } else {
162- batchOutput += `${clearSeq}\n`;
163- }
98+ const raw = this.rawBuffer.slice(0, boundary);
99+ const rendered = this.renderSingleLine(raw);
100+ const streamedForLine = Math.min(this.streamedChars, raw.length);
101+
102+ if (streamedForLine > 0) {
103+ if (streamedForLine < raw.length) {
104+ this.writePartial(raw.slice(streamedForLine));
164105 }
165- } else if (out !== null) {
166- batchOutput += `${out}\n`;
106+ writeln();
107+ } else {
108+ if (rendered !== null) writeln(rendered);
109+ else writeln();
167110 }
168- firstLine = false;
169- }
170111
171- this.rawBuffer = start > 0 ? this.rawBuffer.slice(start) : this.rawBuffer;
172- this.styledPrefix = "";
173- this.resetLineState();
174- if (batchOutput) write(batchOutput);
112+ this.rawBuffer = this.rawBuffer.slice(boundary + 1);
113+ this.streamedChars = Math.max(0, this.streamedChars - raw.length);
114+ boundary = this.rawBuffer.indexOf("\n");
115+ }
175116 }
176117
177- private streamPartialLine(): void {
178- const out = streamPartialPreviewDelta(this.partialPreview, this.rawBuffer);
179- if (!out) return;
118+ private streamPartialRemainder(): void {
119+ if (this.rawBuffer.length <= this.streamedChars) return;
180120 this.spinner.stop();
181- write(out);
121+ this.writePartial(this.rawBuffer.slice(this.streamedChars));
122+ this.streamedChars = this.rawBuffer.length;
123+ }
124+
125+ private writePartial(text: string): void {
126+ if (!text) return;
127+ if (this.inReasoning) {
128+ const prefix = this.streamedChars === 0 ? " " : "";
129+ write(`${prefix}${c.dim(c.italic(text))}`);
130+ return;
131+ }
132+ write(text);
182133 }
183134 }
src/cli/stream-render.test.ts+6−6
@@ -185,7 +185,7 @@ describe("renderTurn", () => {
185185 expect(simulateTerminal(stdout)).toBe("◆ hello\nworld\n");
186186 });
187187
188- test("clears wrapped streamed partials when trailing content arrives in a later chunk", async () => {
188+ test("keeps wrapped partials stable without cursor rewrites", async () => {
189189 captureStdout();
190190 await withTerminalColumns(20, async () => {
191191 await renderTurn(
@@ -198,7 +198,7 @@ describe("renderTurn", () => {
198198 );
199199 });
200200
201- expect(stdout.includes("\x1b[1A\r\x1b[2K")).toBe(true);
201+ expect(stdout.includes("\x1b[1A\r\x1b[2K")).toBe(false);
202202 expect(simulateTerminal(stdout)).toContain(
203203 "◆ this is a long streamed partial line\n",
204204 );
@@ -274,10 +274,10 @@ describe("renderTurn", () => {
274274 new Spinner(),
275275 );
276276
277- // The partial raw text is streamed immediately and then overwritten on
278- // turn-end with the fully styled line (bold ANSI codes applied).
279- expect(simulateTerminal(stdout)).toBe("◆ bold 👩🏽‍💻\n");
280- expect(hasAnsi(stdout, "[1m")).toBe(true);
277+ // Streaming now prioritizes immediate output stability over end-of-line markdown
278+ // rewrite, so raw markdown markers are preserved in partial lines.
279+ expect(simulateTerminal(stdout)).toBe("◆ **bold** 👩🏽‍💻\n");
280+ expect(hasAnsi(stdout, "[1m")).toBe(false);
281281 });
282282
283283 test("preserves fenced-code state across streamed lines", async () => {
src/cli/terminal-width.ts+0−120
@@ -1,120 +0,0 @@
1-const emojiLikeRegex = /\p{Extended_Pictographic}/u;
2-const ansiEscapeChar = String.fromCharCode(0x1b);
3-const graphemeSegmenter =
4- typeof Intl !== "undefined" && typeof Intl.Segmenter === "function"
5- ? new Intl.Segmenter(undefined, { granularity: "grapheme" })
6- : null;
7-
8-function stripSgrAnsi(s: string): string {
9- if (!s) return "";
10- let out = "";
11- for (let i = 0; i < s.length; i++) {
12- if (s[i] !== ansiEscapeChar || s[i + 1] !== "[") {
13- out += s[i] ?? "";
14- continue;
15- }
16-
17- let j = i + 2;
18- while (j < s.length) {
19- const ch = s[j] ?? "";
20- if ((ch >= "0" && ch <= "9") || ch === ";") {
21- j++;
22- continue;
23- }
24- break;
25- }
26-
27- if (s[j] === "m") {
28- i = j;
29- continue;
30- }
31-
32- out += s[i] ?? "";
33- }
34- return out;
35-}
36-
37-function isControlCodePoint(cp: number): boolean {
38- return (cp >= 0 && cp <= 0x1f) || (cp >= 0x7f && cp <= 0x9f);
39-}
40-
41-function isCombiningCodePoint(cp: number): boolean {
42- return (
43- (cp >= 0x0300 && cp <= 0x036f) ||
44- (cp >= 0x1ab0 && cp <= 0x1aff) ||
45- (cp >= 0x1dc0 && cp <= 0x1dff) ||
46- (cp >= 0x20d0 && cp <= 0x20ff) ||
47- (cp >= 0xfe20 && cp <= 0xfe2f)
48- );
49-}
50-
51-function isVariationSelector(cp: number): boolean {
52- return (cp >= 0xfe00 && cp <= 0xfe0f) || (cp >= 0xe0100 && cp <= 0xe01ef);
53-}
54-
55-function isWideCodePoint(cp: number): boolean {
56- return (
57- cp >= 0x1100 &&
58- (cp <= 0x115f ||
59- cp === 0x2329 ||
60- cp === 0x232a ||
61- (cp >= 0x2e80 && cp <= 0xa4cf && cp !== 0x303f) ||
62- (cp >= 0xac00 && cp <= 0xd7a3) ||
63- (cp >= 0xf900 && cp <= 0xfaff) ||
64- (cp >= 0xfe10 && cp <= 0xfe19) ||
65- (cp >= 0xfe30 && cp <= 0xfe6f) ||
66- (cp >= 0xff00 && cp <= 0xff60) ||
67- (cp >= 0xffe0 && cp <= 0xffe6) ||
68- (cp >= 0x1f300 && cp <= 0x1f64f) ||
69- (cp >= 0x1f900 && cp <= 0x1f9ff) ||
70- (cp >= 0x20000 && cp <= 0x3fffd))
71- );
72-}
73-
74-function graphemeWidth(grapheme: string): number {
75- if (!grapheme) return 0;
76- if (emojiLikeRegex.test(grapheme)) return 2;
77-
78- let width = 0;
79- let hasRegionalIndicator = false;
80- for (const ch of grapheme) {
81- const cp = ch.codePointAt(0);
82- if (cp === undefined) continue;
83- if (cp >= 0x1f1e6 && cp <= 0x1f1ff) hasRegionalIndicator = true;
84- if (
85- isControlCodePoint(cp) ||
86- isCombiningCodePoint(cp) ||
87- isVariationSelector(cp) ||
88- cp === 0x200d ||
89- (cp >= 0x1f3fb && cp <= 0x1f3ff)
90- ) {
91- continue;
92- }
93- width += isWideCodePoint(cp) ? 2 : 1;
94- }
95-
96- if (hasRegionalIndicator) return 2;
97- return width;
98-}
99-
100-export function visibleLength(s: string): number {
101- if (!s) return 0;
102- const plain = stripSgrAnsi(s);
103- if (!plain) return 0;
104-
105- if (!graphemeSegmenter) {
106- let width = 0;
107- for (const ch of plain) {
108- const cp = ch.codePointAt(0);
109- if (cp === undefined || isControlCodePoint(cp)) continue;
110- width += isWideCodePoint(cp) ? 2 : 1;
111- }
112- return width;
113- }
114-
115- let width = 0;
116- for (const { segment } of graphemeSegmenter.segment(plain)) {
117- width += graphemeWidth(segment);
118- }
119- return width;
120-}