Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(open-knowledge): smooth, consistent mouse-wheel scrolling in terminal TUIs (#2110)

serafin-garcia350b3935f653
diff --git a/.changeset/terminal-mouse-mode-wheel-scroll.md b/.changeset/terminal-mouse-mode-wheel-scroll.md
new file mode 100644
index 000000000..c34b60e4e
--- /dev/null
+++ b/.changeset/terminal-mouse-mode-wheel-scroll.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Fix jumpy, inconsistent mouse-wheel scrolling inside full-screen terminal apps that capture the mouse (the `claude` TUI, `vim`, `less`, `top`). In mouse-tracking mode xterm.js forwards one mouse-wheel report per OS wheel event with no accumulation, so the high-frequency event stream from trackpad momentum and free-spin/fast-scroll wheels floods the app — scrolling that lurches and can run away ("rocket scroll"). The terminal now accumulates fractional rows of travel and emits one wheel report per whole row of distance crossed, so scroll tracks the actual distance moved regardless of how many events deliver it: gentle drags and fast flicks over the same distance scroll the same amount, with no dead zone and a per-event clamp that absorbs momentum spikes. Normal scrollback (no mouse-capturing app) additionally gets smooth scrolling. Desktop only.
diff --git a/packages/app/src/components/TerminalPanel.dom.test.tsx b/packages/app/src/components/TerminalPanel.dom.test.tsx
index bf1838aac..bf2e69a5f 100644
--- a/packages/app/src/components/TerminalPanel.dom.test.tsx
+++ b/packages/app/src/components/TerminalPanel.dom.test.tsx
@@ -21,8 +21,17 @@ class MockTerminal {
cols = 80;
rows = 24;
unicode = { activeVersion: '6' };
+ modes = { mouseTrackingMode: 'none' as string };
+ mouseEncoding = 'SGR' as string;
+ get _core() {
+ return {
+ coreMouseService: { activeEncoding: this.mouseEncoding },
+ _renderService: { dimensions: { css: { cell: { height: 17 } } } },
+ };
+ }
onDataCb: ((d: string) => void) | null = null;
keyHandler: ((e: KeyboardEvent) => boolean) | null = null;
+ wheelHandler: ((e: WheelEvent) => boolean) | null = null;
options: Record<string, unknown>;
open = mock(() => {});
focus = mock(() => {});
@@ -45,6 +54,9 @@ class MockTerminal {
attachCustomKeyEventHandler = mock((h: (e: KeyboardEvent) => boolean) => {
this.keyHandler = h;
});
+ attachCustomWheelEventHandler = mock((h: (e: WheelEvent) => boolean) => {
+ this.wheelHandler = h;
+ });
constructor(options: Record<string, unknown>) {
this.options = options;
lastTerm = this;
@@ -153,6 +165,7 @@ describe('TerminalPanel', () => {
expect(lastTerm?.options.minimumContrastRatio).toBe(4.5);
expect(lastTerm?.unicode.activeVersion).toBe('11');
expect(lastTerm?.options.scrollback).toBe(10000);
+ expect(lastTerm?.options.smoothScrollDuration).toBe(125);
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
expect(terminal.create).toHaveBeenCalledWith({ cols: 80, rows: 24 });
@@ -291,6 +304,58 @@ describe('TerminalPanel', () => {
expect(plainEnterPreventDefault).not.toHaveBeenCalled();
});
+ test('wheel handler defers to xterm in normal scrollback, drives the PTY in mouse mode', async () => {
+ const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(lastTerm?.wheelHandler).toBeTruthy());
+ const term = lastTerm;
+ if (term?.wheelHandler == null) throw new Error('wheel handler not attached');
+ const wheel = term.wheelHandler;
+
+ term.modes.mouseTrackingMode = 'none';
+ expect(wheel({ deltaY: 120, deltaMode: 0 } as unknown as WheelEvent)).toBe(true);
+ expect(terminal.input).not.toHaveBeenCalled();
+
+ term.modes.mouseTrackingMode = 'any';
+ term.mouseEncoding = 'DEFAULT';
+ expect(wheel({ deltaY: 120, deltaMode: 0 } as unknown as WheelEvent)).toBe(true);
+ expect(terminal.input).not.toHaveBeenCalled();
+
+ term.mouseEncoding = 'SGR';
+ expect(wheel({ deltaY: 120, deltaMode: 0 } as unknown as WheelEvent)).toBe(false);
+ expect(terminal.input).toHaveBeenCalledTimes(1);
+ const [ptyId, payload] = terminal.input.mock.calls[0] as [string, string];
+ expect(ptyId).toBe('pty-1');
+ expect(payload).toBe('\x1b[<65;1;1M'.repeat(4));
+
+ terminal.input.mockClear();
+ term.mouseEncoding = 'SGR_PIXELS';
+ expect(wheel({ deltaY: 120, deltaMode: 0 } as unknown as WheelEvent)).toBe(false);
+ expect(terminal.input).toHaveBeenCalledTimes(1);
+ });
+
+ test('mode transition resets the wheel accumulator (no stale carry across apps)', async () => {
+ const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(lastTerm?.wheelHandler).toBeTruthy());
+ const term = lastTerm;
+ if (term?.wheelHandler == null) throw new Error('wheel handler not attached');
+ const wheel = term.wheelHandler;
+ term.mouseEncoding = 'SGR';
+
+ term.modes.mouseTrackingMode = 'any';
+ expect(wheel({ deltaY: 30, deltaMode: 0 } as unknown as WheelEvent)).toBe(false);
+ expect(terminal.input).toHaveBeenCalledTimes(1);
+
+ term.modes.mouseTrackingMode = 'none';
+ expect(wheel({ deltaY: 5, deltaMode: 0 } as unknown as WheelEvent)).toBe(true);
+
+ term.modes.mouseTrackingMode = 'any';
+ terminal.input.mockClear();
+ expect(wheel({ deltaY: 10, deltaMode: 0 } as unknown as WheelEvent)).toBe(false);
+ expect(terminal.input).not.toHaveBeenCalled();
+ });
+
test('disposes the terminal, kills the PTY, and unsubscribes on unmount', async () => {
const { bridge, terminal, unsubData, unsubExit } = makeBridge({ ok: true, ptyId: 'pty-1' });
const { unmount } = render(<TerminalPanel bridge={bridge} />);
diff --git a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
index b844a62e7..0730441ea 100644
--- a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
+++ b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
@@ -37,6 +37,7 @@ class MockTerminal {
attachCustomKeyEventHandler = mock((h: (e: KeyboardEvent) => boolean) => {
this.keyHandler = h;
});
+ attachCustomWheelEventHandler = mock(() => {});
constructor(options: Record<string, unknown>) {
this.options = options;
}
diff --git a/packages/app/src/components/TerminalPanel.tsx b/packages/app/src/components/TerminalPanel.tsx
index 0350dcd55..99aa8001c 100644
--- a/packages/app/src/components/TerminalPanel.tsx
+++ b/packages/app/src/components/TerminalPanel.tsx
@@ -17,6 +17,7 @@ import { TerminalCliMissingBanner } from './TerminalCliMissingBanner';
import { type TerminalExitInfo, TerminalExitNotice } from './TerminalExitNotice';
import { TerminalRefusalNotice } from './TerminalRefusalNotice';
import { xtermThemeForMode } from './terminal-theme';
+import { nextWheelReports, sgrWheelReport } from './terminal-wheel';
interface TerminalPanelProps {
/** Desktop bridge — the panel is rendered only on the Electron host, where
@@ -121,6 +122,7 @@ function TerminalSession({
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, monospace',
fontSize: 13,
scrollback: 10000,
+ smoothScrollDuration: 125,
theme: xtermThemeForMode(initialResolvedThemeRef.current),
});
termRef.current = term;
@@ -167,6 +169,46 @@ function TerminalSession({
return true;
});
+ let wheelRowAccumulator = 0;
+ let warnedMissingCellHeight = false;
+ term.attachCustomWheelEventHandler((event) => {
+ const core = (
+ term as unknown as {
+ _core?: {
+ coreMouseService?: { activeEncoding?: string };
+ _renderService?: { dimensions?: { css?: { cell?: { height?: number } } } };
+ };
+ }
+ )._core;
+ const encoding = core?.coreMouseService?.activeEncoding;
+ const sgrTrackingActive =
+ term.modes.mouseTrackingMode !== 'none' &&
+ (encoding === 'SGR' || encoding === 'SGR_PIXELS');
+ if (!sgrTrackingActive) {
+ wheelRowAccumulator = 0; // reset between gestures/apps; defer to xterm
+ return true;
+ }
+ const ptyId = ptyIdRef.current;
+ if (ptyId === null || event.deltaY === 0) return true;
+ const measuredCellHeight = core?._renderService?.dimensions?.css?.cell?.height;
+ if (measuredCellHeight === undefined && !warnedMissingCellHeight) {
+ warnedMissingCellHeight = true;
+ console.warn(
+ '[terminal] xterm cell-height internal not found; wheel scroll using fallback. An xterm upgrade may have moved _core._renderService.dimensions.css.cell.height.',
+ );
+ }
+ const cellHeight = measuredCellHeight ?? 17;
+ const { count, button, accumulator } = nextWheelReports(
+ event.deltaY,
+ event.deltaMode,
+ wheelRowAccumulator,
+ { cellHeight, sensitivity: 1, maxRowsPerEvent: 4, viewportRows: term.rows },
+ );
+ wheelRowAccumulator = accumulator;
+ if (count > 0) bridge.terminal.input(ptyId, sgrWheelReport(button).repeat(count));
+ return false;
+ });
+
void (async () => {
let result: Awaited<ReturnType<typeof bridge.terminal.create>>;
try {
diff --git a/packages/app/src/components/terminal-wheel.test.ts b/packages/app/src/components/terminal-wheel.test.ts
new file mode 100644
index 000000000..a31ace08c
--- /dev/null
+++ b/packages/app/src/components/terminal-wheel.test.ts
@@ -0,0 +1,100 @@
+import { describe, expect, test } from 'bun:test';
+import { nextWheelReports, sgrWheelReport, type WheelReportOptions } from './terminal-wheel';
+
+const PIXEL = 0;
+const LINE = 1;
+const PAGE = 2;
+
+const OPTS: WheelReportOptions = {
+ cellHeight: 20,
+ sensitivity: 1,
+ maxRowsPerEvent: 4,
+ viewportRows: 24,
+};
+
+/** Drive a sequence of wheel events through the accumulator, returning the
+ * total reports emitted (signed downward) — the user-visible travel. */
+function totalReports(deltas: readonly number[], opts: WheelReportOptions = OPTS): number {
+ let acc = 0;
+ let total = 0;
+ for (const deltaY of deltas) {
+ const r = nextWheelReports(deltaY, PIXEL, acc, opts);
+ acc = r.accumulator;
+ total += r.button === 65 ? r.count : -r.count;
+ }
+ return total;
+}
+
+describe('nextWheelReports', () => {
+ test('emits one report per whole row of pixel travel (PIXEL mode)', () => {
+ const r = nextWheelReports(60, PIXEL, 0, OPTS);
+ expect(r.count).toBe(3);
+ expect(r.button).toBe(65); // positive deltaY = wheel down
+ });
+
+ test('negative delta reports wheel-up (button 64)', () => {
+ const r = nextWheelReports(-60, PIXEL, 0, OPTS);
+ expect(r.count).toBe(3);
+ expect(r.button).toBe(64);
+ });
+
+ test('is frequency-independent: same distance over many small events == one big event', () => {
+ const many = totalReports(Array.from({ length: 20 }, () => 3));
+ const one = totalReports([60]);
+ expect(many).toBe(one);
+ expect(one).toBe(3);
+ });
+
+ test('no dead zone: sub-row events accumulate instead of being dropped', () => {
+ const first = nextWheelReports(5, PIXEL, 0, OPTS);
+ expect(first.count).toBe(0);
+ expect(first.accumulator).toBeCloseTo(0.25);
+ expect(totalReports([5, 5, 5, 5])).toBe(1);
+ });
+
+ test('per-event count is clamped to maxRowsPerEvent (momentum-spike guard)', () => {
+ const r = nextWheelReports(200, PIXEL, 0, OPTS);
+ expect(r.count).toBe(4);
+ });
+
+ test('clamped excess is discarded (only the fractional remainder carries)', () => {
+ const r = nextWheelReports(205, PIXEL, 0, OPTS);
+ expect(r.count).toBe(4);
+ expect(r.accumulator).toBeCloseTo(0.25);
+ });
+
+ test('reversing direction nets out at the sign boundary (frequency-independent)', () => {
+ const down = nextWheelReports(30, PIXEL, 0, OPTS);
+ expect(down.count).toBe(1);
+ expect(down.button).toBe(65);
+ expect(down.accumulator).toBeCloseTo(0.5);
+ const up = nextWheelReports(-30, PIXEL, down.accumulator, OPTS);
+ expect(up.count).toBe(1);
+ expect(up.button).toBe(64);
+ expect(up.accumulator).toBeCloseTo(0);
+ });
+
+ test('LINE mode counts deltaY directly as rows', () => {
+ const r = nextWheelReports(3, LINE, 0, OPTS);
+ expect(r.count).toBe(3);
+ expect(r.button).toBe(65);
+ });
+
+ test('PAGE mode scales by the viewport row count', () => {
+ const r = nextWheelReports(1, PAGE, 0, OPTS);
+ expect(r.count).toBe(4);
+ });
+
+ test('sensitivity scales total travel linearly', () => {
+ const base = totalReports([100]);
+ const half = totalReports([100], { ...OPTS, sensitivity: 0.5 });
+ expect(half).toBe(Math.trunc(base / 2));
+ });
+});
+
+describe('sgrWheelReport', () => {
+ test('encodes SGR wheel up/down press at position 1;1', () => {
+ expect(sgrWheelReport(64)).toBe('\x1b[<64;1;1M');
+ expect(sgrWheelReport(65)).toBe('\x1b[<65;1;1M');
+ });
+});
diff --git a/packages/app/src/components/terminal-wheel.ts b/packages/app/src/components/terminal-wheel.ts
new file mode 100644
index 000000000..5b0e2e136
--- /dev/null
+++ b/packages/app/src/components/terminal-wheel.ts
@@ -0,0 +1,48 @@
+export type WheelButton = 64 | 65;
+
+export interface WheelReportOptions {
+ readonly cellHeight: number;
+ readonly sensitivity: number;
+ readonly maxRowsPerEvent: number;
+ readonly viewportRows: number;
+}
+
+export interface WheelReportResult {
+ readonly count: number;
+ readonly button: WheelButton;
+ readonly accumulator: number;
+}
+
+const DOM_DELTA_LINE = 1;
+const DOM_DELTA_PAGE = 2;
+
+export function nextWheelReports(
+ deltaY: number,
+ deltaMode: number,
+ accumulator: number,
+ opts: WheelReportOptions,
+): WheelReportResult {
+ const rows =
+ deltaMode === DOM_DELTA_LINE
+ ? deltaY
+ : deltaMode === DOM_DELTA_PAGE
+ ? deltaY * opts.viewportRows
+ : deltaY / opts.cellHeight; // DOM_DELTA_PIXEL (and any unknown mode)
+
+ const next = accumulator + rows * opts.sensitivity;
+ const whole = Math.trunc(next);
+ if (whole === 0) {
+ return { count: 0, button: 65, accumulator: next };
+ }
+ return {
+ count: Math.min(Math.abs(whole), opts.maxRowsPerEvent),
+ button: whole < 0 ? 64 : 65,
+ accumulator: next - whole,
+ };
+}
+
+/** SGR-encoded wheel report at position 1;1 (always inside the window; mouse-
+ * mode apps scroll their active region regardless of the pointer cell). */
+export function sgrWheelReport(button: WheelButton): string {
+ return `\x1b[<${button};1;1M`;
+}