diff --git a/java/junit-runner/README.md b/java/junit-runner/README.md index a576e95a1..8537417d0 100644 --- a/java/junit-runner/README.md +++ b/java/junit-runner/README.md @@ -6,6 +6,11 @@ parameterized tests run too) and prints each test as the TeamCity service messag `src/features/run/gradleTests.gradle`, which the Run window's JVM parser already reads. It exits with 1 when a test failed or none ran. +A test's stdout and stderr are reported with it (`testStdOut`, `testStdErr`), line by line as they +are written; a class's own output (static initializers, `@BeforeAll`) with the class, and output +outside any test, such as a thread the test started, is printed as is. Each line is printed once: +JUnit's own output capture, which also copies everything to the original stream, stays off. + JUnit Platform tests run on the Platform launcher. JUnit 4 and JUnit 3 tests run on JUnit 4's own `JUnitCore` (`Junit4Runner`) when the classpath has no JUnit Platform, or one without the Vintage engine, so a JUnit 4 project needs nothing beyond its `junit` dependency. diff --git a/java/junit-runner/build.py b/java/junit-runner/build.py index 96cb5f175..ec6a47d81 100644 --- a/java/junit-runner/build.py +++ b/java/junit-runner/build.py @@ -58,6 +58,11 @@ with tempfile.TemporaryDirectory() as scratch: missing = [e for e in expected if e not in out] assert not missing, missing assert run.returncode == 1, run.returncode + # Each line once: a test's output only in its messages, a thread outside any test's as is. + assert "##teamcity[testStdErr name='passes' className='sample.SampleTest' out='to stderr|n']" in out, out + assert "##teamcity[testStdOut className='sample.SampleTest' out='class set-up|n']" in out, out + assert all(out.count(text) == 1 for text in ("hello", "to stderr", "loaded", "class set-up")), out + assert "\nfrom a thread\n" in out and out.count("from a thread") == 1, out method = subprocess.run([tool("java"), "-cp", os.pathsep.join([str(classes), str(sample), cp]), "ai.openidea.junit.Runner", "sample.SampleTest#parameterized"], capture_output=True) assert method.stdout.decode().count("testStarted") == 2, method.stdout diff --git a/java/junit-runner/openidea-junit-runner.jar b/java/junit-runner/openidea-junit-runner.jar index 9250f777f..1a18960b4 100644 Binary files a/java/junit-runner/openidea-junit-runner.jar and b/java/junit-runner/openidea-junit-runner.jar differ diff --git a/java/junit-runner/src/ai/openidea/junit/PlatformRunner.java b/java/junit-runner/src/ai/openidea/junit/PlatformRunner.java index 0f921d443..1d4e2d845 100644 --- a/java/junit-runner/src/ai/openidea/junit/PlatformRunner.java +++ b/java/junit-runner/src/ai/openidea/junit/PlatformRunner.java @@ -1,7 +1,14 @@ package ai.openidea.junit; +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Deque; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -10,7 +17,6 @@ import org.junit.platform.engine.DiscoverySelector; import org.junit.platform.engine.TestExecutionResult; import org.junit.platform.engine.TestSource; import org.junit.platform.engine.discovery.DiscoverySelectors; -import org.junit.platform.engine.reporting.ReportEntry; import org.junit.platform.engine.support.descriptor.ClassSource; import org.junit.platform.engine.support.descriptor.MethodSource; import org.junit.platform.launcher.Launcher; @@ -20,27 +26,47 @@ import org.junit.platform.launcher.TestPlan; import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; import org.junit.platform.launcher.core.LauncherFactory; -/** Runs JUnit Platform tests (Jupiter, and JUnit 4 through the Vintage engine when it is on the classpath). */ +/** + * Runs JUnit Platform tests (Jupiter, and JUnit 4 through the Vintage engine when it is on the classpath). + * A thread's stdout and stderr while it runs a test (or a class's set-up) are reported with it, line by + * line; any other output is printed as is. + */ final class PlatformRunner implements TestExecutionListener { private final Reporter report; private final Map started = new HashMap<>(); + /** The tests and classes each thread is running, innermost first: its output belongs to the first. */ + private final ThreadLocal> owners = ThreadLocal.withInitial(ArrayDeque::new); + private final List outputs = new ArrayList<>(); private TestPlan plan; private PlatformRunner(Reporter report) { this.report = report; } - static void run(Reporter report, String[] args) { + static void run(Reporter report, String[] args) throws UnsupportedEncodingException { List selectors = new ArrayList<>(); for (String arg : args) selectors.addAll(selectors(arg)); Launcher launcher = LauncherFactory.create(); - launcher.execute( - LauncherDiscoveryRequestBuilder.request() - .selectors(selectors) - .configurationParameter("junit.platform.output.capture.stdout", "true") - .configurationParameter("junit.platform.output.capture.stderr", "true") - .build(), - new PlatformRunner(report)); + PlatformRunner listener = new PlatformRunner(report); + PrintStream stdout = System.out; + PrintStream stderr = System.err; + System.setOut(new PrintStream(listener.new Output("testStdOut", null), true, "UTF-8")); + System.setErr(new PrintStream(listener.new Output("testStdErr", stderr), true, "UTF-8")); + try { + // JUnit's own capture also writes everything to the original stream: each line would show twice. + launcher.execute( + LauncherDiscoveryRequestBuilder.request() + .selectors(selectors) + .configurationParameter("junit.platform.output.capture.stdout", "false") + .configurationParameter("junit.platform.output.capture.stderr", "false") + .build(), + listener); + } finally { + System.out.flush(); + System.err.flush(); + System.setOut(stdout); + System.setErr(stderr); + } } /** Every method named {@code method} (parameterized ones too); the class when there is none. */ @@ -75,6 +101,11 @@ final class PlatformRunner implements TestExecutionListener { @Override public void executionStarted(TestIdentifier id) { + String owner = owner(id); + if (owner != null) { + flushOutput(); + owners.get().push(owner); + } if (!id.isTest()) return; started.put(id.getUniqueId(), System.currentTimeMillis()); report.message("testStarted", id(id)); @@ -90,6 +121,10 @@ final class PlatformRunner implements TestExecutionListener { @Override public void executionFinished(TestIdentifier id, TestExecutionResult result) { + if (owner(id) != null) { + flushOutput(); + owners.get().pop(); + } TestExecutionResult.Status status = result.getStatus(); if (!id.isTest()) { // A class whose set-up failed (`@BeforeAll`): reported as a test, like JUnit 4's initializationError. @@ -108,15 +143,13 @@ final class PlatformRunner implements TestExecutionListener { report.finished(own, start == null ? 0 : System.currentTimeMillis() - start); } - @Override - public void reportingEntryPublished(TestIdentifier id, ReportEntry entry) { - for (Map.Entry e : entry.getKeyValuePairs().entrySet()) { - String kind = e.getKey().equals("stdout") ? "testStdOut" : e.getKey().equals("stderr") ? "testStdErr" : null; - if (kind == null) continue; - // A class's own output (`@BeforeAll`, `@AfterAll`) carries no test name. - String own = id.isTest() ? id(id) : className(id).map(c -> Reporter.attr("className", c)).orElse(null); - if (own != null) report.message(kind, own + Reporter.attr("out", e.getValue())); - } + /** Whose output a thread's is while it runs {@code id}: the test, or a class (`@BeforeAll`, `@AfterAll`) with no test name. */ + private String owner(TestIdentifier id) { + return id.isTest() ? id(id) : className(id).map(c -> Reporter.attr("className", c)).orElse(null); + } + + private void flushOutput() { + for (Output o : outputs) o.flushLines(true); } /** `name='method' className='a.B$Nested'`, the method and class of the test or its closest source. */ @@ -137,4 +170,55 @@ final class PlatformRunner implements TestExecutionListener { TestSource source = id.getSource().orElse(null); return source instanceof ClassSource ? Optional.of(((ClassSource) source).getClassName()) : Optional.empty(); } + + /** System.out or System.err: reported with the thread's test, else passed through ({@code null}: the reporter's stdout). */ + private final class Output extends OutputStream { + private final String kind; + private final PrintStream passThrough; + private final ThreadLocal pending = ThreadLocal.withInitial(ByteArrayOutputStream::new); + + Output(String kind, PrintStream passThrough) { + this.kind = kind; + this.passThrough = passThrough; + outputs.add(this); + } + + @Override + public void write(int b) { + write(new byte[] {(byte) b}, 0, 1); + } + + @Override + public void write(byte[] b, int off, int len) { + if (owners.get().isEmpty()) { + if (passThrough == null) report.write(b, off, len); + else { + passThrough.write(b, off, len); + passThrough.flush(); + } + return; + } + pending.get().write(b, off, len); + for (int i = off; i < off + len; i++) { + if (b[i] == '\n') { + flushLines(false); + return; + } + } + } + + /** The thread's complete lines, or with {@code all} its partial line too, as a message of its test. */ + void flushLines(boolean all) { + String owner = owners.get().peek(); + ByteArrayOutputStream buffer = pending.get(); + if (owner == null || buffer.size() == 0) return; + byte[] bytes = buffer.toByteArray(); + int end = bytes.length; + if (!all) while (end > 0 && bytes[end - 1] != '\n') end--; + if (end == 0) return; + buffer.reset(); + buffer.write(bytes, end, bytes.length - end); + report.message(kind, owner + Reporter.attr("out", new String(bytes, 0, end, StandardCharsets.UTF_8))); + } + } } diff --git a/java/junit-runner/src/ai/openidea/junit/Reporter.java b/java/junit-runner/src/ai/openidea/junit/Reporter.java index e0472750b..52b696ec3 100644 --- a/java/junit-runner/src/ai/openidea/junit/Reporter.java +++ b/java/junit-runner/src/ai/openidea/junit/Reporter.java @@ -24,6 +24,14 @@ final class Reporter { } } + /** Output written outside any test, as it was written. */ + void write(byte[] bytes, int off, int len) { + synchronized (out) { + out.write(bytes, off, len); + out.flush(); + } + } + /** Output written outside any test. */ void print(String text) { synchronized (out) { diff --git a/java/junit-runner/tests/SampleTest.java b/java/junit-runner/tests/SampleTest.java index 7a071316c..aa5a59715 100644 --- a/java/junit-runner/tests/SampleTest.java +++ b/java/junit-runner/tests/SampleTest.java @@ -3,6 +3,7 @@ package sample; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assumptions.assumeTrue; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; @@ -10,9 +11,22 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; class SampleTest { + static { + System.out.println("loaded"); + } + + @BeforeAll + static void setUp() { + System.out.println("class set-up"); + } + @Test - void passes() { + void passes() throws InterruptedException { System.out.println("hello [ünï]"); + System.err.println("to stderr"); + Thread other = new Thread(() -> System.out.println("from a thread")); + other.start(); + other.join(); } @Test diff --git a/src/features/run/store.ts b/src/features/run/store.ts index 170969aca..f5c8757e1 100644 --- a/src/features/run/store.ts +++ b/src/features/run/store.ts @@ -127,6 +127,8 @@ interface SessionRuntime { pluginTests: PluginTestOutput | null; /** Machine-readable stdout (`go test -json`, `--teamcity`, the Ruby reporter): fed to the parser, shown decoded. */ stdout: TestStdout | null; + /** "Show console when a message is printed to stderr", for stderr decoded from `stdout` (`testStdErr`). */ + onDecodedStderr?: () => void; queue: OutputChunk[]; /** * rAF id while the page is visible, timeout id while hidden (rAF pauses in @@ -696,10 +698,12 @@ function flush(sessionId: string) { rt.flushedAt = performance.now(); const chunks = rt.queue.splice(0); for (const c of chunks) { - const text = c.kind === "stdout" && rt.stdout ? rt.stdout.feed(c.text) : c.text; - if (!text) continue; - rt.console.append({ ...c, text }); - for (const l of rt.outputListeners) l(c.kind, text); + for (const shown of c.kind === "stdout" && rt.stdout ? rt.stdout.feed(c.text) : [c]) { + if (!shown.text) continue; + rt.console.append(shown); + for (const l of rt.outputListeners) l(shown.kind, shown.text); + if (shown.kind === "stderr" && c.kind === "stdout") rt.onDecodedStderr?.(); + } } bump(sessionId); } @@ -1117,6 +1121,7 @@ async function startRunIn( return getSession(sessionId) ?? null; } + rt.onDecodedStderr = !check && config.showOnStderr ? () => revealSession(sessionId) : undefined; const channel = new Channel(); channel.onmessage = (chunk) => { if (runtimes.get(sessionId)?.generation !== generation) return; @@ -1333,10 +1338,7 @@ function finishSession(sessionId: string, code: number | null) { void (async () => { if (runtimes.get(sessionId) !== rt) return; flush(sessionId); - if (rt.stdout) { - const text = rt.stdout.end(); - if (text) rt.console.append({ kind: "stdout", text }); - } + if (rt.stdout) for (const shown of rt.stdout.end()) rt.console.append(shown); rt.console.flush(); await rt.pluginTests?.end(); if (runtimes.get(sessionId) !== rt) return; diff --git a/src/features/run/testStderr.test.ts b/src/features/run/testStderr.test.ts new file mode 100644 index 000000000..6b4256147 --- /dev/null +++ b/src/features/run/testStderr.test.ts @@ -0,0 +1,62 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import type { OutputChunk, RunConfig } from "@/platform/ipc"; + +const ipc = vi.hoisted(() => ({ + runStart: vi.fn(async (_config: RunConfig, _channel: unknown) => ({ status: "ok", data: { id: 7, pty: false } })), +})); +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } }; +}); +vi.mock("@tauri-apps/api/core", async (importOriginal) => ({ + ...(await importOriginal()), + Channel: class { + onmessage: ((m: unknown) => void) | null = null; + }, +})); + +import { useProject } from "@/platform/project"; +import { provideToolWindowService, type ToolWindowService } from "@/workbench/contributions"; +import { runtime, startRun } from "./store"; + +// OpenIDEA's JUnit runner and Gradle's test init script report through the same service messages. +const gradle = { + id: "gradle:test", + name: "test", + kind: "gradle", + command: "./gradlew", + args: ["test"], + cwd: null, + env: {}, + isTest: true, + showOnStderr: true, +} as unknown as RunConfig; + +beforeEach(() => { + useProject.setState({ settings: null, project: { root: "/p" } as never }); +}); + +it("shows a test's stderr (`testStdErr`) as stderr and reveals the console for it", async () => { + const show = vi.fn(); + provideToolWindowService({ show, hide: vi.fn(), isVisible: () => false } as unknown as ToolWindowService); + const session = await startRun(gradle, undefined, undefined, { prepared: true }); + const channel = ipc.runStart.mock.calls[0]![1] as { onmessage: (chunk: OutputChunk) => void }; + show.mockClear(); + channel.onmessage({ + kind: "stdout", + text: [ + "##teamcity[testStarted name='prints' className='demo.GreeterTest']", + "##teamcity[testStdOut name='prints' className='demo.GreeterTest' out='out|n']", + "##teamcity[testStdErr name='prints' className='demo.GreeterTest' out='err|n']", + "##teamcity[testFinished name='prints' className='demo.GreeterTest' duration='1']", + "", + ].join("\n"), + }); + await vi.waitFor(() => + expect(runtime(session!.id)!.console.textChunks()).toEqual([ + { kind: "stdout", text: "out\n" }, + { kind: "stderr", text: "err\n" }, + ]), + ); + expect(show).toHaveBeenCalledWith("run"); +}); diff --git a/src/features/run/testing/go.test.ts b/src/features/run/testing/go.test.ts index 41226b5e3..adb560669 100644 --- a/src/features/run/testing/go.test.ts +++ b/src/features/run/testing/go.test.ts @@ -130,12 +130,15 @@ describe("Go JSON tests", () => { const line = record("p", "output", "TestFail", { Output: " main_test.go:6: failure " + "x".repeat(9000) + "\n", }); - expect(output.feed(line.slice(0, 22))).toBe(""); - const text = output.feed(line.slice(22) + "\n" + record("p", "fail", "TestFail")); + expect(output.feed(line.slice(0, 22))).toEqual([]); + const text = output + .feed(line.slice(22) + "\n" + record("p", "fail", "TestFail")) + .map((c) => c.text) + .join(""); expect(text).toContain("main_test.go:6: failure"); expect(text).not.toContain('"Action"'); expect(findOutputLinks(text.slice(0, 100)).some((link) => link.kind === "file")).toBe(true); - expect(output.end()).toBe(""); + expect(output.end()).toEqual([]); expect(results.counts().failed).toBe(1); }); diff --git a/src/features/run/testing/nodeTest.test.ts b/src/features/run/testing/nodeTest.test.ts index ed5e3e324..4795a1497 100644 --- a/src/features/run/testing/nodeTest.test.ts +++ b/src/features/run/testing/nodeTest.test.ts @@ -75,7 +75,10 @@ describe("node:test reporter records", () => { it("are hidden from the console", () => { const fed: string[] = []; - const console = new RecordsOutput((line) => fed.push(line)).feed(OUTPUT + "\n"); + const console = new RecordsOutput((line) => fed.push(line)) + .feed(OUTPUT + "\n") + .map((c) => c.text) + .join(""); expect(console).not.toContain("@@openidea"); expect(console).toContain(" ✔ adds items (0.4259ms)\n"); expect(fed.filter((l) => l.startsWith("@@openidea"))).toHaveLength(8); diff --git a/src/features/run/testing/phpunit.test.ts b/src/features/run/testing/phpunit.test.ts index 79b0b9614..6ea116aaa 100644 --- a/src/features/run/testing/phpunit.test.ts +++ b/src/features/run/testing/phpunit.test.ts @@ -111,17 +111,21 @@ describe("TeamcityOutput", () => { const results = new TestResults(); const parser = phpunitParser(); const output = new TeamcityOutput((line) => results.apply(parser.feed(line))); - const shown = - output.feed( + const shown = [ + ...output.feed( "PHPUnit 11.5 by Sebastian Bergmann\n##teamcity[testSuiteStarted name='CalcTest']\n##teamcity[testStar", - ) + - output.feed("ted name='testAdd']\r\n##teamcity[testFinished name='testAdd' duration='1']\nOK (1 test") + - output.end(); - expect(shown).toBe("PHPUnit 11.5 by Sebastian Bergmann\nOK (1 test\n"); + ), + ...output.feed("ted name='testAdd']\r\n##teamcity[testFinished name='testAdd' duration='1']\nOK (1 test"), + ...output.end(), + ]; + expect(shown).toEqual([ + { kind: "stdout", text: "PHPUnit 11.5 by Sebastian Bergmann\n" }, + { kind: "stdout", text: "OK (1 test\n" }, + ]); expect(results.counts()).toMatchObject({ passed: 1 }); }); - it("shows a test's own output and failures in the console when asked (JVM runs)", () => { + it("shows a test's own output, its stderr as stderr, and failures in the console when asked (JVM runs)", () => { const lines = [ "##teamcity[testStarted name='prints' className='demo.GreeterTest']", "##teamcity[testStdOut name='prints' className='demo.GreeterTest' out='输出结果:OpenIdea|n']", @@ -134,11 +138,16 @@ describe("TeamcityOutput", () => { "", ].join("\n"); const fed: string[] = []; - expect(new TeamcityOutput((line) => fed.push(line), true).feed(lines)).toBe( - "输出结果:OpenIdea\nwarn [x]\njava.lang.AssertionError: no\n\tat demo.GreeterTest.fails(GreeterTest.java:15)\n1 test completed\n", - ); + expect(new TeamcityOutput((line) => fed.push(line), true).feed(lines)).toEqual([ + { kind: "stdout", text: "输出结果:OpenIdea\n" }, + { kind: "stderr", text: "warn [x]\n" }, + { + kind: "stdout", + text: "java.lang.AssertionError: no\n\tat demo.GreeterTest.fails(GreeterTest.java:15)\n1 test completed\n", + }, + ]); expect(fed).toHaveLength(8); - expect(new TeamcityOutput(() => {}).feed(lines)).toBe("1 test completed\n"); + expect(new TeamcityOutput(() => {}).feed(lines)).toEqual([{ kind: "stdout", text: "1 test completed\n" }]); }); }); diff --git a/src/features/run/testing/ruby.test.ts b/src/features/run/testing/ruby.test.ts index 1139bc54d..a4e294d7f 100644 --- a/src/features/run/testing/ruby.test.ts +++ b/src/features/run/testing/ruby.test.ts @@ -152,7 +152,7 @@ describe("the IDE's Minitest reporter", () => { const collect = (chunks: string[]) => { const lines: string[] = []; const out = new RubyTestOutput((line) => lines.push(line)); - const text = chunks.map((c) => out.feed(c)).join("") + out.end(); + const text = [...chunks.flatMap((c) => out.feed(c)), ...out.end()].map((c) => c.text).join(""); return { text, records: lines.filter((l) => l.includes(M)), lines }; }; diff --git a/src/features/run/testing/teamcity.ts b/src/features/run/testing/teamcity.ts index 600c9b2a7..67d3aa440 100644 --- a/src/features/run/testing/teamcity.ts +++ b/src/features/run/testing/teamcity.ts @@ -33,7 +33,7 @@ export function serviceMessage(line: string): ServiceMessage | null { * Console text of a run reporting through service messages: the messages feed the test tree. With * `testOutput`, a test's own stdout / stderr (`testStdOut`, `testStdErr`) and its failure are shown in * the console too, so the run reads like the program's output with no test selected (OpenIDEA's JUnit - * runner and the Gradle init script report them only through these messages). + * runner and the Gradle init script report them only through these messages), `testStdErr` as stderr. */ export class TeamcityOutput extends TestStdout { constructor(feedLine: (line: string) => void, testOutput = false) { @@ -41,7 +41,8 @@ export class TeamcityOutput extends TestStdout { if (!MESSAGE_RE.test(line)) return line + "\n"; if (!testOutput) return ""; const message = serviceMessage(line); - if (message?.kind === "testStdOut" || message?.kind === "testStdErr") return message.attrs.out ?? ""; + if (message?.kind === "testStdOut") return message.attrs.out ?? ""; + if (message?.kind === "testStdErr") return { kind: "stderr", text: message.attrs.out ?? "" }; if (message?.kind !== "testFailed") return ""; const failure = (message.attrs.details || message.attrs.message || "").replace(/\n$/, ""); return failure ? failure + "\n" : ""; diff --git a/src/features/run/testing/types.ts b/src/features/run/testing/types.ts index 6291f3fd2..cc9071a1c 100644 --- a/src/features/run/testing/types.ts +++ b/src/features/run/testing/types.ts @@ -2,6 +2,7 @@ * Test runner output parsing. Each framework parser turns plain output lines * (ANSI already stripped) into events; `TestResults` folds them into a tree. */ +import type { OutputChunk } from "@/bindings"; export type TestStatus = "running" | "passed" | "failed" | "skipped"; @@ -60,28 +61,39 @@ export function formatDuration(ms: number | undefined): string { /** * Stdout of a runner that prints machine-readable records (`go test -json`, PHPUnit `--teamcity`): - * feeds complete, unsplit lines to the test parser and returns each line's console text. + * feeds complete, unsplit lines to the test parser and returns their console text. A line shows as + * stdout, or as a chunk of its own kind (a test's stderr reported on stdout, `testStdErr`). */ export class TestStdout { private pending = ""; constructor( private readonly feedLine: (line: string) => void, - private readonly display: (line: string) => string, + private readonly display: (line: string) => string | OutputChunk, ) {} - feed(text: string): string { + feed(text: string): OutputChunk[] { this.pending += text; const lines = this.pending.split("\n"); this.pending = lines.pop()!; - return lines.map((line) => this.line(line)).join(""); + return this.chunks(lines); } - end(): string { + end(): OutputChunk[] { const pending = this.pending; this.pending = ""; - return pending ? this.line(pending) : ""; + return pending ? this.chunks([pending]) : []; } - private line(raw: string): string { - const line = raw.replace(/\r$/, ""); - this.feedLine(line); - return this.display(line); + /** Consecutive lines of one kind in one chunk. */ + private chunks(lines: string[]): OutputChunk[] { + const out: OutputChunk[] = []; + for (const raw of lines) { + const line = raw.replace(/\r$/, ""); + this.feedLine(line); + const shown = this.display(line); + const chunk = typeof shown === "string" ? { kind: "stdout" as const, text: shown } : shown; + if (!chunk.text) continue; + const last = out[out.length - 1]; + if (last?.kind === chunk.kind) last.text += chunk.text; + else out.push({ ...chunk }); + } + return out; } }