Skip to content

Preserve terminal scrollbar position after tab switches - #7472

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/sta-1341-codex-terminal-scroll
Jul 6, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/sta-1341-codex-terminal-scroll

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Preserves terminal scroll position after the user drags xterm's scrollbar thumb or track, then switches tabs or returns from visibility/layout resume. This fixes STA-1341's stale-scroll-intent shape: a dragged viewport could snap back to an older pinned line.

This does not change wheel/trackpad scrolling, Codex/TUI mouse-reporting behavior, hidden-output replay, output scheduling, or terminal styling.

Design Approach

  • Treat pointerdown targets on .xterm-scrollbar and .xterm-slider as user scroll-intent sources, alongside the existing .xterm-viewport path.
  • Reuse the existing scroll/pointerup synchronization path so xterm remains the source for the settled viewportY.
  • Add focused regression coverage for scrollbar/slider pointer intent and stale-top restore.
  • Register terminal-scroll.intent-preservation as an experimental/partial reliability gate.

Design review completed clean after tightening the reliability gate, provider/platform gap language, and Electron validation selector.

Implementation

  • terminal-scroll-intent.ts now classifies xterm viewport, scrollbar, and slider pointer targets as scroll-intent targets.
  • terminal-scroll-intent.test.ts covers scrollbar/slider pointer-driven scroll intent and proves a dragged viewport restores instead of stale top intent.
  • config/reliability-gates.jsonc adds the experimental/partial terminal-scroll.intent-preservation gate.
  • SourceControlActionRepoOverrideNote.tsx removes an unnecessary exhaustive-switch default that blocked repo-wide lint.

No implementation deviations from the reviewed design, except the small unrelated lint cleanup required to get pnpm run lint passing.

Completeness

Headline behavior: implemented.

Independent completeness verification found no blockers. The stale-top regression test would fail under the old .xterm-viewport-only classifier because .xterm-slider pointerdown would not refresh stored intent.

Broad app consistency: the source-of-truth behavior is terminal scroll intent architecture: user-driven scroll position is authoritative, and tab/workspace visibility changes should not become scroll operations. Desktop terminal panes share the renderer/xterm path; mobile/relay is unaffected by desktop xterm DOM scrollbar pointer events. No header/footer/overflow/command-palette/review/settings actions changed.

Reliability

Reliability invariant: a user-driven xterm scrollbar thumb or track scroll updates live terminal scroll intent before tab, visibility, or layout resume enforces intent.

Gate: terminal-scroll.intent-preservation, experimental/partial.

Correctness evidence:

  • Unit oracle records .xterm-scrollbar / .xterm-slider pointer intent and restores the dragged line instead of stale top intent.
  • Electron oracle reproduced the product flow with real mouse input.

Provider/platform coverage:

  • Covered live: local macOS Electron; SSH to a throwaway Linux Docker target with a real relay-backed remote PTY; Windows desktop Electron; Windows WSL2-backed terminal.
  • Covered by shared renderer-path reasoning/unit gate: daemon, remote-runtime.
  • Live-unproved gaps: daemon, remote-runtime, Linux desktop host.
  • Mobile/relay: unaffected by this desktop xterm DOM change.

Performance

Perf audit clean. The runtime change is bounded to three classList.contains / closest checks on existing pointerdown handling. No polling, timers, output parsing, IPC, PTY listing, provider scans, resize churn, startup awaits, hidden-pane wake loops, or listener fanout were added.

Review

  • Design review: clean after fixes.
  • Completeness verification: complete, no blockers.
  • Perf audit: clean.
  • Code-review loop: final four-file diff reviewed by two fresh reviewers in the same round; both returned clean.
  • Merge-confidence validation: should land.
  • Post-PR stabilization: CodeRabbit quick-win comment addressed; refreshed CodeRabbit sweep reported no actionable comments; PR checks passed.

