Skip to content

perf(agent-status): strip terminal control bytes by run, not per character - #10866

Merged
nwparker merged 4 commits into
stablyai:mainfrom
nwparker:perf/strip-terminal-control
Jul 27, 2026
Merged

nwparker merged 4 commits into
stablyai:mainfrom
nwparker:perf/strip-terminal-control

Conversation

@nwparker

@nwparker nwparker commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

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 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:

Complete stripTerminalControl path. Lower is better.
iterations=501 (1002 first-touch samples/implementation, counterbalanced median)
                  fixture    per-char   slice runs   speedup
          300 history TUI      1.5 us       1.0 us     1.50x
         301 boundary TUI      1.5 us       1.0 us     1.46x
            4096 scan TUI     18.6 us      11.6 us     1.60x
       4096 scan 49.6% C0     14.7 us      18.9 us     0.78x

validated=4008 measured pairs, result checksum=2159192968
Production calls are bounded to 4096, 4096, 300, and 301 code units.

The benchmark mirrors the complete pre/post stripTerminalControl paths, 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:

  • Exhaustive over every string up to length 4 across a 13-symbol alphabet chosen to cover the branch conditions: \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.
  • Plus 200,000 random strings from the same alphabet.
  • 224,831 inputs, 0 mismatches.

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:

mutant result
drop the trailing run (return output) 86 tests fail
drop the run copy, keep only the skip 2 tests fail
  • pnpm lint
  • pnpm typecheck
  • pnpm test — 3134/3134 across src/shared/; 92/92 in the touched file
  • Added tests that would catch the regression

Pre-existing test failures

Full suite: 5 failures / 37,128. Two are agent-exec-handler.test.ts, which assert against the machine's real process.env. The others — transcript-watch ×2 and project-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 unmodified main produce 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 !hasSeenCommandCodeUi early-out, but that latches to true after 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:

  • shouldIncludeQuickOpenPath substring 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.
  • MJPEG frame parser re-concat — the concat only fires on the bounded-remainder path; frames are subarray views, pending is trimmed, and it already has its own benchmark. Prior work got there first.

AI Review Report

Risks reviewed:

  • Boundary conditions. A control byte at index 0 means the first run is empty (guarded by index > runStart); one at the final index means no trailing run to append; none at all means runStart === 0 and the input is returned unchanged. All three are covered by the exhaustive sweep and by explicit tests.
  • The no-control fast path. runStart === 0 returns withoutAnsi directly 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 by terminalControlMayAffectText, so it is a second-level optimization, not a substitute for that guard.
  • Multi-byte safety. Iteration is by UTF-16 code unit, exactly as before, and slice respects code-unit boundaries the same way index-based access did. Surrogate pairs are never split differently than the original — both halves are above 0x9f and so are never stripped. Covered by CJK and emoji fixtures.
  • ANSI stripping is untouched — the two replace calls 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 🐋

…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).
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Updated 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: optimizing terminal control stripping by copying runs instead of per-character concatenation.
Description check ✅ Passed The description covers summary, screenshots, testing evidence, AI review, and security audit; only the template's Notes section is missing.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between a1a78da and 289f640.

📒 Files selected for processing (3)
  • config/scripts/terminal-control-strip-benchmark.mjs
  • src/shared/command-code-output-status.test.ts
  • src/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]>
@nwparker

Copy link
Copy Markdown
Contributor Author

Addressed in bd80fbf. Both comments were walking through the implementation; each is now a single line of non-obvious rationale (// Why slice runs: control bytes are sparse and this runs 4x per PTY chunk. and // Run-copying breaks at run boundaries, so these pin start/end/adjacent/none.). 92 tests still green.

@nwparker
nwparker merged commit 165e4e0 into stablyai:main Jul 27, 2026
1 check passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant