Skip to content
Source
Sign inSign up
pingdotgg/t3code

perf(shared): fold command output without copying scrollback per chunk #26691

Mergedhieu-lee(GitHub profile, opens in a new tab)merged 1 commit intomain fromrefs/pull/26691/headmerged by maria-rcks View on GitHub

appendTerminalOutput 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 timenew timeold allocatednew allocated
80 chars (19,370)597 ms97 ms (6.1x)4,854 MiB560 MiB (−88%)
1,024 chars (1,514)60.7 ms19.4 ms (3.1x)416 MiB58 MiB (−86%)
16,384 chars (95)15.3 ms13.0 ms (1.18x)40 MiB16 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 run on packages/shared/src/terminalOutput.test.ts, packages/client-runtime/src/state/commandOutput.test.ts and apps/server/src/orchestration-v2/CommandOutputHub.test.ts: 25 pass.
  • vp run check:changed is 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, with maxChars from 16 to 65536 and chunk sizes from 1 to 5000. text, truncated, pending, the joined scrollback, screen lines/row/col/pen/saved and terminalOutputResumeText were 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

    2. Approvability

      Verdict: Approved at e715892

      Macroscope'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).
    3. Review in Change Stack →

      No actionable comments were generated in the recent review.

      Recent review info
      Run configuration
      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.ts
      • packages/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. appendTerminalOutput returns the trimmed parts as combined text and stores settled output in the updated shape.

      Changes: Terminal scrollback

      Layer / File(s)Summary
      Store and update scrollback parts
      packages/shared/src/terminalOutput.ts
      TerminalOutputState.screen.settled changes 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.ts
      Tail trimming prefers a newline when the discarded partial line is less than one quarter of the limit. appendTerminalOutput trims and combines the parts. Tests cover nearby and over-distant newline boundaries.
      Priority: Low

      Estimated 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 to e7158

      The change reorganizes scrollback while preserving text-only output frames. No merge-blocking issue was identified.

      Pre-merge checks: Passed 3 · Failed 1
      Failed Failed checks: 1 warning
      Check nameStatusExplanationResolution
      Description checkWarningThe 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 Passed checks: 3 passed
      Check nameStatusExplanation
      Title checkPassedThe title clearly and concisely describes the primary performance change: reducing scrollback copying while folding command output.
      Linked Issues checkPassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes checkPassedCheck 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
      Comment `@coderabbitai help` to get the list of available commands.
    4. @juliusmarminge ready for review. appendTerminalOutput stops 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 in CommandOutputHub on the server and per frame on clients. Related to #9661. CI workflows on this fork PR show action_required, so they are waiting on a maintainer to approve the run. CodeRabbit and Macroscope are done with no open findings.

    5. maria-rckscommented

      Note

      Written by gpt-6.1-sol on behalf of Maria

      Verified in a real dev environment

      verified unchanged head e715892ac970844588c69490fed26cddc19dee90 on a linux boat vm. installed and ran github/main in 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 codex gpt-6.1-sol turns 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.ts was 3,734.594 ms on main and 369.418 ms on the pr. main's terminalOutputTail alone 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, and CommandOutputHub.test.ts. existing applicable ci checks are green. no source changes or pushes were needed.

      main:

      main command output with truncation and final timing

      pr:

      pr command output with ansi unicode tail and final timing

      pr command output collapse and reopen recording

      command transcript

      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.

    6. Complementary terminal optimization for visibility: #28539 removes the temporary split array from terminalOutputResumeText line 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).

    7. maria-rcks merged thisc2985a7

    8. maria-rcks closed this

Sign in to join this conversation.