Skip to content

Refine TUI wheel scroll feel - #7179

Merged
Jinwoo-H merged 2 commits into
mainfrom
Jinwoo-H/tui-scroll-feel
Jul 3, 2026
Merged

Jinwoo-H merged 2 commits into
mainfrom
Jinwoo-H/tui-scroll-feel

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • make fullscreen TUI wheel reports distance-aware using terminal row height, wheel delta mode, and legacy wheel deltas
  • keep paced 1x scrolling precise while allowing aggressive discrete mouse-wheel bursts to ramp higher
  • handle trackpad-like TUI pixel scrolling in Orca instead of falling through to xterm partial-scroll accumulation
  • cap trackpad pixel input to at most one synthetic TUI report per native wheel event so reports do not buffer and play out after release
  • suppress decaying and alternating trackpad momentum tails so scrolling stops after release instead of continuing by itself
  • stop applying burst boost to tiny trackpad pixel deltas and decaying mouse-wheel momentum tails
  • add a visible mouse-reporting TUI fixture plus focused report-count coverage

Verification

  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.test.ts
  • pnpm exec oxlint src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.ts src/renderer/src/lib/pane-manager/pane-terminal-tui-wheel-reports.ts src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.test.ts tests/e2e/terminal-tui-wheel-reports.spec.ts tests/e2e/fixtures/visible-tui-scroll-fixture.cjs

Harness evidence

  • paced 1x ticks stay precise: [1, 1, 1, 1]
  • fast 1x discrete ticks ramp: [1, 1, 3, 3, 4]
  • single huge discrete event caps at 6 reports
  • repeated aggressive discrete events ramp to [6, 6, 8, 8, 9]
  • decaying mouse-wheel momentum tail falls back to [6, 6, 8, 6, 6, 4]
  • rapid trackpad-like pixels are not burst boosted: [0, 0, 0, 1]
  • one large trackpad-like pixel event emits one report, not a batch: [1]
  • repeated large trackpad-like pixel events stay one report per event: [1, 1, 1]
  • trackpad-like reversal replays resolved reports as [1, -1]
  • decaying trackpad tail is suppressed: [1, 1, 1, 1, 0, 0, 0, 0]
  • alternating trackpad tail is suppressed: [1, 1, 1, 1, 1, 1, 0, 0, 0, 0]

Made with Orca

Co-authored-by: Orca <help@stably.ai>
@coderabbitai

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The terminal mouse-wheel flow now resolves wheel events through a shared report-count module, then replays the resolved reports through a queued microtask drain. The terminal attachment code now reads cell height from the terminal DOM, uses discrete-wheel detection, and enqueues report batches instead of dispatching a fixed multiplier loop. Unit tests cover report-count resolution and replay dispatch, and end-to-end tests add timed wheel sampling plus a visible scroll fixture.

Changes

Related issues: None found
Related PRs: None found
Suggested labels: area/terminal, tests
Suggested reviewers: None found

Sequence Diagram(s)

sequenceDiagram
  participant attachTerminalMouseWheelMultiplier
  participant resolveTerminalTuiMouseWheelReportCount
  participant queueTerminalTuiWheelReports
  participant DOM

  attachTerminalMouseWheelMultiplier->>resolveTerminalTuiMouseWheelReportCount: resolve reportCount
  resolveTerminalTuiMouseWheelReportCount-->>attachTerminalMouseWheelMultiplier: reportCount
  attachTerminalMouseWheelMultiplier->>queueTerminalTuiWheelReports: enqueue reportCount
  queueTerminalTuiWheelReports->>DOM: dispatch cloned wheel reports on drain
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers summary and verification, but it omits required Screenshots, AI Review Report, Security Audit, and Notes sections. Add the missing template sections and include screenshots or 'No visual change', an AI review summary, a security audit, and any platform notes.
✅ 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 is concise and accurately reflects the main change to TUI wheel scrolling behavior.
✨ 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 (5)
src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.ts (2)

239-266: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

No upper bound on pendingReports under sustained fast scrolling.

Each accelerated tick adds up to normalizedMaxReports to pendingReports, while the drain only emits TUI_WHEEL_REPORTS_PER_FRAME (4) per frame. If tick arrival outpaces the drain (fast continuous scroll), the backlog grows and reports keep firing after the gesture stops, causing scroll "momentum"/lag. Consider clamping pendingReports to a sane ceiling.

