Skip to content

perf(terminal): bound the reattach payload agent-signal scan - #12681

Merged
nwparker merged 1 commit into
mainfrom
perf/terminal-reattach-payload-scan-bound
Aug 6, 2026
Merged

nwparker merged 1 commit into
mainfrom
perf/terminal-reattach-payload-scan-bound

Conversation

@nwparker

@nwparker nwparker commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

hasCursorAgentReattachPayloadScreenSignal classifies the reattach payload by building a character-by-character full copy of it (normalized += data[index]), then reading the last "Cursor Agent" occurrence plus 5000 chars. The payload is capped only by the 16MB daemon frame, the work is synchronous on the renderer main thread with no yield, and it runs on all four reattach branches — including the miss case, which pays the whole copy for a result that is always false.

Measured

config/scripts/terminal-reattach-payload-scan-benchmark.mjs, deterministic SGR-heavy payloads, median of 7 rounds:

payload before after
2MB snapshot, header hit 17.5 ms 0.76 ms 23x
2MB snapshot, miss 8.7 ms 0.50 ms 17x
200KB snapshot, header hit 1.42 ms 0.63 ms 2.3x
100KB relay tail 0.30 ms 0.20 ms 1.5x

For scale, xterm's own parse of that 2MB payload is ~23 ms — so the old scan was adding ~75% on top of the parse for the same bytes.

Change

Two lines of idea, both with existing in-tree precedent:

  1. Bound the scan to a 256KB tail. Only the header nearest the end matters, and every replay puts the current screen last (scrollbackAnsi + rehydrateSequences + snapshotAnsi). This is the same shape the kitty tracker already uses for its own scan. 256KB clears even a fully SGR-styled frame by ~2x, so the cut can only drop stale scrollback — which the post-parse viewport veto would have rejected anyway.
  2. Strip with the shared precompiled CSI_SEQUENCE_PATTERN instead of the hand-rolled loop. Deletes 20 lines. It is also faster in V8: the loop builds a rope node per character, the regex copies spans.

Deliberately CSI-only, not the full stripAnsiEscapeSequences — OSC-carried titles must keep counting as a header occurrence, exactly as they did before.

No exotic optimization: no streaming stripper, no rolling-hash search over raw bytes, no worker offload. The bound makes payload size irrelevant, so the constant factor stops mattering.

Negative result, recorded

Porting the daemon mouse mirror's includes() pre-filter to TerminalKittyKeyboardModeTracker.scanReplay makes reattach slower — 2.1 ms → 3.7 ms at 2MB — because snapshots always contain \x1b[?, so the gate never fires and the three extra full scans are pure cost. It only pays on the live per-chunk path with escape-free output, worth ~2.7 µs/chunk. The benchmark keeps measuring this so the question doesn't get re-asked. scanReplay is left untouched.

Guards

