Repository navigation
perf(agent-status): strip terminal control bytes by run, not per character - #10866
Conversation
…acter stripTerminalControl built its result with a per-character `+=`, allocating a fresh string for every retained character. The Command Code status detector calls it four times per PTY chunk — the scan text, the chunk-boundary variant, and both previous-text lengths — so an agent pane paid that on every write. Control bytes are sparse in real output, so copy the spans between them instead: 2.3x-2.6x from 5 KiB to 106 KiB chunks. Output is byte-identical, checked exhaustively over every string up to length 4 across a 13-symbol control/unicode alphabet plus 200k random strings (224,831 inputs, 0 mismatches).
📝 WalkthroughWalkthroughUpdated terminal control stripping to preserve unchanged strings when possible and concatenate printable runs instead of appending characters individually. Added tests covering control bytes around prompts and multi-byte characters. Added a configurable benchmark comparing both stripping strategies across synthetic TUI-like outputs. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: fe00261f-d317-4826-8bac-e4dae5e85cdc
📒 Files selected for processing (3)
config/scripts/terminal-control-strip-benchmark.mjssrc/shared/command-code-output-status.test.tssrc/shared/command-code-output-status.ts
Review feedback: both comments walked through the implementation. Keep one line of non-obvious rationale each, per the repo's comment guidelines. Co-authored-by: Orca <[email protected]>
|
Addressed in bd80fbf. Both comments were walking through the implementation; each is now a single line of non-obvious rationale ( |
…acter (stablyai#10866) * perf(agent-status): strip terminal control bytes by run, not per character stripTerminalControl built its result with a per-character `+=`, allocating a fresh string for every retained character. The Command Code status detector calls it four times per PTY chunk — the scan text, the chunk-boundary variant, and both previous-text lengths — so an agent pane paid that on every write. Control bytes are sparse in real output, so copy the spans between them instead: 2.3x-2.6x from 5 KiB to 106 KiB chunks. Output is byte-identical, checked exhaustively over every string up to length 4 across a 13-symbol control/unicode alphabet plus 200k random strings (224,831 inputs, 0 mismatches). * docs(agent-status): condense the run-copy rationale comments Review feedback: both comments walked through the implementation. Keep one line of non-obvious rationale each, per the repo's comment guidelines. Co-authored-by: Orca <[email protected]> * test(agent-status): correct terminal strip benchmark * test(agent-status): bound terminal strip benchmark --------- Co-authored-by: Orca <[email protected]>
Summary
stripTerminalControlbuilt its result with a per-character+=, allocating a fresh string for every retained character.The Command Code status detector calls it four times per PTY chunk — the combined scan text, the chunk-boundary variant, and both previous-text lengths — on every write once a Command Code pane is live. Control bytes are sparse in real agent output, so copying the spans between them is far cheaper than appending character by character.
ELI5
Agent output arrives full of invisible control codes that have to be removed before Orca can read the text.
The old code walked the text one character at a time and glued each keeper onto a growing string, creating allocation pressure for every retained character. The detector's four per-chunk calls are bounded to 4,096, 4,096, 300, and 301 code units, so the work is bounded but repeated.
Now it finds the stretches of clean text between control codes and copies each stretch in one go. Same output, a fraction of the work — and it happens four times for every chunk of output an agent produces.
Screenshots
No visual change.
Proof of performance improvement
node config/scripts/terminal-control-strip-benchmark.mjs:The benchmark mirrors the complete pre/post
stripTerminalControlpaths, including the unchanged guard and ANSI stripping. Its agent-TUI-shaped fixtures match the detector’s production bounds: 300 code units of recent history, the 301-unit chunk-boundary variant, and 4096-unit scan text. The pathological dense fixture is also bounded to 4096 units and alternates printable bytes with C0 controls (49.6% controls).Timing is first-touch and counterbalanced: each measured pair independently builds equal-length, output-equivalent inputs for the two arms, neither input is reused, and every iteration measures both call orders. Every timed output is checked for equality and folded into the printed checksum so V8 cannot discard the work.
The representative TUI rows are 1.46–1.60× faster. The pathological 49.6%-control row is honestly slower at 0.78×; production logic is unchanged because real TUI control bytes are sparse and every call is already bounded.
Proof of zero regression
The output is byte-identical. Since this is a pure string function, I proved that rather than argued it:
\x00,\x07,\x1f(C0 kept/stripped boundary),\n,\r(the two explicit exemptions),\x7f,\x9f(C1 range edges),\xa0(just past it), plus ASCII, accented, CJK, and an astral emoji.That covers the cases this rewrite could plausibly break: a control byte at index 0, at the final index, several adjacent, and a string containing none at all (which now returns the input untouched rather than rebuilding it).
Four new tests driving the real exported detector — control bytes leading, trailing, adjacent, and none — plus multi-byte preservation.
Mutation tested, 2/2 killed:
return output)pnpm lintpnpm typecheckpnpm test— 3134/3134 acrosssrc/shared/; 92/92 in the touched filePre-existing test failures
Full suite: 5 failures / 37,128. Two are
agent-exec-handler.test.ts, which assert against the machine's realprocess.env. The others —transcript-watch×2 andproject-view-wrapper-source-context-boundary— pass 30/30 in isolation and import nothing from the changed file. They join the load-flaky pool this series has tracked across ~16 full-suite runs, where two consecutive runs on unmodifiedmainproduce different failure sets. (A sixth reported failure was a stray scratch file another agent left in this shared checkout; removed.)Review loop count + verdict
3 review loops: implementation review, adversarial correction, and clean re-review. Final verdict: ship.
Found by a discovery sweep over
src/shared, then verified by hand before implementing — I traced the call chain to confirm the four-calls-per-chunk claim and, importantly, checked where the guard stops helping: the detector has a!hasSeenCommandCodeUiearly-out, but that latches totrueafter the banner is seen, and the four strip calls sit after it. So on a live Command Code pane this runs unconditionally per chunk.The same sweep surfaced two neighbouring candidates I rejected with numbers:
shouldIncludeQuickOpenPathsubstring allocations — 1.76 ms for the entire 10,287-file repo (0.172 µs/path), and only during an explicit search. Its own doc comment already notes it avoids a split allocation.AI Review Report
Risks reviewed:
index > runStart); one at the final index means no trailing run to append; none at all meansrunStart === 0and the input is returned unchanged. All three are covered by the exhaustive sweep and by explicit tests.runStart === 0returnswithoutAnsidirectly rather than a rebuilt copy. This is only reachable when zero control bytes were found, so it cannot skip a strip — and note the function is already gated byterminalControlMayAffectText, so it is a second-level optimization, not a substitute for that guard.slicerespects code-unit boundaries the same way index-based access did. Surrogate pairs are never split differently than the original — both halves are above0x9fand so are never stripped. Covered by CJK and emoji fixtures.replacecalls that precede this loop are unchanged.Cross-platform: no path, shell, or platform-dependent behaviour. Pure in-memory string processing, identical on macOS/Linux/Windows, and unaffected by SSH/WSL/remote hosts — though remote panes benefit equally since the detector runs on their output too.
Security Audit
No new input handling, command execution, path handling, auth, secrets, or IPC surface. The same bytes are stripped by the same predicate; only the string-building strategy changed. This is defensive sanitization of untrusted PTY output, and its behaviour is provably unchanged (224,831-input differential), so the sanitization guarantee is preserved exactly. No dependency changes.
Made with Orca 🐋