perf(shared): fold command output without copying scrollback per chunk #26691
main fromrefs/pull/26691/head·merged by maria-rcks View on GitHubappendTerminalOutput runs on every streamed command-output chunk on the server (CommandOutputHub) and on every output frame on clients. It kept scrolled-out lines as one string of up to 64K chars and cut it twice per chunk (settled + new lines, then settled + live window). V8 flattens a concatenated string the first time it is searched or sliced, so every chunk copied about 128K chars. A chatty build streaming small deltas spent tens of microseconds and about 250 KB of garbage per chunk.
Fix#
TerminalScreen.settled (an internal, in-memory-only field) is now a [head, tail] pair, and only the tail grows. A new terminalOutputTailParts gives exactly what terminalOutputTail(parts.join("")) gives. When the cut is a newline cut, which is the normal case, it searches and slices only the part the cut lands in and returns the other parts unjoined. The rare long-line cut (styleAt) falls back to the joined string. The final text is built with +, so nothing is copied until a reader needs it. Each piece of scrollback is now copied about once as it moves from tail to head, not once per chunk. No wire contract or visible behaviour changes.
Measurements#
Harness: Node 24.18, --expose-gc. It imports the original module (a copy of main) and the new one, then streams 1.55M chars of test-runner-like output (20k lines, every 7th line with SGR colour and a non-Latin-1 char) through appendTerminalOutput at each chunk size. Each variant ran 7 times, interleaved old/new; the table shows the median of the last 6. Allocated bytes are the sum of allocated= from --trace-gc-nvp plus the final heap delta, median of 5 separate processes. Heap-used deltas undercount the old code, because its 128 KB strings go to large-object space and trigger GCs.
| chunk size (chunks) | old time | new time | old allocated | new allocated |
|---|---|---|---|---|
| 80 chars (19,370) | 597 ms | 97 ms (6.1x) | 4,854 MiB | 560 MiB (−88%) |
| 1,024 chars (1,514) | 60.7 ms | 19.4 ms (3.1x) | 416 MiB | 58 MiB (−86%) |
| 16,384 chars (95) | 15.3 ms | 13.0 ms (1.18x) | 40 MiB | 16 MiB (−60%) |
The old 80-char timing varies between 600 and 990 ms with GC pressure. What limits the new number: each chunk still re-serializes the 64-line live window (lines.map(serializeLine).join("\n")), about 5 µs and 29 KB per small chunk. This is now the top self-time in the profile.
Bench script (old vs new, interleaved)
import * as New from "<repo>/packages/shared/src/terminalOutput.ts";
import * as Old from "./terminalOutput.orig.ts"; // copy of main
const ESC = "\u001b";
const out: string[] = [];
for (let i = 0; i < 20000; i++)
out.push(i % 7 === 0
? `${ESC}[32m✓${ESC}[0m test case number ${i} passes in ${i % 97}ms\n`
: ` at Object.<anonymous> (src/file${i}.ts:${i}:12) some log output line here ${i}\n`);
const total = out.join("");
const gc = (globalThis as any).gc as () => void;
for (const chunkSize of [80, 1024, 16384]) {
const chunks: string[] = [];
for (let i = 0; i < total.length; i += chunkSize) chunks.push(total.slice(i, i + chunkSize));
const t: Record<string, number[]> = { old: [], new: [] };
for (let r = 0; r < 7; r++) {
for (const [name, mod] of [["old", Old], ["new", New]] as const) {
gc(); gc();
const t0 = performance.now();
let s: any = mod.EMPTY_TERMINAL_OUTPUT;
for (const c of chunks) s = mod.appendTerminalOutput(s, c);
if (r > 0) t[name]!.push(performance.now() - t0);
(globalThis as any).sink = s;
}
}
const med = (xs: number[]) => xs.sort((a, b) => a - b)[xs.length >> 1]!;
console.log(chunkSize, "old", med(t.old!), "new", med(t.new!));
}
// Allocation: same stream once per process after 2 warm runs, summing `allocated=` from
// `node --expose-gc --trace-gc-nvp` between start/end markers plus the final heapUsed delta.
Validation#
vp test runonpackages/shared/src/terminalOutput.test.ts,packages/client-runtime/src/state/commandOutput.test.tsandapps/server/src/orchestration-v2/CommandOutputHub.test.ts: 25 pass.vp run check:changedis clean (format, lint, knip, typecheck, tests).- Differential fuzz of the original module against the new one: about 460k random chunk applications. Inputs mix SGR, cursor moves, erase,
ESC[2J/ESC[3J, save/restore, OSC, lone surrogates and long lines, withmaxCharsfrom 16 to 65536 and chunk sizes from 1 to 5000.text,truncated,pending, the joined scrollback, screen lines/row/col/pen/saved andterminalOutputResumeTextwere identical after every chunk, so server and client folds still agree. - Mutating the new quarter-budget boundary (
>=to>) passed the existing tests, so I added an assertion pair for that boundary to the existing bounded-tail test.
Not checked: I did not run a real client or a real provider stream. The change touches no UI and the output is byte-identical.
Authored with Claude Opus 5.5 via the Claude Code harness in T3 Code.
🤖 Generated with Claude Code
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:M
Approvability#
Verdict: Approved at
e715892Macroscope's review found this PR approvable — This reduces repeated scrollback copying in server and client command-output folding without changing product defaults or the output contract. Bounded retention and reported differential validation support a low-risk performance optimization.
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).No actionable comments were generated in the recent review.
Recent review info-
Run configuration-
- Source mode: Auto
- Repository: pingdotgg/t3code
- Branch: main
- File: .coderabbit.config.ts
- Commit: 9826dbb
- Layers: Repository TS config
- Review profile: CHILL
- Plan: Advanced
- Run ID:
0b9d5a80-0706-4177-82d9-3895205ad323
Commits-
Reviewing files that changed from the base of the PR and between 9826dbb9904b2591bfbf60d1317486b59132f56b and e715892ac970844588c69490fed26cddc19dee90.
Files selected for processing: 2-
packages/shared/src/terminalOutput.test.tspackages/shared/src/terminalOutput.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.
-
Walkthrough
-
Settled terminal scrollback now uses a head-and-tail pair. The terminal appends and clears both parts, and tail trimming can select a nearby newline boundary.
appendTerminalOutputreturns the trimmed parts as combined text and stores settled output in the updated shape.Changes: Terminal scrollback
Priority:Layer / File(s) Summary Store and update scrollback parts
packages/shared/src/terminalOutput.tsTerminalOutputState.screen.settledchanges to a head-and-tail tuple. The terminal initializes, appends, repartitions, and clears both parts.Trim and compose terminal output
packages/shared/src/terminalOutput.ts,packages/shared/src/terminalOutput.test.tsTail trimming prefers a newline when the discarded partial line is less than one quarter of the limit. appendTerminalOutputtrims and combines the parts. Tests cover nearby and over-distant newline boundaries. LowEstimated code review effort: 2 (Simple) | ~10 minutes
Possibly related issues
pingdotgg/t3code#20535— This issue also concerns repeated materialization of retained terminal history.
Possibly related PRs
- pingdotgg/t3code#24261 — Adds incremental mobile terminal output delivery that consumes terminal output snapshots.
- pingdotgg/t3code#24783 — Adds capability-gated incremental output delivery using the shared terminal output state.
- pingdotgg/t3code#25071 — Moves mobile terminal lifecycle handling into a session store and carries the incremental output writer.
Suggested reviewers:
maria-rcks
Merge Risk:
Minimal · up toe7158-
The change reorganizes scrollback while preserving text-only output frames. No merge-blocking issue was identified.
Pre-merge checks:
3 · 1-
Failed checks: 1 warningCheck name Status Explanation Resolution Description check The description clearly explains the problem, implementation, performance measurements, validation results, and untested scenarios. It does not provide the required Scope and approval information, suc… Add a Scope and approval section. Include the triaged bug or approval discussion with the approval comment, or explain why this focused performance fix is an obvious bug that qualifies without prior approval. Passed checks: 3 passed-
Check name Status Explanation Title check The title clearly and concisely describes the primary performance change: reducing scrollback copying while folding command output. Linked Issues check Check skipped because no linked issues were found for this pull request. Out of Scope Changes check Check skipped because no linked issues were found for this pull request.
Full details: Description check
-
Explanation
The description clearly explains the problem, implementation, performance measurements, validation results, and untested scenarios. It does not provide the required Scope and approval information, such as a linked issue, maintainer approval, or an explanation for why this focused fix is exempt.
Resolution
Add a Scope and approval section. Include the triaged bug or approval discussion with the approval comment, or explain why this focused performance fix is an obvious bug that qualifies without prior approval.
-
Finishing Touches
-
🧪 Generate unit tests (beta)
-
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
-
@juliusmarminge ready for review.
appendTerminalOutputstops copying the whole scrollback twice per chunk: 80-char chunks 597 ms to 97 ms and 4,854 to 560 MiB allocated; 16 KiB chunks about 60% less memory. It runs per chunk inCommandOutputHubon the server and per frame on clients. Related to #9661. CI workflows on this fork PR showaction_required, so they are waiting on a maintainer to approve the run. CodeRabbit and Macroscope are done with no open findings.Note
Written by
gpt-6.1-solon behalf of MariaVerified in a real dev environment#
verified unchanged head
e715892ac970844588c69490fed26cddc19dee90on a linux boat vm. installed and rangithub/mainin a separate worktree first, stopped it, then installed and ran the exact pr head. used playwright with google chrome, added the real repository through the app, and submitted real codexgpt-6.1-solturns through the composer.the provider streamed 20,000 numbered tracked paths with ansi colour and unicode. the expanded command row received live append frames, retained the bounded tail, and showed "Earlier output not shown". collapse/reopen during streaming recovered the output. after completion, reload/reopen restored identical inspector text and the final marker. a neighboring command with a split ansi sequence, an 80,000-character coloured line, emoji, and carriage-return/erase-line progress updates retained the final styles and showed only progress 100%.
live server profiling reproduced main's scrollback hotspot: sampled self time in
terminalOutput.tswas 3,734.594 ms on main and 369.418 ms on the pr. main'sterminalOutputTailalone accounted for 3,316.155 ms. these are single-run cpu samples through the actual provider path, not an end-to-end speed guarantee; the paced producer took 42.977 s and 42.319 s respectively. path lists reflect each checkout.all 25 existing focused tests passed on blacksmith across
terminalOutput.test.ts,commandOutput.test.ts, andCommandOutputHub.test.ts. existing applicable ci checks are green. no source changes or pushes were needed.main:

pr:


Not verified#
native ios/android, the electron shell, macos/windows, other providers, and remote relay/tunnel connections were not exercised on this linux web setup. heap allocation reduction and statistically repeated performance measurements were not measured.
Complementary terminal optimization for visibility: #28539 removes the temporary
splitarray fromterminalOutputResumeTextline counting, using O(1) auxiliary counting space with no worse time complexity. This is the resume/reopen path, not the streaming tail-folding work in this PR. Maria has posted live verification on #28539; the required output stream is still O(n).maria-rcks merged thisc2985a7
maria-rcks closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes