Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(canvas): route wheel-vs-trackpad by main-process gesture facts, not delta guessing

Rick-VIPER391056b81abd
diff --git a/src/main/index.ts b/src/main/index.ts
index bf3aa3afe..be1460693 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -46,6 +46,7 @@ import {
type RevocationTargets
} from './browser-revocation'
import { registerFsHandlers } from '../core/fs-handlers'
+import { TrackpadGestureLedger } from './trackpad-gesture'
import { LogBuffer } from '../core/log-buffer'
import { installLogSink, splitTag } from '../core/log-sink'
import { registerLogHandlers } from '../core/log-handlers'
@@ -976,6 +977,20 @@ function createWindow(): BrowserWindow {
// (both projects, every terminal). Bounded by the policy so a boot-path crash can't loop;
// past the budget the user decides. The tmux sessions all live in this process, so a reload
// costs nothing but the canvas re-hydrating from the workspace store.
+ // Trackpad-vs-mouse ground truth for the canvas wheel router: macOS wraps trackpad scrolls and
+ // pinches in gesture begin/end events a wheel mouse never emits, visible only here in main.
+ // The ledger reduces the raw stream (which includes every ~120Hz pointer packet — observe() is
+ // one Set lookup on the hot path) to edge transitions, so the renderer hears a few messages per
+ // physical gesture. Attached unconditionally: on non-mac these events simply never fire, and
+ // the renderer's router ignores the flag off macOS anyway. See main/trackpad-gesture.ts and
+ // canvas/wheel-gesture.ts for the two halves of the contract.
+ const trackpadLedger = new TrackpadGestureLedger()
+ win.webContents.on('input-event', (_event, input) => {
+ const active = trackpadLedger.observe(input.type)
+ if (active !== null && !win.isDestroyed()) {
+ win.webContents.send(IPC.canvasTrackpadGesture, active)
+ }
+ })
const crashReload = createCrashReloadPolicy()
win.webContents.on('render-process-gone', (_event, details) => {
ptyManager.dropClient(presenceId)
diff --git a/src/main/trackpad-gesture.test.ts b/src/main/trackpad-gesture.test.ts
new file mode 100644
index 000000000..21dc9b3f2
--- /dev/null
+++ b/src/main/trackpad-gesture.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest'
+import { TrackpadGestureLedger } from './trackpad-gesture'
+
+describe('TrackpadGestureLedger', () => {
+ it('reports a transition on the first begin and the matching end', () => {
+ const ledger = new TrackpadGestureLedger()
+ expect(ledger.observe('gestureScrollBegin')).toBe(true)
+ expect(ledger.observe('gestureScrollEnd')).toBe(false)
+ })
+
+ it('treats pinch begin/end as trackpad activity too', () => {
+ const ledger = new TrackpadGestureLedger()
+ expect(ledger.observe('gesturePinchBegin')).toBe(true)
+ expect(ledger.observe('gesturePinchEnd')).toBe(false)
+ })
+
+ it('stays silent for every non-gesture event (the ~120Hz path)', () => {
+ const ledger = new TrackpadGestureLedger()
+ expect(ledger.observe('mouseWheel')).toBe(null)
+ expect(ledger.observe('pointerRawUpdate')).toBe(null)
+ expect(ledger.observe('mouseMove')).toBe(null)
+ expect(ledger.observe('keyDown')).toBe(null)
+ })
+
+ it('does not repeat a state that has not changed (overlapping gestures nest)', () => {
+ // A pinch can begin while a scroll phase is still open; only the OUTERMOST transition is a
+ // state change worth an IPC message.
+ const ledger = new TrackpadGestureLedger()
+ expect(ledger.observe('gestureScrollBegin')).toBe(true)
+ expect(ledger.observe('gesturePinchBegin')).toBe(null)
+ expect(ledger.observe('gesturePinchEnd')).toBe(null)
+ expect(ledger.observe('gestureScrollEnd')).toBe(false)
+ })
+
+ it('ignores a stray end with no open gesture instead of going negative', () => {
+ const ledger = new TrackpadGestureLedger()
+ expect(ledger.observe('gestureScrollEnd')).toBe(null)
+ expect(ledger.observe('gestureScrollBegin')).toBe(true)
+ expect(ledger.observe('gestureScrollEnd')).toBe(false)
+ })
+
+ it('handles the observed touch-phase → momentum-phase sequence as two clean transitions', () => {
+ // Empirical shape from a macOS two-finger scroll with a glide (Electron 42, measured):
+ // Begin…End for the touch phase, a few mouseWheel packets, then Begin…End for momentum.
+ const ledger = new TrackpadGestureLedger()
+ expect(ledger.observe('gestureScrollBegin')).toBe(true)
+ expect(ledger.observe('mouseWheel')).toBe(null)
+ expect(ledger.observe('gestureScrollEnd')).toBe(false)
+ expect(ledger.observe('mouseWheel')).toBe(null)
+ expect(ledger.observe('gestureScrollBegin')).toBe(true)
+ expect(ledger.observe('gestureScrollEnd')).toBe(false)
+ })
+})
diff --git a/src/main/trackpad-gesture.ts b/src/main/trackpad-gesture.ts
new file mode 100644
index 000000000..8fdcb4c6d
--- /dev/null
+++ b/src/main/trackpad-gesture.ts
@@ -0,0 +1,45 @@
+/**
+ * Trackpad gesture ledger — the main-process half of canvas wheel routing.
+ *
+ * The renderer cannot tell a precise-pixel mouse (Magic Mouse, MX Master) from a trackpad: both
+ * reach the DOM as unmodified pixel-mode wheel events, which is why `canvas/wheel-gesture.ts`
+ * historically guessed from delta shapes and offered `trackpadPan` off as the escape hatch. The
+ * main process CAN tell: macOS delivers a trackpad's two-finger scroll to `webContents`
+ * 'input-event' wrapped in `gestureScrollBegin`/`gestureScrollEnd` (momentum included, as its own
+ * begin/end pair) and a pinch in `gesturePinchBegin`/`gesturePinchEnd`, while a wheel mouse only
+ * ever produces bare `mouseWheel` packets — measured on Electron 42 / macOS with an MX Master 3S
+ * and a MacBook trackpad side by side.
+ *
+ * This ledger reduces that stream to edge transitions ("a trackpad gesture is now open / now
+ * closed") so the wire cost is a handful of IPC messages per physical gesture, not one per
+ * packet. Depth-counting keeps an inner pinch inside an open scroll phase from reporting a false
+ * close, and a stray end (whose begin predates the listener) is ignored rather than driving the
+ * depth negative.
+ *
+ * Timing note for the consumer: one `mouseWheel` precedes the touch phase's `gestureScrollBegin`,
+ * and a few more sit in the gap before the momentum phase's begin. The renderer's router absorbs
+ * both with the same linger window it already used for heuristic stickiness — see
+ * `MacWheelGestureRouter.noteGesture`.
+ */
+
+const GESTURE_BEGIN = new Set(['gestureScrollBegin', 'gesturePinchBegin'])
+const GESTURE_END = new Set(['gestureScrollEnd', 'gesturePinchEnd'])
+
+export class TrackpadGestureLedger {
+ private depth = 0
+
+ /** Feed one raw input-event type; returns the new active state on a transition, null when
+ * nothing changed (the overwhelmingly common case — this runs on every input event). */
+ observe(type: string): boolean | null {
+ if (GESTURE_BEGIN.has(type)) {
+ this.depth += 1
+ return this.depth === 1 ? true : null
+ }
+ if (GESTURE_END.has(type)) {
+ if (this.depth === 0) return null
+ this.depth -= 1
+ return this.depth === 0 ? false : null
+ }
+ return null
+ }
+}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index f965a61cf..b6e285dc4 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -731,6 +731,11 @@ const api: NodeTerminalApi = {
ipcRenderer.on(IPC.ptyPressure, handler)
return () => ipcRenderer.removeListener(IPC.ptyPressure, handler)
},
+ onCanvasTrackpadGesture: (listener) => {
+ const handler = (_e: unknown, active: boolean) => listener(active)
+ ipcRenderer.on(IPC.canvasTrackpadGesture, handler)
+ return () => ipcRenderer.removeListener(IPC.canvasTrackpadGesture, handler)
+ },
raisePtyDeviceLimit: () => ipcRenderer.invoke(IPC.ptyRaiseDeviceLimit),
answerPermission: (payload) => ipcRenderer.invoke(IPC.agentAnswerPermission, payload),
ackDone: (nodeId) => {
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 0a9def0aa..c912525c0 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -466,6 +466,11 @@ export function buildStubApi(): Omit<
// here (see the note beside createPtyPressureMonitor in src/server/index.ts). The fix itself
// rejects rather than pretending, so a stray call can never look like it worked.
onPtyPressure: noopUnsub,
+ // A browser tab has no raw input stream to classify — trackpad-vs-mouse ground truth exists
+ // only under the Electron shell (main/trackpad-gesture.ts). Never fires here; the canvas
+ // wheel router is constructed WITHOUT gesture reporting in this runtime and keeps its
+ // delta-shape heuristics, so the degrade is a kept behavior, not a silent gap.
+ onCanvasTrackpadGesture: noopUnsub,
raisePtyDeviceLimit: async () => ({
ok: false as const,
error: 'Raising the terminal limit must be done on the machine running the server.'
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 49f76fb64..534c3c7b1 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -35,6 +35,7 @@ import {
} from '../nodes/TerminalNode'
import { solveFitPadding } from './fit-view'
import { MacWheelGestureRouter, trackpadRoutingEnabled } from './wheel-gesture'
+import { isBrowserRuntime } from '@renderer/bridge/runtime'
import { selectedLocalFilePaths } from './canvas-file-copy'
import {
canvasImagePasteArmedAfterKey,
@@ -3040,7 +3041,15 @@ export function Canvas() {
useEffect(() => {
const wrap = flowWrapRef.current
if (!wrap) return
- const wheelRouting = new MacWheelGestureRouter()
+ // Desktop: the main process reports trackpad gestures from the raw input stream, so the
+ // router routes by device FACT instead of delta-shape guessing — a precise-pixel mouse
+ // (MX Master) zooms while the trackpad pans, both settings on. The browser (Server Edition)
+ // has no such stream: reporting stays off and the router keeps its heuristics.
+ const gestureReporting = isMac && !isBrowserRuntime()
+ const wheelRouting = new MacWheelGestureRouter(gestureReporting)
+ const offGesture = gestureReporting
+ ? window.nodeTerminal.onCanvasTrackpadGesture?.((active) => wheelRouting.noteGesture(active))
+ : undefined
const onWheel = (e: WheelEvent) => {
if (canvasLocked) return
if (!e.ctrlKey && !e.metaKey) {
@@ -3072,7 +3081,10 @@ export function Canvas() {
setViewport({ x: px - (px - x) * k, y: py - (py - y) * k, zoom: next })
}
wrap.addEventListener('wheel', onWheel, { capture: true, passive: false })
- return () => wrap.removeEventListener('wheel', onWheel, { capture: true })
+ return () => {
+ wrap.removeEventListener('wheel', onWheel, { capture: true })
+ offGesture?.()
+ }
}, [getViewport, setViewport, wheelZoom, trackpadRouting, canvasLocked])
// Double-clicking EMPTY canvas pulls back to the overview zoom — the inverse of the node
diff --git a/src/renderer/canvas/wheel-gesture.test.ts b/src/renderer/canvas/wheel-gesture.test.ts
index 48fad63e3..61fc79b18 100644
--- a/src/renderer/canvas/wheel-gesture.test.ts
+++ b/src/renderer/canvas/wheel-gesture.test.ts
@@ -85,3 +85,58 @@ describe('MacWheelGestureRouter', () => {
expect(router.shouldPan(gesture(5), false, 1000)).toBe(false)
})
})
+
+describe('MacWheelGestureRouter with main-process gesture reporting', () => {
+ const reporting = () => new MacWheelGestureRouter(true)
+
+ it('zooms a smooth-looking packet when no trackpad gesture is in flight (the MX Master fix)', () => {
+ // A precise-pixel mouse emits exactly what a trackpad emits at the DOM level. With the
+ // main-process ledger reporting, silence is a POSITIVE fact — no gesture is open, so this
+ // is a wheel mouse and it must reach the zoom path even though the heuristic reads it as
+ // a trackpad.
+ const router = reporting()
+ expect(router.shouldPan(gesture(6.25), true, 1000)).toBe(false)
+ expect(router.shouldPan(gesture(30), true, 1010)).toBe(false)
+ })
+
+ it('pans while a reported gesture is active, even for a notch-quantized packet', () => {
+ const router = reporting()
+ router.noteGesture(true, 995)
+ expect(router.shouldPan(gesture(100, { wheelDeltaY: -120 }), true, 1000)).toBe(true)
+ })
+
+ it('keeps panning through the touch→momentum gap after the gesture ends', () => {
+ // Measured: a few mouseWheel packets arrive between the touch phase's End and the momentum
+ // phase's Begin. They belong to the same physical gesture and must not blip into zoom.
+ const router = reporting()
+ router.noteGesture(true, 1000)
+ router.noteGesture(false, 1200)
+ expect(router.shouldPan(gesture(40), true, 1230)).toBe(true)
+ // Long after the gesture (and its linger) the mouse owns the wheel again.
+ expect(router.shouldPan(gesture(40), true, 1900)).toBe(false)
+ })
+
+ it('still refuses non-mac, modified, and line-mode packets in reporting mode', () => {
+ const router = reporting()
+ router.noteGesture(true, 995)
+ expect(router.shouldPan(gesture(10), false, 1000)).toBe(false)
+ expect(router.shouldPan(gesture(10, { ctrlKey: true }), true, 1000)).toBe(false)
+ expect(router.shouldPan(gesture(10, { metaKey: true }), true, 1000)).toBe(false)
+ expect(router.shouldPan(gesture(10, { deltaMode: 1 }), true, 1000)).toBe(false)
+ })
+
+ it('without reporting (default constructor) the legacy heuristics are unchanged', () => {
+ const router = new MacWheelGestureRouter()
+ expect(router.shouldPan(gesture(6.25), true, 1000)).toBe(true)
+ expect(router.shouldPan(gesture(100, { wheelDeltaY: -120 }), true, 2000)).toBe(false)
+ })
+
+ it('noteGesture on a non-reporting router does not flip it into reporting mode', () => {
+ // The stub bridge never calls this, but a defensive caller might: reporting mode is decided
+ // by the shell (constructor), never inferred from traffic.
+ const router = new MacWheelGestureRouter()
+ router.noteGesture(true, 995)
+ router.noteGesture(false, 996)
+ expect(router.shouldPan(gesture(6.25), true, 1000)).toBe(true)
+ })
+})
diff --git a/src/renderer/canvas/wheel-gesture.ts b/src/renderer/canvas/wheel-gesture.ts
index 3228653c4..b278fc01e 100644
--- a/src/renderer/canvas/wheel-gesture.ts
+++ b/src/renderer/canvas/wheel-gesture.ts
@@ -11,9 +11,11 @@ export type MacWheelDestination = 'flow-pan' | 'native'
* router and React Flow's own `panOnScroll` have to agree exactly (disagreeing means a gesture
* that neither of them pans), and `trackpadPan` is the user's ESCAPE HATCH. Turning it off
* restores the pre-router behavior on macOS — `wheelZoom` alone decides, and a plain wheel zooms.
- * That is the recourse for a precise-pixel MOUSE (Magic Mouse, MX Master), whose deltas are
- * indistinguishable from a trackpad's here: it classifies as a trackpad and would otherwise have
- * no way back to wheel zoom.
+ * On the desktop the hatch is rarely needed anymore: main-process gesture reporting (the
+ * `gestureReporting` constructor flag below) identifies the device as a fact, so a precise-pixel
+ * MOUSE (Magic Mouse, MX Master) reaches wheel zoom while the trackpad keeps panning. It remains
+ * the recourse where reporting does not exist — the Server Edition's browser tab — whose
+ * heuristics still classify such a mouse as a trackpad.
*/
export const trackpadRoutingEnabled = (mac: boolean, trackpadPan: boolean): boolean =>
mac && trackpadPan
@@ -25,9 +27,41 @@ const LARGE_PIXEL_DELTA = 40
/** Pixel mode alone is not a device identity: Chromium uses it for trackpads and many mice. */
export class MacWheelGestureRouter {
private trackpadUntil = 0
+ private gestureActive = false
+ private gestureEndedAt = Number.NEGATIVE_INFINITY
+
+ /**
+ * `gestureReporting` — the desktop shell watches the raw input stream in the main process
+ * (main/trackpad-gesture.ts) and feeds `noteGesture` below, which makes device identity a FACT:
+ * macOS wraps every trackpad scroll/pinch in gestureScrollBegin/End events a wheel mouse never
+ * produces. With reporting on, the delta-shape heuristics below are bypassed entirely — silence
+ * from the ledger positively means "wheel mouse", which is what finally lets a precise-pixel
+ * mouse (MX Master) zoom while the trackpad pans, both settings on. The flag is decided by the
+ * SHELL (Electron preload present = true), never inferred from traffic: the Server Edition's
+ * browser tab has no raw input stream, stays at `false`, and keeps the heuristics.
+ */
+ constructor(private readonly gestureReporting = false) {}
+
+ /** Desktop only: the main-process ledger's edge transitions (trackpad gesture opened/closed). */
+ noteGesture(active: boolean, now = performance.now()): void {
+ this.gestureActive = active
+ if (!active) this.gestureEndedAt = now
+ }
shouldPan(event: WheelGesture, mac: boolean, now = performance.now()): boolean {
if (!mac || event.ctrlKey || event.metaKey || event.deltaMode !== 0) return false
+ if (this.gestureReporting) {
+ // Linger after a close: a few mouseWheel packets sit in the touch→momentum gap of the same
+ // physical gesture, and one precedes the next phase's Begin (measured; see
+ // main/trackpad-gesture.ts). The race the linger cannot cover — the FIRST packet of a
+ // brand-new gesture reaching this handler before the Begin's IPC message lands — is
+ // accepted: wheel dispatch is rAF-aligned while IPC is a plain task, so the flag almost
+ // always wins, and the loser is one small leading delta misrouted to zoom.
+ if (this.gestureActive || now - this.gestureEndedAt < TRACKPAD_SEQUENCE_MS) return true
+ // Reported silence is a positive fact: no trackpad gesture is open, so this packet is a
+ // wheel mouse — even when its deltas look trackpad-smooth.
+ return false
+ }
// Device identity is sticky for one physical gesture. Chromium can quantize a later
// trackpad/momentum event to wheelDeltaY=120; treating that single packet as a mouse notch
// hands it to wheelZoom and creates the observed one-frame zoom inside an otherwise pure pan.
diff --git a/src/renderer/components/settings/sections/BehaviorSection.tsx b/src/renderer/components/settings/sections/BehaviorSection.tsx
index 026be981d..f8133d52b 100644
--- a/src/renderer/components/settings/sections/BehaviorSection.tsx
+++ b/src/renderer/components/settings/sections/BehaviorSection.tsx
@@ -237,7 +237,7 @@ export function BehaviorSection({ isActive }: { isActive: boolean }): React.JSX.
<FieldRow
label="Trackpad scroll pans"
description={hintLabel(
- 'macOS: a two-finger trackpad scroll pans the canvas even with wheel zoom on. Turn off if a precise-pixel mouse (Magic Mouse, MX) pans when you meant to zoom.'
+ 'macOS: a two-finger trackpad scroll pans the canvas even with wheel zoom on. The desktop app tells mouse and trackpad apart directly, so a wheel mouse still zooms; in the browser (Server Edition) detection is heuristic — turn off there if a precise-pixel mouse (Magic Mouse, MX) pans when you meant to zoom.'
)}
control={
<Switch
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index be384b08a..9c7f50b3f 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -124,6 +124,12 @@ export const IPC = {
* so the renderer should run its reclaim levers now (hidden WebGL contexts, parked terminals).
* Payload: `'warning' | 'critical'`. Re-fired at most once a minute — see core/memory-pressure. */
appMemoryPressure: 'app:memory-pressure',
+ /** Main → renderer: a macOS trackpad gesture (two-finger scroll or pinch) opened or closed on
+ * the main window — edge transitions from main/trackpad-gesture.ts, a handful per physical
+ * gesture. Payload: `boolean` (active). The canvas wheel router uses this as ground-truth
+ * device identity, replacing delta-shape guessing on the desktop. Desktop only — the Server
+ * Edition's browser tab has no raw input stream and keeps the heuristics. */
+ canvasTrackpadGesture: 'canvas:trackpad-gesture',
agentStatus: 'agent:status',
/** Renderer → main/server: answer a held Claude permission hook (deterministic approvals).
* Payload: `{ nodeId, pendingId, decision: 'allow'|'deny' }`; resolves boolean. See
diff --git a/src/shared/types.ts b/src/shared/types.ts
index c3f6dac5b..8a69edf6d 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1220,7 +1220,10 @@ export interface Settings {
wheelZoom: boolean
/** macOS only: a two-finger trackpad scroll pans the canvas, independently of `wheelZoom`
* (see canvas/wheel-gesture.ts). Off restores the pre-router behavior — `wheelZoom` alone
- * decides — which is also the recourse for a precise-pixel MOUSE that reads as a trackpad. */
+ * decides. On the desktop the device is identified from the main process's raw input stream
+ * (main/trackpad-gesture.ts), so mouse zoom and trackpad pan coexist; the off-switch is the
+ * remaining recourse for the Server Edition's browser tab, where detection is heuristic and a
+ * precise-pixel MOUSE still reads as a trackpad. */
trackpadPan: boolean
/** What a left-drag on EMPTY canvas does. 'select' (default) rubber-band selects, like
* Figma's move tool — pan stays on middle-drag / two-finger scroll. 'pan' drags the map
@@ -2899,6 +2902,13 @@ export interface NodeTerminalApi {
* minutes; `level: 'none'` means the banner should come down. Returns unsubscribe.
* Server Edition: never fires — the reaper leg runs host-side only (see src/server/index.ts). */
onPtyPressure(listener: (reading: PtyPressure) => void): () => void
+ /** Fires when a macOS trackpad gesture (two-finger scroll or pinch) opens or closes on the
+ * main window — edge transitions from the main process's raw input stream
+ * (main/trackpad-gesture.ts), a handful per physical gesture. The canvas wheel router uses
+ * this as ground-truth device identity so a precise-pixel mouse (MX Master) can zoom while the
+ * trackpad pans. Returns unsubscribe. Server Edition: never fires — a browser tab has no raw
+ * input stream, and the router keeps its delta-shape heuristics there. */
+ onCanvasTrackpadGesture(listener: (active: boolean) => void): () => void
/** Raise this Mac's pty-device ceiling (`kern.tty.ptmx_max`) now AND across reboots, behind
* macOS's own administrator-password dialog. Called ONLY from the banner's explicit
* "Fix automatically…" click — never on the app's initiative. macOS only; a dismissed password