The two behaviours a future "just lastIndexOf the raw bytes" shortcut would silently break are now pinned, and both were confirmed to fail without the code under test:

  • a CSI-split header (Cursor \x1b[1mAgent) must still match — this is why the strip exists
  • a header behind the tail bound must not match

Also byte-pins POST_REPLAY_REATTACH_RESET_KEEP_MOUSE, which shipped unpinned in #12461 — without it, silently collapsing that profile into the live-agent one would pass CI.

Verification

  • pnpm typecheck clean
  • 3040 tests pass across the terminal-pane and shared suites
  • benchmark asserts every variant agrees with the baseline on every payload before timing it

Follows #12461, now merged; rebased onto main.

Made with Orca 🐋

hasCursorAgentReattachPayloadScreenSignal built a char-by-char copy of the
entire reattach payload so it could read the last header plus 5000 chars. On a
2MB daemon snapshot that cost 17.5ms of synchronous renderer main-thread work —
~75% of what xterm then spends parsing the same bytes — and the miss case paid
it in full for a result that is always false.

Two changes, both matching existing in-tree precedent: bound the scan to a
256KB tail (as the kitty tracker already bounds its own scan), and strip via
the shared precompiled CSI_SEQUENCE_PATTERN instead of a hand-rolled loop,
which is also faster in V8 because it copies spans rather than building a rope
per character.

  2MB snapshot, header hit   17.5ms -> 0.80ms  (22x)
  2MB snapshot, miss          8.7ms -> 0.52ms  (17x)
  200KB snapshot, header hit  1.5ms -> 0.62ms  (2.4x)

config/scripts/terminal-reattach-payload-scan-benchmark.mjs reproduces this and
asserts every candidate agrees with the baseline before timing it. It also
records a negative result: porting the daemon mouse mirror's includes()
pre-filter to the kitty tracker makes reattach slower, because snapshots always
contain the introducer.

Adds guards for the two behaviours a future shortcut would silently break: a
CSI-split header must still match, and a header behind the tail bound must not.
Also byte-pins POST_REPLAY_REATTACH_RESET_KEEP_MOUSE, which shipped unpinned.

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker changed the base branch from fix/terminal-reattach-mouse-mode-rearm to main August 6, 2026 07:11
@nwparker
nwparker force-pushed the perf/terminal-reattach-payload-scan-bound branch from 333d977 to 85e4b10 Compare August 6, 2026 07:11
@nwparker
nwparker requested a review from brennanb2025 as a code owner August 6, 2026 07:11
@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PTY replay path now limits Cursor Agent screen detection to the final 256 KiB and uses shared CSI stripping. Regression tests cover styled headers, bounded-tail misses, and reset-profile sequences. A deterministic benchmark compares scan implementations, Kitty replay scanning, escape gating, and xterm headless parsing.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed and relevant but omits Screenshots, AI Review Report, Security Audit, Notes, and several required testing checklist items. Add all missing template sections, state “No visual change,” complete the testing checklist, and document cross-platform review and security findings.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 and concisely describes the main performance change: bounding the terminal reattach payload agent-signal scan.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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: bab5e7f0-3ff0-47f2-9995-31103ac878c2

📥 Commits

Reviewing files that changed from the base of the PR and between 39ba201 and 85e4b10.

📒 Files selected for processing (4)
  • config/scripts/terminal-reattach-payload-scan-benchmark.mjs
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/shared/terminal-mode-reset-profiles.test.ts

Comment on lines +218 to +223
const kittyGated = (data) => {
if (!data.includes('\x1b[?') && !data.includes('\x1bc') && !data.includes('\x9b')) {
return 0
}
return kittyScan(data)
}

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Make the Kitty gate behavior-equivalent before timing it.

kittyGated('\x1b[>1u') returns 0, but TerminalKittyKeyboardModeTracker.scanReplay parses that Kitty enable sequence and returns flags. The benchmark can report a faster result by skipping valid Kitty protocol input. Add protocol fixtures and assert equal results before measuring.

Proposed fix
 const kittyGated = (data) => {
-  if (!data.includes('\x1b[?') && !data.includes('\x1bc') && !data.includes('\x9b')) {
+  if (!data.includes('\x1b') && !data.includes('\x9b')) {
     return 0
   }
   return kittyScan(data)
 }

@nwparker
nwparker merged commit a7ffb24 into main Aug 6, 2026
67 of 109 checks passed
@nwparker
nwparker deleted the perf/terminal-reattach-payload-scan-bound branch August 6, 2026 07:24
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…i#12681)

hasCursorAgentReattachPayloadScreenSignal built a char-by-char copy of the
entire reattach payload so it could read the last header plus 5000 chars. On a
2MB daemon snapshot that cost 17.5ms of synchronous renderer main-thread work —
~75% of what xterm then spends parsing the same bytes — and the miss case paid
it in full for a result that is always false.

Two changes, both matching existing in-tree precedent: bound the scan to a
256KB tail (as the kitty tracker already bounds its own scan), and strip via
the shared precompiled CSI_SEQUENCE_PATTERN instead of a hand-rolled loop,
which is also faster in V8 because it copies spans rather than building a rope
per character.

  2MB snapshot, header hit   17.5ms -> 0.80ms  (22x)
  2MB snapshot, miss          8.7ms -> 0.52ms  (17x)
  200KB snapshot, header hit  1.5ms -> 0.62ms  (2.4x)

config/scripts/terminal-reattach-payload-scan-benchmark.mjs reproduces this and
asserts every candidate agrees with the baseline before timing it. It also
records a negative result: porting the daemon mouse mirror's includes()
pre-filter to the kitty tracker makes reattach slower, because snapshots always
contain the introducer.

Adds guards for the two behaviours a future shortcut would silently break: a
CSI-split header must still match, and a header behind the tail bound must not.
Also byte-pins POST_REPLAY_REATTACH_RESET_KEEP_MOUSE, which shipped unpinned.

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