Please confirm the intended behavior for a long, fast gesture — whether accumulated reports beyond a threshold should be capped or dropped rather than fully replayed.


143-169: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Drop the unused streak field from the mouse-wheel acceleration state. streak is only updated here and never read, so the acceleration logic depends entirely on elapsedMs/cadence. Remove it from TerminalTuiMouseWheelAccelerationState and its initializer unless it’s meant to drive the curve later.

src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.test.ts (1)

93-135: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Verified acceleration math, but timestamp deltas are opaque.

Manually traced all four cases against resolveTerminalTuiMouseWheelReportCount's streak/easeOutCubic logic and every expected report count is consistent. The 200ms vs 50ms tick spacing is what determines whether a tick counts as "accelerating" against the internal window constant, but that constant and its relationship to these magic numbers isn't visible from the test alone.

A short inline comment noting why 200ms gaps stay unaccelerated (spacing exceeds the window) vs 50ms gaps accelerate would help future maintainers who touch TUI_WHEEL_ACCELERATION_WINDOW_MS without re-deriving the math.

As per coding guidelines: "When writing or modifying code driven by a design doc or non-obvious constraint, add a comment explaining why the code behaves the way it does."

Source: Coding guidelines

tests/e2e/terminal-tui-wheel-reports.spec.ts (2)

98-196: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Near-duplicate of probeSmallMouseWheelReports.

probeTimedSmallMouseWheelReports (lines 98-196) repeats almost the entire body of the existing probeSmallMouseWheelReports (pane lookup, mouse-reporting activation, deltaY computation, event construction) with only the timing/return-shape differing. This duplicates the "Why" comment and the deltaY formula in two places, so any future tuning of the notched-wheel simulation risks drifting between the two probes.

Consider making probeTimedSmallMouseWheelReports the single implementation and have probeSmallMouseWheelReports delegate to it with intervalMs: 0, drainWaitMs: 0 and map samples back to WheelReportSample[].

♻️ Proposed consolidation
-async function probeSmallMouseWheelReports(
-  page: Page,
-  ticks: number
-): Promise<WheelReportSample[]> {
-  return page.evaluate(
-    async ({ tickCount, physicalMouseWheelDelta }) => {
-      ...
-    },
-    { tickCount: ticks, physicalMouseWheelDelta: PHYSICAL_MOUSE_WHEEL_DELTA }
-  )
-}
+async function probeSmallMouseWheelReports(
+  page: Page,
+  ticks: number
+): Promise<WheelReportSample[]> {
+  const { samples } = await probeTimedSmallMouseWheelReports(page, {
+    ticks,
+    intervalMs: 0,
+    drainWaitMs: 0
+  })
+  return samples.map(({ reportCount, reportDelta, reports }) => ({
+    reportCount,
+    reportDelta,
+    reports
+  }))
+}

225-239: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Add a short timing note for the slow/fast probes. 220ms and 40ms are intentionally chosen around the 140ms acceleration window, so the split is stable but not obvious from the test alone.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: f23e03a2-1307-46c3-b12b-c23d8fda8fa3

📥 Commits

Reviewing files that changed from the base of the PR and between 087ad66 and d29b1a8.

📒 Files selected for processing (3)
  • src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.test.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.ts
  • tests/e2e/terminal-tui-wheel-reports.spec.ts

Co-authored-by: Orca <help@stably.ai>
@Jinwoo-H Jinwoo-H changed the title Tune TUI wheel scroll acceleration Refine TUI wheel scroll feel Jul 3, 2026
@Jinwoo-H
Jinwoo-H merged commit 827d2bb into main Jul 3, 2026
3 checks passed

@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

🧹 Nitpick comments (3)
src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.ts (2)

173-203: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Redundant multiplier normalization.

normalizeTerminalTuiMouseWheelMultiplier(options.getTuiMouseWheelMultiplier?.()) is called here (line 193) and the result is passed into resolveTerminalTuiMouseWheelReportCount, which normalizes it again internally (line 201 in pane-terminal-tui-wheel-reports.ts). Harmless since normalization is idempotent, but redundant — could drop one of the two calls.


