Skip to content

fix: eliminate quadratic whitespace trimming during fullscreen scrolling - #19214

Merged
nwparker merged 1 commit into
mainfrom
nwparker/slow-scroll
Sep 7, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/slow-scroll

Conversation

@nwparker

@nwparker nwparker commented Sep 7, 2026 •

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

ELI5

Scrolling Pi in fullscreen could leave Orca catching up for seconds. This removes expensive whitespace cleanup that blocked terminal output, making scrolling more responsive.

What Changed

Replace two trailing-whitespace regex calls with the existing linear trimTerminalLineRight implementation. Add regression coverage for retained-row and carried-prefix redraws plus the experimental terminal-performance.padded-fullscreen-redraw reliability gate.

Why

Long internal runs of spaces caused quadratic regex backtracking. A main-process CPU profile attributed 3.087 seconds to redraw-row trimming during one wheel gesture. The existing trim preserves internal whitespace and removes only trailing spaces/tabs; terminal contents, retention, cursors, and pagination semantics stay intact.

Linked Issue

Fixes #14770

Visual Proof

Before and after captures of the Pi fullscreen reproduction (same dimensions). These show the rendered scenario; static screenshots cannot demonstrate latency. The baseline includes a historical failed model request from the saved session.

Before After
Before After

Pi 0.84.2, macOS, isolated folder workspace, saved ~1,200-line transcript, 60 requested CDP wheel events:

Measurement Before After
Wheel dispatch completion 1,116 ms 523 ms
Final output parsed after dispatch 2,127 ms 14 ms

An alternating-direction stream finished output 5.5 ms after dispatch. CDP coalescing and existing wheel acceleration produce different report counts, so these measure output backlog, not fixed-report throughput. The user also compared the fixed dev app with production and confirmed improved responsiveness.

Testing

  • I manually tested these changes locally

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

  • Regression and tail-equivalence suites: 17 passed. Both new padded-redraw budget cases failed before the fix (~1.7 seconds each) and pass afterward; four redraws with 32,000 internal spaces must complete within 500 ms while preserving content.

  • Full runtime suite: 1,257 passed, 1 skipped.

  • Node typecheck, changed-code quality checks, reliability manifest validation, and diff whitespace checks passed.

  • Rendered validation and user comparison on macOS. Linux, Windows, live SSH rendering, and Terminal.app comparison were not exercised. Full lint/build and remaining platform checks are left to CI.

Run the focused regression checks:

ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/terminal-tail-whitespace.test.ts src/main/runtime/terminal-tail-buffer.test.ts src/main/runtime/retained-tail-redraw-window.equivalence.test.ts

To compare manually, open the same long Pi transcript in fullscreen on this branch and production, hide the fullscreen scrollbar, and scroll repeatedly in both directions. Check that output catches up promptly and typing remains responsive.

Review

The change reuses existing trimming logic and adds no timers, caches, output dropping, execution-host behavior, or wire changes.

Agent skill upstream boundary

  • Not applicable; no agent skill code or content changed.

Notes

Platform-independent string handling applies to all providers. Folder workspaces were exercised. No path, shortcut, mobile, security, or remote protocol changes.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • 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)

@coderabbitai

coderabbitai Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: f54a9a65-56bd-4c24-afb6-dd5eb96a1fe6

📥 Commits

Reviewing files that changed from the base of the PR and between c300913 and 773947d.

📒 Files selected for processing (4)
  • config/reliability-gates.jsonc
  • src/main/runtime/terminal-tail-buffer.ts
  • src/main/runtime/terminal-tail-redraw-buffer.ts
  • src/main/runtime/terminal-tail-whitespace.test.ts

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


📝 Walkthrough

Walkthrough

The change replaces inline trailing-space and tab regular expressions with trimTerminalLineRight in two terminal redraw paths. New Vitest coverage checks spaces, tabs, non-breaking spaces, newline preservation, multi-row padded redraw output, and execution time. A new experimental reliability gate records the redraw invariant, oracle, test coverage, performance evidence, budgets, known gaps, and promotion criteria.

Merge Risk: ⚪ Minimal · up to 77394

The terminal redraw paths now use linear trailing whitespace trimming while preserving existing space-and-tab behavior, with coverage for retained rows, prefix rewrites, and padded redraw performance. No concrete merge-blocking risk remains.