Validation

  • pnpm run lint passed, with existing warnings only.
  • pnpm run typecheck passed.
  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/pane-manager/terminal-scroll-intent.test.ts passed, 17 tests.
  • pnpm run check:reliability-gates passed, 28 gates.
  • git diff --check passed.
  • Live Electron validation in this worktree:
    • real xterm scrollbar track moved top: 0px -> 467px;
    • after switching Terminal 2 -> Terminal 3 -> Terminal 2, it stayed at top: 467px.
  • Live SSH/Linux validation in this worktree:
    • relay target: throwaway node:22-bookworm Docker container, remotePlatform: linux;
    • real SSH PTY id: ssh:ssh-1783310567594-y6qz85@@pty-1;
    • xterm scrollback baseY: 652;
    • scrollbar drag moved viewportY 0 -> 387 and slider top: 40px -> 489px;
    • after switching away and back, viewportY stayed 387 and slider top stayed 489px.
  • Live Windows validation from Neil's Windows agent report:
    • environment: Windows 11 Pro 10.0.26100, Node v24.16.0, pnpm 10.24.0, Orca 1.4.123-rc.1 (Electron 42.3.3, Chrome 148);
    • CDP identity confirmed branch brennanb2025/sta-1341-codex-terminal-scroll at C:\Users\neil\orca\workspaces\orca\7472;
    • static checks passed, including typecheck, oxlint on tracked source, switch exhaustiveness, styled scrollbars, reliability gates, localization checks, and focused Vitest 17/17;
    • real Playwright mouse drag on .xterm-scrollable-element > .xterm-scrollbar.xterm-vertical > .xterm-slider;
    • scrollbar drag moved viewportY 0 -> 296, baseY: 651, and slider top: 40px -> 390px;
    • after switching to Terminal 2 and back, viewportY stayed 296 and slider top stayed 390px.
  • Live WSL2 validation from PR comment:
    • environment: Windows 11 Pro 10.0.26100, WSL 2.7.8.0, kernel 6.18.33.1-microsoft-standard-WSL2, Ubuntu 24.04.4 LTS, Orca 1.4.123-rc.1;
    • confirmed genuinely WSL-backed via terminal uname=Linux, OS process table showing both PTYs as wsl.exe children of electron.exe, and workspace path \\wsl.localhost\Ubuntu-24.04\root\orca-wsl-sta1341;
    • real Playwright mouse drag on .xterm-scrollable-element > .xterm-scrollbar.xterm-vertical > .xterm-slider;
    • scrollbar drag moved viewportY 0 -> 296, baseY: 653, and slider top: 40px -> 390px;
    • after switching to Terminal 2 and back, viewportY stayed 296 and slider top stayed 390px.
  • Earlier Electron screenshot evidence: .tmp/validation-evidence/sta-1341-terminal-scrollbar-after-tab-switch.png, with viewportY 0 -> 431 -> 431 after tab switch.
  • PR checks after the follow-up push:
    • verify passed.
    • golden e2e linux experiment passed.
    • golden e2e mac experiment passed.

Screenshots

  • Manual Electron evidence screenshot: .tmp/validation-evidence/sta-1341-terminal-scrollbar-after-tab-switch.png.
  • The screenshot shows Terminal 2 preserved around lines 430-480 after the tab switch.
  • SSH/Linux remote PTY evidence screenshot: .tmp/validation-evidence/sta-1341-ssh-linux-lite-terminal-scrollbar-after-tab-switch.png.
  • Windows evidence screenshot from Neil's agent report: C:\Users\neil\AppData\Local\Temp\orca-sta1341-evidence\terminal1-after-return.png, showing Terminal 1 preserved around STA1341_WIN_LINE_0294 through _0345 after switching away and back.
  • WSL2 evidence from PR comment: after-return screenshot showed Terminal 1 preserved around STA1341_WSL_LINE_0292 through _0343, matching viewportY=296.

Testing Checklist

  • Focused unit regression test for terminal scrollbar/slider scroll intent.
  • Full lint.
  • Typecheck.
  • Reliability gate manifest check.
  • Live Electron local macOS validation.
  • Live SSH/Linux remote PTY validation.
  • Live Windows desktop Electron validation.
  • Live Windows WSL2 terminal validation.
  • PR CI checks.

AI Review Report

  • Design review completed clean after edits.
  • Perf audit completed clean.
  • Code-review loop completed clean with two reviewers in the same round.
  • CodeRabbit quick-win comment was addressed; refreshed sweep reported no actionable comments.

Security Audit

No security-sensitive behavior changes. This PR changes renderer-side xterm DOM event classification, renderer-unit tests, a reliability manifest entry, and an exhaustive-switch lint cleanup. It adds no network calls, filesystem access, shell/process execution, authentication, permission, or provider-identity behavior.

Notes

The first Linux golden experiment failed once in an unrelated terminal-rendering golden test with Execution context was destroyed during setup; the refreshed run after the follow-up push passed.

SSH/Linux validation used a minimal synthetic remote workspace state after establishing a real Orca SSH target and relay-backed PTY. The earlier full repos:addRemote harness caused unrelated remote repo watcher/mux churn before reaching the scrollbar assertion; the passing lite harness still exercised the real renderer, xterm, tab switch, SSH target, Linux relay, and remote PTY path for this scroll behavior.