93-104: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Move the terminal cell-height read off the wheel hot path. getBoundingClientRect() here can force sync layout during bursty scrolling; cache the height and refresh it from resize/font-metric updates instead. .xterm-screen is also an internal xterm DOM class, so this fallback can silently regress if xterm reshapes its markup.

tests/e2e/terminal-tui-wheel-reports.spec.ts (1)

206-281: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract shared active-pane resolution instead of triplicating it.

readVisibleTuiOffset, dispatchTuiWheel, and the inline cellHeight lookup each re-derive tabId/manager/pane from window.__store with the same ~10-line block. helpers/terminal.ts already has resolveActiveTabId for this (used by waitForActivePanePtyId); reusing it here would let each page.evaluate take a resolved tabId and just look up the pane.

♻️ Proposed refactor sketch
 async function readVisibleTuiOffset(page: Page): Promise<number | null> {
-  return page.evaluate(() => {
-    const state = window.__store?.getState()
-    const worktreeId = state?.activeWorktreeId
-    const tabId =
-      state?.activeTabType === 'terminal'
-        ? state.activeTabId
-        : worktreeId
-          ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null)
-          : null
-    const manager = tabId ? window.__paneManagers?.get(tabId) : null
-    const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null
+  const tabId = await resolveActiveTabId(page)
+  return page.evaluate((tabId) => {
+    const manager = tabId ? window.__paneManagers?.get(tabId) : null
+    const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null
     if (!pane?.terminal) {
       return null
     }
     ...
-  })
+  }, tabId)
 }

This assumes resolveActiveTabId is exported from ./helpers/terminal; please confirm before applying.

Also applies to: 357-373


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 39088d98-fd6c-4b04-854e-69e6029861d2

📥 Commits

Reviewing files that changed from the base of the PR and between d29b1a8 and ab602bf.

📒 Files selected for processing (5)
  • src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.test.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-tui-wheel-reports.ts
  • tests/e2e/fixtures/visible-tui-scroll-fixture.cjs
  • tests/e2e/terminal-tui-wheel-reports.spec.ts

Comment on lines +4 to +15
const DISCRETE_PIXEL_WHEEL_DELTA_MIN = 50
const LEGACY_MOUSE_WHEEL_DELTA_MIN = 100
const LEGACY_MOUSE_WHEEL_DELTA_UNIT = 120
const DEFAULT_TERMINAL_CELL_HEIGHT = 16
const TUI_WHEEL_ACCELERATED_DISTANCE_GAIN = 1.6
const TUI_WHEEL_BURST_FULL_INTERVAL_MS = 16
const TUI_WHEEL_BURST_MAX_INTERVAL_MS = 45
const TUI_WHEEL_BURST_MAX_BONUS_ROWS = 3
const TUI_WHEEL_BURST_RAMP_EVENTS = 4
const TUI_WHEEL_MOMENTUM_TAIL_DECAY_RATIO = 0.85
const TUI_WHEEL_COMPRESSED_MAX_DISTANCE_ROWS_PER_EVENT = 6
const TUI_WHEEL_BURST_MAX_DISTANCE_ROWS_PER_EVENT = 9

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.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Tuning constants lack "why" comments.

These 15 empirically-tuned constants (burst interval thresholds, decay ratio, distance caps, gain factor) encode non-obvious design decisions (per the PR's harness-tuned cadence curve) but have no comments explaining their derivation or intended effect. A future contributor tweaking scroll feel has no context for safe bounds.

📝 Example of adding brief rationale comments
+// Below this, xterm treats a discrete pixel delta as a synthetic 1px tick rather than a real notch.
 const DISCRETE_PIXEL_WHEEL_DELTA_MIN = 50
+// Legacy wheelDelta unit is 120/notch; treat >=100 as a full notch to tolerate rounding.
 const LEGACY_MOUSE_WHEEL_DELTA_MIN = 100
+// Ticks faster than this are considered part of the same burst cadence (~60fps).
 const TUI_WHEEL_BURST_FULL_INTERVAL_MS = 16
+// Ticks slower than this are treated as isolated, not a burst.
 const TUI_WHEEL_BURST_MAX_INTERVAL_MS = 45

As per coding guidelines, "When writing or modifying code driven by a design doc or non-obvious constraint, add a comment explaining why the code behaves the way it does."

Source: Coding guidelines

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