🚥 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%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 3 files. (1 skipped: 1 … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary change: removing quadratic whitespace trimming during fullscreen terminal scrolling.
Description check ✅ Passed The description is complete and follows the repository template. It explains the change, rationale, linked issue, validation results, limitations, and checklist status.
Linked Issues check ✅ Passed The changes address issue #14770 by removing the redraw bottleneck that caused slow fullscreen scrolling. Regression tests and performance measurements verify preserved terminal behavior and improved …
Out of Scope Changes check ✅ Passed All changes are related to the linked issue: they replace two trimming operations, add focused regression coverage, and document the associated reliability gate. No unrelated product or protocol chang…
Full details: Docstring Coverage

Explanation

Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 3 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 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.

@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

  • Quadratic trim replaced with linear helper — the two /[ \t]+$/g trailing-whitespace calls in terminal-tail-buffer.ts and terminal-tail-redraw-buffer.ts now delegate to the existing trimTerminalLineRight, eliminating the quadratic backtracking on padded fullscreen redraws.
  • Regression coverage — a new terminal-tail-whitespace.test.ts pins exact content preservation for trimTerminalLineRight plus a < 500ms budget across both the retained-row (unwindowed) and carried-prefix (windowed) redraw paths.
  • Reliability gate — an experimental/partial gate documents the invariant, oracle, and red/green evidence; the manifest validates cleanly (109 gates).

The substitution is behaviorally equivalent: trimTerminalLineRight trims only trailing spaces/tabs, and the one regex divergence ($ matching before a trailing line terminator) is unreachable because retained row/line texts never end in \n/\r. The perf budget genuinely fails on the old code — a single /[ \t]+$/g replace on the 32,000-space padded line takes ~857ms vs ~0ms linear — so the test is a real regression guard, not theatre. Focused gate suite (17 tests) and the manifest check both pass.

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

@nwparker
nwparker merged commit 2ccf35b into main Sep 7, 2026
29 checks passed
fabolivark added a commit to ab2webco/orca-oss that referenced this pull request Sep 9, 2026
…s, and two hot-path walks (#371)

* fix(terminal): keep restored OSC-8 ranges across a no-op resize (#17759)

Cold restore seeded a checkpoint's OSC-8 link ranges and then replayed records
that resize, so any resize record after the checkpoint dropped them and
restored hyperlinks in scrollback lost clickability. Same-size resize records
reach the durable log routinely, because every attach re-asserts the pane's
dimensions and session-output-plane records each one without a same-size
dedupe — so an ordinary reattach was enough to lose the links.

Restored ranges are row-indexed, so clearing them on a reflow is right; a
resize to the size already applied is not a reflow. Gate on the dimensions
actually changing.

Introduced in d46349c ("fix: improve mobile link modifier handling",
#5597), which added setRestoredOscLinks along with unconditional clearing in
both resize() and clearScrollback(). clearScrollback's clearing is correct and
is unchanged, with a test pinning it.

Found during adversarial review of #17752 and filed as #17756. Not a
regression from that PR: #17667 had incidentally masked it by gating no-op
resizes to protect a snapshot cache, and removing the cache removed the gate.
The same gate returns here on its own terms — as a correctness fix with tests,
rather than as a side effect of a cache.

(cherry picked from commit ae35e04)

* fix(mobile): stop double-scaling commit timestamps in history rows (#17731)

Co-authored-by: Claude <[email protected]>
Co-authored-by: Jinwoo-H <[email protected]>
(cherry picked from commit c300913)

* perf(terminal): usar el trim que ya camina, no la regex cuadratica (upstream #19214)

Port de la idea de stablyai/orca#19214. Dos call sites del redraw seguian con
`line.replace(/[ \t]+$/g, '')`: el `+` anclado hace que el motor retroceda sobre
la corrida de padding por cada posicion de inicio que prueba, o sea tiempo
cuadratico en una fila que un TUI rellena hasta el ancho de la ventana. Y un
redraw a pantalla completa trimea CADA fila retenida en cada frame.

No hace falta traer nada: nuestro `trimTerminalLineRight` (orca-runtime.ts:39163)
ya camina la cadena y es identico al de upstream, solo que esos dos sitios nunca
lo usaron. El diff son dos lineas.

El test de upstream no se trae: importa `terminal-tail-buffer` y
`terminal-tail-line-controls`, dos modulos que extrajo despues de nuestra
divergencia, y nuestro helper es privado del monolito. Sin cambio de
comportamiento —las dos implementaciones son equivalentes, leidas lado a lado— y
los 4554 tests de `src/main/runtime` que cubren ese camino siguen verdes. La
medicion de la mejora es de upstream, no mia.

* perf(terminal): saltar a cada ESC en vez de caminar cada chunk (upstream #19400)

Port de stablyai/orca#19400 a nuestro monolito.
`containsTerminalVerticalLineControl` corre una vez por chunk de PTY, en el main
thread, para CADA terminal —visible, oculta o aparcada— y caminaba la cadena
posicion por posicion. Solo un ESC puede introducir un control vertical, asi que
para salida ordinaria (logs de build, `cat`, texto por pipe) el walk entero es
trabajo tirado.

Nuestra version era incluso mas lenta que la de upstream ANTES de su fix: leia
`value[index]`, que crea un string de un caracter por posicion. Ahora salta con
`indexOf` de ESC en ESC, conservando el skip de `parsed.endIndex` en el cuerpo.

4554 tests de `src/main/runtime` en verde, sin cambio de comportamiento.

---------

Co-authored-by: Neil <[email protected]>
Co-authored-by: blade035 <[email protected]>
Co-authored-by: Claude <[email protected]>
Co-authored-by: Jinwoo-H <[email protected]>
@pullfrog pullfrog Bot mentioned this pull request Sep 10, 2026
8 of 9 tasks
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.

[Bug]: Pi fullscreen TUI scroll is slow-motion in Orca, fine in Terminal.app

1 participant