Risks And Gaps

  • Live daemon, remote-runtime, and Linux desktop host validation were not run.
  • Future xterm scrollbar DOM class changes could require updating the target classifier and tests.
  • Keyboard scroll intent is a documented non-goal for this fix.
  • CodeRabbit's description-template warning is non-actionable for this repository PR body; no code-review comments remain actionable after the follow-up push.

@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This change extends terminal scroll-intent detection to treat xterm scrollbar and slider interactions like viewport pointer activity, adds tests for intent switching and viewport restoration, and records the behavior in a new reliability gate. It also removes an unrelated exhaustive-switch default branch from a settings component.

Changes

  • Terminal scroll intent now recognizes .xterm-scrollbar and .xterm-slider targets.
  • Tests cover pointer-driven intent changes and restored viewport position.
  • A new reliability gate documents evidence, coverage, and promotion criteria.
  • One switch statement no longer includes a never exhaustiveness branch.

Related issues: None found.

Related PRs: None found.

Suggested labels: renderer, terminal, tests, config

Suggested reviewers: None identified from provided data.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 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 summarizes the main user-visible change: preserving terminal scrollbar position after tab switches.
Description check ✅ Passed The description includes all required template sections and provides concrete summary, screenshots, testing, review, security, and notes.
✨ Finishing Touches
📝 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.

🧹 Nitpick comments (1)
src/renderer/src/lib/pane-manager/terminal-scroll-intent.ts (1)

128-136: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Redundant classList.contains check — closest() already matches the element itself.

Element.closest() includes the element itself in its ancestor search, so target.classList.contains(className) is dead logic. Also, iterating and calling closest() once per class does up to three separate ancestor walks per pointerdown; a single combined selector does it in one pass.

♻️ Proposed simplification
 function isTerminalScrollIntentPointerTarget(target: EventTarget | null): target is Element {
   if (typeof Element === 'undefined' || !(target instanceof Element)) {
     return false
   }
   // xterm's custom scrollbar uses separate thumb/track nodes from the viewport.
-  return XTERM_SCROLL_INTENT_POINTER_TARGET_CLASSES.some(
-    (className) => target.classList.contains(className) || target.closest(`.${className}`) !== null
-  )
+  const selector = XTERM_SCROLL_INTENT_POINTER_TARGET_CLASSES.map((className) => `.${className}`).join(',')
+  return target.closest(selector) !== null
 }

Note: this requires the test file's TestElement.closest() polyfill to support comma-separated selectors (it currently only handles a single .class selector), so update that fixture alongside this change if adopted.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: c440f7ea-beb4-4890-b402-6e3e3abffff2

📥 Commits

Reviewing files that changed from the base of the PR and between 0fa8589 and 285517a.

📒 Files selected for processing (4)
  • config/reliability-gates.jsonc
  • src/renderer/src/components/settings/SourceControlActionRepoOverrideNote.tsx
  • src/renderer/src/lib/pane-manager/terminal-scroll-intent.test.ts
  • src/renderer/src/lib/pane-manager/terminal-scroll-intent.ts
💤 Files with no reviewable changes (1)
  • src/renderer/src/components/settings/SourceControlActionRepoOverrideNote.tsx

@brennanb2025

Copy link
Copy Markdown
Contributor Author

✅ WSL validation (Windows + WSL2) — PASS

Verified on Windows that the scrollbar-drag position is preserved across terminal-tab switches when the terminal is genuinely WSL-backed (PTY = wsl.exe, a real Linux login shell — not PowerShell).

Truly WSL-backed — confirmed three independent ways

  1. PTY output: the terminal printed uname=Linux 6.18.33.1-microsoft-standard-WSL2 distro=Ubuntu-24.04 user=root.
  2. OS process table: both tabs' PTYs are wsl.exe processes parented to electron.exe, launched with Orca's real WSL args:
    wsl.exe -d Ubuntu-24.04 -- sh -c "cd '/root/orca-wsl-sta1341' && … exec "$_orca_wsl_shell" -l" (two such processes → both tabs are Linux shells).
  3. Workspace identity: worktree is the WSL UNC path itself — \\wsl.localhost\Ubuntu-24.04\root\orca-wsl-sta1341; tab prompt renders root@win:~/orca-wsl-sta1341.

