|
| 1 | +# ADR 017: Client — SGR mouse scroll sequences via custom wheel handler |
| 2 | + |
| 3 | +**SPEC:** [client](../specs/client.md) |
| 4 | +**Status:** Accepted |
| 5 | +**Date:** 2026-03-27 |
| 6 | + |
| 7 | +--- |
| 8 | + |
| 9 | +## Context |
| 10 | + |
| 11 | +When vim (or any TUI app) runs in webtty with `set mouse=a`, scrolling the |
| 12 | +mouse wheel moves the cursor up/down instead of scrolling the buffer. The same |
| 13 | +vim in a native terminal (VSCode, iTerm2) scrolls correctly. |
| 14 | + |
| 15 | +### How terminal mouse scrolling is supposed to work |
| 16 | + |
| 17 | +When a TUI app enables mouse tracking — typically via `DECSET ?1000h` (VT200 |
| 18 | +mouse protocol) and `DECSET ?1006h` (SGR mouse encoding) — the terminal |
| 19 | +emulator is obligated to report wheel events as mouse escape sequences rather |
| 20 | +than handling them itself. In SGR format: |
| 21 | + |
| 22 | +``` |
| 23 | +\x1b[<64;col;rowM — scroll up |
| 24 | +\x1b[<65;col;rowM — scroll down |
| 25 | +``` |
| 26 | + |
| 27 | +The app then processes K_MOUSEUP / K_MOUSEDOWN and scrolls its own buffer. |
| 28 | +Arrow keys (`\x1b[A` / `\x1b[B`) are cursor movement, not scroll events — |
| 29 | +if the terminal sends those instead, the cursor moves. |
| 30 | + |
| 31 | +### The ghostty-web bug |
| 32 | + |
| 33 | +ghostty-web's `Terminal.handleWheel` (registered with `capture: true`) fires |
| 34 | +before the `InputHandler`'s own wheel handler. It calls `stopPropagation()` |
| 35 | +immediately, so `InputHandler.handleWheel` — which correctly checks mouse |
| 36 | +tracking state and sends SGR sequences — never runs. |
| 37 | + |
| 38 | +`Terminal.handleWheel` then bifurcates on `isAlternateScreen()`: |
| 39 | + |
| 40 | +```js |
| 41 | +if (this.wasmTerm?.isAlternateScreen()) { |
| 42 | + // send arrow keys — always, regardless of mouse tracking state |
| 43 | + const dir = deltaY > 0 ? 'down' : 'up'; |
| 44 | + for (let i = 0; i < lines; i++) |
| 45 | + dir === 'up' ? dataEmitter.fire('\x1B[A') : dataEmitter.fire('\x1B[B'); |
| 46 | +} else { |
| 47 | + // scroll the viewport (correct for the shell prompt) |
| 48 | +} |
| 49 | +``` |
| 50 | +
|
| 51 | +vim always uses the alternate screen. So every scroll tick emits arrow keys |
| 52 | +into the PTY — moving the cursor — regardless of whether the app has requested |
| 53 | +mouse tracking. The mouse protocol the app negotiated is silently ignored. |
| 54 | +
|
| 55 | +### Why VSCode works |
| 56 | +
|
| 57 | +VSCode's terminal (xterm.js) checks whether the app has requested mouse |
| 58 | +events (`ctx.requestedEvents.wheel`) before falling back to arrow keys. When |
| 59 | +vim has enabled mouse tracking, xterm.js sends proper SGR sequences. ghostty-web |
| 60 | +skips this check entirely. |
| 61 | +
|
| 62 | +## Decision |
| 63 | +
|
| 64 | +Use `term.attachCustomWheelEventHandler()` to intercept wheel events before |
| 65 | +`Terminal.handleWheel` reaches its arrow-key path. |
| 66 | +
|
| 67 | +```ts |
| 68 | +let scrollAccum = 0; |
| 69 | +let scrollDir = 0; |
| 70 | +term.attachCustomWheelEventHandler((e: WheelEvent): boolean => { |
| 71 | + if (!term.hasMouseTracking()) return false; |
| 72 | + const metrics = term.renderer?.getMetrics(); |
| 73 | + if (!metrics) return false; |
| 74 | + const dir = e.deltaY < 0 ? -1 : 1; |
| 75 | + if (dir !== scrollDir) { scrollAccum = 0; scrollDir = dir; } |
| 76 | + scrollAccum += config.mouseScrollSpeed; |
| 77 | + const ticks = Math.trunc(scrollAccum); |
| 78 | + if (ticks === 0) return true; |
| 79 | + scrollAccum -= ticks; |
| 80 | + const rect = (e.target as HTMLElement).getBoundingClientRect(); |
| 81 | + const col = Math.max(1, Math.floor((e.clientX - rect.left) / metrics.width) + 1); |
| 82 | + const row = Math.max(1, Math.floor((e.clientY - rect.top) / metrics.height) + 1); |
| 83 | + const btn = dir < 0 ? 64 : 65; |
| 84 | + const seq = `\x1b[<${btn};${col};${row}M`; |
| 85 | + if (ws && ws.readyState === WebSocket.OPEN) { |
| 86 | + for (let i = 0; i < ticks; i++) ws.send(seq); |
| 87 | + } |
| 88 | + return true; |
| 89 | +}); |
| 90 | +``` |
| 91 | +
|
| 92 | +When the custom handler returns `true`, `Terminal.handleWheel` returns early |
| 93 | +and skips the arrow-key loop. When it returns `false` (mouse tracking off), |
| 94 | +the default behaviour is preserved — arrow keys are still sent for apps that |
| 95 | +benefit from that fallback (e.g. `less`, `man` without mouse support). |
| 96 | +
|
| 97 | +**Why SGR (button 64/65) and not X10 (button 4/5 + legacy encoding)?** |
| 98 | +SGR is always active in webtty because ghostty-web's `hasSgrMouseMode` |
| 99 | +defaults to `true`, and `TERM=xterm-256color` causes vim to enable SGR mode |
| 100 | +(`DECSET ?1006h`). Button codes 64 (scroll up) and 65 (scroll down) are the |
| 101 | +standard SGR wheel codes used by ghostty-web's own `InputHandler.handleWheel`. |
| 102 | +
|
| 103 | +## Considered Options |
| 104 | +
|
| 105 | +**Option A: Let InputHandler handle it** |
| 106 | +
|
| 107 | +`InputHandler.handleWheel` already does the right thing — but it never runs |
| 108 | +because `Terminal.handleWheel` calls `stopPropagation()` first. Removing |
| 109 | +`stopPropagation()` from `Terminal.handleWheel` would fix it but requires |
| 110 | +patching ghostty-web. |
| 111 | +
|
| 112 | +**Option B: Patch ghostty-web upstream** |
| 113 | +
|
| 114 | +The correct fix is for `Terminal.handleWheel` to check `hasMouseTracking()` |
| 115 | +before sending arrow keys — mirroring xterm.js's `ctx.requestedEvents.wheel` |
| 116 | +check. Until that patch lands, the custom handler is the correct workaround. |
| 117 | +
|
| 118 | +**Option C: `attachCustomWheelEventHandler` (chosen)** |
| 119 | +
|
| 120 | +Uses the public API ghostty-web already provides for exactly this purpose. |
| 121 | +Zero patches, removed when ghostty-web fixes its `Terminal.handleWheel`. |
| 122 | +
|
| 123 | +## Consequences |
| 124 | +
|
| 125 | +- vim `set mouse=a` scrolls the buffer as expected in webtty, matching native |
| 126 | + terminal behaviour. |
| 127 | +- Apps without mouse tracking (shell prompt, `less` without `-R`, etc.) |
| 128 | + continue to receive arrow keys from the default path — no regression. |
| 129 | +- One SGR sequence is sent per wheel tick by default (`mouseScrollSpeed: 1`). |
| 130 | + `mouseScrollSpeed` in config scales this: values `< 1` reduce rate via |
| 131 | + accumulation (e.g. `0.5` fires every other tick); values `> 1` send multiple |
| 132 | + SGRs per tick. Multi-line scroll per SGR is left |
| 133 | + to the app's `scroll` option (vim: `:set scroll=N`), consistent with how |
| 134 | + native terminals behave. |
| 135 | +- When ghostty-web fixes `Terminal.handleWheel` to respect mouse tracking |
| 136 | + state, `attachCustomWheelEventHandler` and this workaround can be removed. |
| 137 | +
|
| 138 | +## Fix to ghostty-web |
| 139 | +
|
| 140 | +### What the bug is |
| 141 | +
|
| 142 | +`Terminal.handleWheel` in `src/Terminal.ts` (registered on the canvas with |
| 143 | +`capture: true`) calls `stopPropagation()` unconditionally, which prevents |
| 144 | +`InputHandler.handleWheel` — the handler that correctly checks mouse tracking |
| 145 | +state — from ever running. It then sends arrow keys whenever |
| 146 | +`isAlternateScreen()` is true, without checking whether the application has |
| 147 | +requested mouse events: |
| 148 | +
|
| 149 | +```ts |
| 150 | +// src/Terminal.ts — Terminal.handleWheel (current, broken) |
| 151 | +this.handleWheel = (e: WheelEvent) => { |
| 152 | + e.preventDefault(); |
| 153 | + e.stopPropagation(); // ← blocks InputHandler |
| 154 | + if (this.customWheelEventHandler?.(e)) return; |
| 155 | + |
| 156 | + if (this.wasmTerm?.isAlternateScreen()) { |
| 157 | + const dir = e.deltaY > 0 ? 'down' : 'up'; |
| 158 | + const lines = Math.min(Math.abs(Math.round(e.deltaY / 33)), 5); |
| 159 | + for (let i = 0; i < lines; i++) |
| 160 | + this.dataEmitter.fire(dir === 'up' ? '\x1B[A' : '\x1B[B'); // ← always |
| 161 | + } else { |
| 162 | + // scroll viewport ... |
| 163 | + } |
| 164 | +}; |
| 165 | +``` |
| 166 | +
|
| 167 | +### What to change |
| 168 | +
|
| 169 | +In the `isAlternateScreen()` branch, check `this.wasmTerm.hasMouseTracking()` |
| 170 | +before emitting arrow keys. When mouse tracking is active, emit the SGR mouse |
| 171 | +scroll sequence instead. The `canvas` element and `renderer` are already |
| 172 | +available on `this`: |
| 173 | +
|
| 174 | +```ts |
| 175 | +// src/Terminal.ts — Terminal.handleWheel (fixed) |
| 176 | +this.handleWheel = (e: WheelEvent) => { |
| 177 | + e.preventDefault(); |
| 178 | + e.stopPropagation(); |
| 179 | + if (this.customWheelEventHandler?.(e)) return; |
| 180 | + |
| 181 | + if (this.wasmTerm?.isAlternateScreen()) { |
| 182 | + if (this.wasmTerm.hasMouseTracking()) { |
| 183 | + // App negotiated mouse tracking — send SGR scroll sequence, not arrow keys. |
| 184 | + const metrics = this.renderer?.getMetrics(); |
| 185 | + if (metrics && this.canvas) { |
| 186 | + const rect = this.canvas.getBoundingClientRect(); |
| 187 | + const col = Math.max(1, Math.floor((e.clientX - rect.left) / metrics.width) + 1); |
| 188 | + const row = Math.max(1, Math.floor((e.clientY - rect.top) / metrics.height) + 1); |
| 189 | + const btn = e.deltaY < 0 ? 64 : 65; |
| 190 | + this.dataEmitter.fire(`\x1b[<${btn};${col};${row}M`); |
| 191 | + } |
| 192 | + return; |
| 193 | + } |
| 194 | + // No mouse tracking: arrow-key fallback for apps like `less`. |
| 195 | + const dir = e.deltaY > 0 ? 'down' : 'up'; |
| 196 | + const lines = Math.min(Math.abs(Math.round(e.deltaY / 33)), 5); |
| 197 | + for (let i = 0; i < lines; i++) |
| 198 | + this.dataEmitter.fire(dir === 'up' ? '\x1B[A' : '\x1B[B'); |
| 199 | + } else { |
| 200 | + // scroll viewport (unchanged) ... |
| 201 | + } |
| 202 | +}; |
| 203 | +``` |
| 204 | +
|
| 205 | +### Why this is the right fix (not the webtty workaround) |
| 206 | +
|
| 207 | +The webtty workaround intercepts the event from outside via |
| 208 | +`attachCustomWheelEventHandler`, computes cell coordinates from the public |
| 209 | +`renderer.getMetrics()` and `e.target.getBoundingClientRect()`, then sends |
| 210 | +the sequence directly over the WebSocket. The upstream fix is structurally |
| 211 | +identical but happens inside `Terminal.handleWheel`, where `this.canvas` and |
| 212 | +`this.renderer` are already in scope — no BoundingClientRect detour needed, |
| 213 | +and the data flows through `dataEmitter` (the canonical internal channel) rather |
| 214 | +than bypassing it via WebSocket. With this upstream fix, the |
| 215 | +`attachCustomWheelEventHandler` call in webtty's `index.ts` can be deleted. |
| 216 | +
|
| 217 | +### Contribution checklist |
| 218 | +
|
| 219 | +- [ ] Open issue: `Terminal.handleWheel` sends arrow keys on alt screen even |
| 220 | + when mouse tracking is active (`hasMouseTracking() === true`) |
| 221 | +- [ ] PR: `src/Terminal.ts` — add `hasMouseTracking()` guard in the |
| 222 | + `isAlternateScreen()` branch; emit SGR scroll sequence when true, fall back |
| 223 | + to arrow keys when false |
| 224 | +- [ ] Test: `write('\x1b[?1000h')` (enable mouse tracking) → simulate wheel |
| 225 | + event → assert `onData` receives `\x1b[<64;…M` or `\x1b[<65;…M`, NOT |
| 226 | + `\x1b[A` / `\x1b[B` |
| 227 | +
|
| 228 | +## Related Decisions |
| 229 | +
|
| 230 | +- [ADR 013 — DECSCUSR cursor style via PTY intercept](013.client.cursor-style.md): |
| 231 | + same pattern — a ghostty-web rendering gap worked around at the webtty client |
| 232 | + layer until upstream fixes it. |
| 233 | +- [ADR 016 — `term` default is `xterm-256color`](016.config.term-default.md): |
| 234 | + ensures vim gets a TERM value whose terminfo includes mouse tracking |
| 235 | + capabilities, so vim actually sends the DECSET sequences that activate this path. |
0 commit comments