Skip to content

perf(terminal): skip background SGR scans without ESC - #21646

Merged
nwparker merged 3 commits into
mainfrom
nwparker/perf-render-refresh-scan-09-19
Sep 19, 2026
Merged

nwparker merged 3 commits into
mainfrom
nwparker/perf-render-refresh-scan-09-19

Conversation

@nwparker

@nwparker nwparker commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​75 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​75
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1

ELI5

The renderer checks terminal output for colored backgrounds so it can repaint a few tricky cases. Before this change, that check opened a full regex rulebook even when the text had no escape marker at all. It now looks for the marker first; if there is none, it skips that one check and continues with the normal Unicode safety check.

What Changed

containsBackgroundSgr() now returns early when the chunk does not contain an ESC + [ introducer. Escape-bearing chunks still use the same global SGR regex and parameter handling. The existing renderer-risk and Unicode checks are unchanged.

For users, non-ASCII terminal output spends less renderer CPU on an irrelevant SGR scan. Background colors and dense SGR output keep the same refresh decisions.

The production caller now delegates directly to this classifier instead of scanning for non-ASCII text and then scanning the same chunk again. The classifier owns the exact same predicate, so ASCII still returns false while non-ASCII output avoids the duplicate JavaScript walk.

Why

A warmed Node 24 benchmark on macOS compared the exact origin/main implementation with this guard over 100,000 calls:

Input Before After Change
CJK, 4 KiB 804 ms 780 ms 3% faster
Arabic, 4 KiB 1,067 ms 999 ms 6% faster
Background SGR 12.1 ms 12.9 ms unchanged within run variance

An isolated 4 KiB containsBackgroundSgr benchmark showed the avoided no-match regex work more clearly: plain ASCII 426.5 ms → 90.3 ms, CJK 213.0 ms → 90.1 ms, and Arabic 2,285.8 ms → 159.1 ms over 1,000,000 calls; ANSI/background input remained on the existing regex path.

The early check is the smallest safe boundary: the SGR regex still receives every chunk that could contain its ESC[ introducer, and no cross-chunk state is changed. Removing the caller pre-gate is behavior-equivalent: 50,000 deterministic generated inputs produced identical old-gate and direct-classifier results. A warmed 200,000-call comparison of the caller path measured 4 KiB input at ASCII 3,456 → 3,166 ms, CJK 1,801 → 1,195 ms, Arabic 2,322 → 1,998 ms, and emoji 67.8 → 36.1 ms.

Linked Issue

Fixes #21645

Visual Proof

N/A — this changes a shared classifier’s CPU path and does not change layout or visual output.

Testing

  • Automated tests added/updated, or explained why not below

  • I manually tested these changes locally

  • pnpm test src/renderer/src/lib/pane-manager/terminal-complex-script.test.ts and the new foreground-renderer-risk-scan-tail.test.ts — 38 tests passed.

  • Added coverage for the carried cross-chunk scan tail, which had none: a background SGR split across PTY chunks is classified from the spliced string, so a pre-gate moved back above the concatenation would silently drop the refresh. Also pins that the shared global SGR regex stays stateless across calls. Both were confirmed to fail when the behaviour they pin is broken.

  • pnpm tc passed.

  • pnpm run check:code-quality:changed passed.

  • A deterministic equivalence check matched the old caller gate and direct classifier on 50,000 generated escape, Unicode, and control-byte inputs.

  • Oxlint, Oxfmt, and git diff --check passed.

  • Existing tests cover background SGR detection, foreground-only SGR, ordinary Unicode output, and renderer-risk classifications.

Review

  • Invariant: every chunk containing ESC[ reaches the existing background-SGR regex and produces the same refresh decision; chunks without it skip only a check that cannot match. The caller’s removed pre-gate and the classifier return the same boolean.
  • Failure source: a no-match global regex adds renderer work before the Unicode risk scan on non-ASCII output.
  • Oracle: the 31-case terminal-complex-script suite, including background SGR and no-refresh controls, passed unchanged.
  • Reliability gate: no existing gate directly covers this classifier. Accepted gap: shared renderer-unit tests prove classification behavior on macOS; live Electron latency and Linux/Windows/WSL/SSH process runs remain CI/follow-up coverage.
  • Diagnostics: future behavior regressions are visible in the focused classifier suite; performance regressions are reproducible with the before/after benchmark inputs above.
  • Provider/platform coverage: local, daemon, SSH, remote-runtime, WSL, and mobile transport behavior is unaffected. This is provider-independent renderer string parsing; no wire format, process, filesystem, or lifecycle code changed. macOS was the validation host.
  • Performance budget: no timers, polling, retries, subprocesses, retained output, or provider calls were added.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

The guard does not change support for C1 CSI or split sequences because this classifier’s existing pattern only matches the ESC + [ form and carries no SGR tail state.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

Full pnpm lint, the complete test suite, and packaging are left to CI; the focused gates above passed locally.

@coderabbitai

coderabbitai Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: d18d552a-ed72-43db-905e-c704a9eb2432

📥 Commits

Reviewing files that changed from the base of the PR and between 534a248 and f0de5d9.

📒 Files selected for processing (2)
  • src/renderer/src/components/terminal-pane/pty-connection/foreground-renderer-risk-scan-tail.test.ts
  • src/renderer/src/lib/pane-manager/terminal-complex-script.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

containsBackgroundSgr now checks for the \x1b[ CSI introducer before running the background-SGR regular expression. It returns false when the introducer is absent. foregroundRendererRiskOutputPrefersRenderRefresh now delegates directly to terminalOutputPrefersRenderRefresh. Tests cover split scan tails, escape-free input, completed sequences, empty chunks, and successive SGR scans.

Priority: ⬇️ Low

Severity of issue fixed: Low

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The pull request satisfies issue #21645. containsBackgroundSgr() returns before SGR_SEQUENCE_PATTERN runs when data lacks \\x1b[. terminalOutputPrefersRenderRefresh() still owns the ASCII/non-A…
Out of Scope Changes check ✅ Passed The changes stay within issue #21645. The caller delegation removes the duplicate predicate required by the issue. The classifier tests and foreground scan-tail tests verify the required performance p…
Title check ✅ Passed The title clearly identifies the main performance change: skipping background SGR scans when terminal output lacks an ESC sequence.
Description check ✅ Passed The description is complete and closely follows the repository template. It explains the change, motivation, linked issue, visual impact, testing, review considerations, platform impact, and checklist…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Skip background SGR scan without an ESC introducer — containsBackgroundSgr() in src/renderer/src/lib/pane-manager/terminal-complex-script.ts now returns false when the chunk lacks the literal \x1b[ before running the global SGR regex.

The guard is a strict necessary condition: every match of SGR_SEQUENCE_PATTERN (ESC \[ ([0-9:;]*) m) contains \x1b[, so classification is unchanged. It is per-chunk with no cross-chunk SGR tail state, and the pattern intentionally only handles the ESC form (never C1 CSI \x9b), which matches the learnings note that a pre-filter is safe only when every regex alternative starts with the matched introducer.

The only production caller (fresh-spawn-follow-reset.ts:94) already gates on scanData.includes('\x1b[') || containsNonAsciiOutput(scanData), so the saved work is the no-match regex scan on non-ASCII, no-ESC chunks — the PR body states this accurately. The existing suite covers both branches (ESC/no-background and no-ESC/non-ASCII), and per the repo's scanner learnings a pre-filter test cannot fail here, so the absence of a new test is not a coverage gap.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes (since prior review of f1474af)

  • Remove the duplicate caller pre-gate — fresh-spawn-follow-reset.ts now calls terminalOutputPrefersRenderRefresh(scanData) directly instead of (scanData.includes('\x1b[') || session.containsNonAsciiOutput(scanData)) && terminalOutputPrefersRenderRefresh(scanData).

The removal is behavior-equivalent. hasESC || hasNonAscii was already a necessary condition for the classifier to return true: the background-SGR branch requires the \x1b[ introducer, and the Unicode branch requires non-ASCII. When both are false, the classifier's own guard returns false. The prior commit's guard in containsBackgroundSgr plus the existing non-ASCII fast path reproduce the exact predicate, so the caller no longer pays a second JavaScript walk over the same chunk. No side effects were dropped — containsNonAsciiOutput is pure.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

The foreground renderer-risk scan splices the carried tail onto the
incoming chunk before classifying it, and nothing covered that ordering:
a pre-gate moved back above the concatenation would silently drop the
refresh for a background SGR split across ConPTY chunks.

Also pins the escape-free ASCII path and the shared global SGR pattern's
statelessness across calls, since the background hit returns mid-loop.
@nwparker
nwparker force-pushed the nwparker/perf-render-refresh-scan-09-19 branch from 534a248 to f0de5d9 Compare September 19, 2026 22:04

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes (since prior pullfrog review of 534a248)

  • Pin the carried renderer-risk scan tail — added foreground-renderer-risk-scan-tail.test.ts, which drives session.foregroundRendererRiskOutputPrefersRenderRefresh through a background SGR split across ConPTY chunks ('\x1b[4' then '1m x') and asserts the spliced tail is consumed and cleared.
  • Cover the escape-free ASCII path and global-pattern statelessness — two tests added to terminal-complex-script.test.ts. The statelessness case is a real oracle: I confirmed the shared SGR_SEQUENCE_PATTERN.lastIndex reset is what makes the second background hit return true.
  • Ran both touched suites: 38 tests pass.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit abd310e into main Sep 19, 2026
36 checks passed
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.

perf(terminal): skip background SGR regex without ESC sequences

1 participant