Backing mechanism: opened a workspace whose folder is a WSL UNC path, so Orca's parseWslPath detection flips the shell executable to wsl.exe -d <distro> (first-class WSL support in src/main/wsl.ts / windows-shell-args.ts). No internal overrides or hacks; both of the 2 tabs were Linux login shells.

Environment

Windows 11 Pro 10.0.26100 · WSL 2.7.8.0 (kernel 6.18.33.1-microsoft-standard-WSL2) · Ubuntu-24.04 (24.04.4 LTS) · Orca 1.4.123-rc.1 (Electron 42.3.3, Chrome 148) · Node v24.16.0 / pnpm 10.24.0 · fresh dev profile.

Repro

WSL-backed workspace + 2 WSL terminal tabs. Terminal 1 seeded with 700 lines via a bash loop (for i in $(seq 0 699); do printf 'STA1341_WSL_LINE_%04d\n' "$i"; done → baseY=653), scrolled to top. Drag was a real Playwright mouse drag (mouse.move/down/move×20/up) of the live custom scrollbar slider (.xterm-scrollable-element > .xterm-scrollbar.xterm-vertical > .xterm-slider), not an API scroll. Then: switch to Terminal 2 → wait → switch back to Terminal 1.

Stage viewportY baseY slider top (px)
Before drag 0 653 40 (track top)
After drag (dragged ~350px down) 296 653 390
After return (Terminal 2 visible while away, then back) 296 653 390
  • afterDrag.viewportY = 296 > 0 ✅
  • afterReturn.viewportY (296) == afterDrag.viewportY (296) — exact, within ±5 lines ✅
  • slider top held at 390, not reset to top ✅

Screenshot after returning shows Terminal 1 still at mid-scrollback (STA1341_WSL_LINE_0292 → _0343, matching viewportY=296) — no snap-back to the stale top. (Evidence captured locally; not committed.)

Static checks (branch, unchanged)

typecheck clean · oxlint clean on tracked source · 28 reliability gates pass · focused terminal-scroll-intent.test.ts 17/17.


This complements an earlier native-Windows-terminal pass with identical results (before viewportY=0 → after-drag 296 → after-return 296). Validated on brennanb2025/sta-1341-codex-terminal-scroll @ 66d856e28.

@brennanb2025
brennanb2025 merged commit 28fe4df into main Jul 6, 2026
3 checks passed
@brennanb2025
brennanb2025 deleted the brennanb2025/sta-1341-codex-terminal-scroll branch July 6, 2026 08:33
Jinwoo-H added a commit that referenced this pull request Jul 6, 2026
74 commits from main, including the STA-1278 ai-vault transcript perf work,
terminal flicker fix (#7540), renderer V8 heap raise (#7531), scrollbar
position preservation (#7472), and the per-delivery debug-snapshot
allocation removal (#7541).

Conflict resolutions (our structure, main's semantics):
- agent-detection: kept the split-module barrel; grafted main's Gemini/Pi
  title-detection refinements (path-fragment false positives, legacy Pi
  synthetic titles) into agent-title-core, dropped the superseded
  PI_IDLE_PREFIX.
- orca-runtime wait-blocked detection: kept the throttled
  scheduleWaitBlockedCheck (branch §1 optimization) and ported it to main's
  new cached TerminalTailWaitState API; main's per-chunk cached scan stays
  on the leaf mismatch path where it auto-merged. pty.tailWaitState is
  deliberately never populated on this branch (throttle owns the pty
  record), so the leaf mirror copy invalidates rather than shares — the
  fromTail exactness contract is never violated by stale state.
- recordPtyRendererDeliveryPressure: took main's allocation-free peak
  update (#7541) and derived per-pty in-flight from this branch's
  cumulative sent/acked accounting instead of the removed
  rendererInFlightCharsByPty map.
- rpc/methods/terminal detach: kept both sides — our
  flushAllAckPendingOutput and main's exitWaiterAbort release.
- pty-connection: kept our single-policy handleCommandFinished (invariant)
  alongside main's new sampleVisiblePaneForegroundAgent (bodies were
  byte-identical where they overlapped).
- e2e pressure scenarios: kept the Phase-4 hidden-gate contract assertions
  and the extracted pressure-script module; adopted main's
  MAX_WORST_KEY_LATENCY_UNDER_LOAD_MS budget.

Also documents the renderer-pull delivery watchdog in the branch guide.

Gates: typecheck clean; ipc/daemon/terminal-pane/pane-manager suites 4256
passed; both fuzz suites pass.

Co-authored-by: Orca <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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