Skip to content

Reland mouse Back/Forward shortcuts, stored where a downgrade can't drop them - #23787

Open
nwparker wants to merge 1 commit into
mainfrom
neil/sta-8684-reland-23287-support-mouse-backforward-shortcuts-after
Open

nwparker wants to merge 1 commit into
mainfrom
neil/sta-8684-reland-23287-support-mouse-backforward-shortcuts-after

Conversation

@nwparker

@nwparker nwparker commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1030 $\color{#cf222e}{\Huge{\mathbf{−}}}$​5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1025
Prod 31 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​828 $\color{#cf222e}{\Huge{\mathbf{−}}}$​116 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​712

ELI5

You can assign your mouse's Back/Forward side buttons to Orca shortcuts again, including switching terminal tabs. This time, saving a mouse shortcut can't take your keyboard shortcut for the same command down with it.

What Changed

This relands #23287 and fixes the reason it was reverted (#23350).

The regression: a shortcut is stored as a string, and each command keeps one list of them. #23287 saved MouseBack into that same list. An Orca build that shipped before MouseBack existed can't parse it — and both stores reacted by throwing away the command's entire list, so Ctrl+PageDown disappeared along with it. On the paired web app the loss was permanent: an older bundle rewrites its whole stored document from its own parsed view, so the shortcut it dropped is gone from storage for good, even after upgrading again.

Before: save Mouse Back on "Next terminal tab", run an older build, and the keyboard shortcut you'd had for years stops working too.
After: the older build still reads the keyboard shortcut; it simply doesn't know about the mouse one.

The mechanism: mouse bindings are persisted in a place older builds ignore, and rejoined into one list per command on read.

Store Keyboard bindings Mouse bindings
~/.orca/keybindings.json keybindings, platforms.<os> mouse.keybindings, mouse.platforms.<os>
Web localStorage orca.web.keybindings.v1 orca.web.keybindingsMouse.v1
{
  "platforms": { "darwin": { "tab.nextTerminal": ["Ctrl+PageDown"] } },
  "mouse": { "platforms": { "darwin": { "tab.nextTerminal": ["MouseBack"] } } }
}

Only the two storage layers know the layout is split — splitBindingsByInputKind on write, unionKeybindingOverrides on read. Settings, conflict detection, and matching still see one list per command, so nothing else changed. The section is omitted until a mouse binding exists and pruned when the last one goes, so a file that never had one gains no new shape. A command whose only binding is a mouse button is written as [] in the keyboard section, so an older build reads it as "no keyboard shortcut" rather than falling back to the default.

Second, independent of the layout: reads now normalize each stored entry on its own and drop only the entry they can't parse, reporting it as a diagnostic. This is what getEffectiveKeybindingsForAction already did downstream; the persistence layer was the odd one out. If nothing survives, the command is left unset so it falls back to its defaults instead of reading as deliberately unbound.

Everything else is #23287 unchanged: recording, dispatch, terminal/floating routing, and native command dispatch.

Why

The revert's loss is a downgrade problem, so it can't be fixed by teaching new builds to be more careful — the builds that do the damage have already shipped. The only thing that helps them is not putting the token where they will look. A separate section works because an older build preserves an unknown root key through its own writes; on web it would destroy one, which is why that side needs its own storage key rather than a key inside the same document.

Alternatives considered: keeping one list and making readers tolerant (doesn't help already-shipped builds, which is the actual bug); mirroring the full list into the new section (preserves list order exactly, but duplicates every keyboard binding and silently wins over a hand-edit); and a separate set of mouse-only actions (loses the shortcut routing, conflict checks, and context handling that reusing the keybinding path buys). The chosen split costs one thing: a round-trip orders keyboard bindings before mouse ones within a command. Chips are unordered in the UI, so this is invisible.

Rule 2 is the durable one — it's why the next new token can't repeat this even if someone forgets rule 1. Both are written down in docs/reference/keybinding-token-downgrade-safety.md, linked from AGENTS.md.

Linked Issue

Relands #23287, reverted by #23350. Original feature request: #23255.

Visual Proof

The UI is unchanged from #23287. Before: Mouse Back leaves the recorder waiting.

Before: Mouse Back ignored

After: the same button is saved as Mouse Back; Shift+Forward is also recorded.

After: Mouse Back recorded

After: Shift+Mouse Forward recorded

Testing

Verified end-to-end in a real hidden Electron instance on macOS over CDP, driving the actual Settings UI:

  1. Opened Settings → Shortcuts, clicked "Add another shortcut for Next terminal tab", and sent a real side-button press. The row rendered ⌃ PageDown and Mouse Back.
  2. ~/.orca/keybindings.json on disk held platforms.darwin["tab.nextTerminal"] = ["Ctrl+PageDown"] with MouseBack isolated under mouse.platforms.darwin.
  3. Deleted the mouse section to stand in for a build that can't see it, reloaded in the running app: tab.nextTerminal still resolved to ["Ctrl+PageDown"], zero diagnostics. On main today this is where the keyboard shortcut vanishes.

Automated coverage added for both stores: the split layout, the downgrade read, a downgraded build's write leaving the section untouched, mouse-only commands, reset clearing both sections, section pruning, hand-authored sections, and per-entry tolerance. Plus unit tests for the split/union helpers. All of #23287's original suites still pass unchanged.

pnpm tc, oxlint, pnpm run check:code-quality:changed, and the localization gates pass. Ran ~15,600 tests across src/shared, src/main, and the affected renderer areas.

Not exercised: physical side-button hardware on Linux/Windows (modifier and platform behavior is covered by unit tests), and the restored e2e spec, which CI runs.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Review

Agent skill upstream boundary

  • Not applicable; no skill-sharing code changed.

Notes

Keybindings are client-local: no remote protocol change, no wire compatibility surface, and no worktree assumptions. Both stores are pure local persistence, so SSH and remote hosts are unaffected. No default shortcuts changed, and primary/middle/right and unbound side-button clicks keep their behavior. Embedded browser pages keep their native mouse navigation.

Backwards compatibility both ways: an existing keybindings.json is read exactly as before and gains no mouse key until a mouse binding is saved; a file or localStorage document written by this build is read correctly by older builds, minus the mouse bindings they can't do anyway.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

…rop them

Relands #23287. The revert (#23350) was for a shortcut-loss regression:
saving a mouse binding put `MouseBack` in the same per-action array as that
action's keyboard chords, and a build that predates the token dropped the
whole array rather than the one entry it could not parse. On the paired web
app the loss was permanent, because an older bundle rewrites its whole
document from its own parsed view.

Mouse bindings now persist in a section older builds ignore — a `mouse` root
key in keybindings.json, a separate localStorage key on web — and are rejoined
into one list per action on read, so nothing above the two stores changes.
Reads also normalize each stored entry on its own, keeping the bindings they
understand instead of discarding the action.
@coderabbitai

coderabbitai Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

The change adds Mouse Back and Mouse Forward as keybinding tokens, with optional modifiers. Desktop and web storage keep mouse bindings separate from keyboard bindings and combine them when reading settings. Renderer and main-window routing dispatch matching shortcuts, including terminal-tab and native actions. Stored bindings are normalized one entry at a time, and invalid entries produce diagnostics. The change also updates recording instructions and adds unit and end-to-end tests.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🔵 Low · up to f32ea

A rarely triggered case could swallow one mouse side-button release, and the impact is minor. The shortcut storage and dispatch changes show no blocking issues, though physical side-button behavior on Linux and Windows was not tested.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to f32ea

Separating mouse shortcuts protects older versions from losing keyboard shortcuts, and native actions remain gated by configured bindings. On the web, however, a failed save can leave the two shortcut stores out of sync, including when a user tries to remove a mouse shortcut.

Retained concerns

  • Medium · reliability · inferred: A web shortcut edit writes the keyboard document before the mouse document. If the second operation fails or execution stops between them, a reset can leave the old mouse binding active alongside partially updated keyboard state.
Security review details

Security Blast Radius

  • inferred — The demonstrated new dispatch authority is bounded to the main window and actions matching its configured shortcuts; the supplied paths do not establish a new cross-service, tenant, credential, or infrastructure authority.

Security Findings and Attack Paths

  • inferred — If a web mouse-binding reset fails after updating keyboard storage, the old mouse binding remains available on the next read. This is a conditional failure path, not evidence that an untrusted sender can choose or execute an arbitrary native action.

Trust Boundaries and Controls

  • observed — The main window loads an application document in production, installs a navigation policy, and restricts the new IPC handler to its own main frame. These controls do not by themselves establish the trustworthiness of all script executing inside that frame.

Resilience and Maintainability Implications

  • observed — The desktop writer refuses to replace an unreadable existing document and mutates the active platform while retaining other stored sections; the web writer instead performs two independent storage operations.

Hardening Proposals

  • proposed — Give web edits a recoverable commit protocol or explicit compensation so a failed second write cannot leave a revoked mouse shortcut in the effective snapshot.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.97% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 62 functions across 30 files. (10 skipped… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: relanding mouse Back/Forward shortcuts with downgrade-safe storage.
Description check ✅ Passed The description is complete and follows the repository template. It explains the user impact, implementation, rationale, linked issues, visual proof, testing, compatibility considerations, and checkli…
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 20.97% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 62 functions across 30 files. (10 skipped: 10 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR

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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 0b0fb80a-6d7c-476b-9d8a-4f68e1574a2f

📥 Commits

Reviewing files that changed from the base of the PR and between c5fc0c6 and f32eacf.

📒 Files selected for processing (40)
  • .gitignore
  • AGENTS.md
  • docs/reference/keybinding-token-downgrade-safety.md
  • docs/site/content/docs/settings.mdx
  • src/main/keybindings/keybinding-file-mouse-section.test.ts
  • src/main/keybindings/keybinding-file-parser.ts
  • src/main/keybindings/keybinding-file.ts
  • src/main/window/main-window-mouse-shortcuts.test.ts
  • src/main/window/main-window-shortcut-routing.ts
  • src/preload/api/ui-bridge-clipboard-and-window-controls.ts
  • src/preload/api/ui-window-api.ts
  • src/renderer/src/app-shell/register-app-mouse-shortcuts.ts
  • src/renderer/src/app-shell/use-global-keybindings.ts
  • src/renderer/src/components/dictation/use-hold-dictation-gesture.test.tsx
  • src/renderer/src/components/dictation/use-hold-dictation-gesture.ts
  • src/renderer/src/components/settings/ShortcutCommandBlock.tsx
  • src/renderer/src/components/terminal-workspace-keydown.test.ts
  • src/renderer/src/components/terminal-workspace-keydown.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/fr.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/lib/mouse-shortcut-dispatch.test.ts
  • src/renderer/src/lib/mouse-shortcut-dispatch.ts
  • src/renderer/src/web/preload-api/web-keybinding-normalization.ts
  • src/renderer/src/web/preload-api/web-keybindings-api.ts
  • src/renderer/src/web/preload-api/web-storage.ts
  • src/renderer/src/web/web-preload-api-keybindings-mouse.test.ts
  • src/shared/keybindings-mouse.test.ts
  • src/shared/keybindings.ts
  • src/shared/keybindings/definitions.ts
  • src/shared/keybindings/formatting.ts
  • src/shared/keybindings/mouse-bindings.ts
  • src/shared/keybindings/normalization.ts
  • src/shared/keybindings/parser.ts
  • src/shared/mouse-shortcut-input.test.ts
  • src/shared/mouse-shortcut-input.ts
  • tests/e2e/mouse-button-shortcuts.spec.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.

Comment on lines +47 to +73
const onMouseRelease = (event: MouseEvent): void => {
const pressed = pressedInputs.get(event.button)
if (event.type === 'mouseup' && pressed) {
pressedInputs.delete(event.button)
const target = pressed.target.isConnected ? pressed.target : window
target.dispatchEvent(
new KeyboardEvent('keyup', {
key: pressed.key,
code: pressed.key,
altKey: event.altKey,
ctrlKey: event.ctrlKey,
metaKey: event.metaKey,
shiftKey: event.shiftKey,
bubbles: true,
cancelable: true
})
)
}
if (!consumedButtons.has(event.button)) {
return
}
event.preventDefault()
event.stopImmediatePropagation()
if (event.type === 'auxclick') {
consumedButtons.delete(event.button)
}
}

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Clear stale consumedButtons entries when auxclick does not fire.

consumedButtons removes an entry only on auxclick or blur. The code runs consumedButtons.delete(event.button) on the next fresh mousedown. Between gestures, a missing auxclick leaves the entry set. Chromium can skip auxclick when the press and release land on different elements. It can also skip auxclick when the target is removed, for example after a tab switch. The next plain mouseup for that button then gets preventDefault and stopImmediatePropagation. This happens even when the button is unbound or is released after a press outside the window. That mouseup can suppress native back-navigation for the button. It also hides the mouseup from page handlers. Delete the entry on mouseup when no pressed entry exists. Alternatively, delete it on the next mousedown before the early returns.

Proposed fix
     const pressed = pressedInputs.get(event.button)
+    if (event.type === 'mouseup' && !pressed) {
+      consumedButtons.delete(event.button)
+      return
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const onMouseRelease = (event: MouseEvent): void => {
const pressed = pressedInputs.get(event.button)
if (event.type === 'mouseup' && pressed) {
pressedInputs.delete(event.button)
const target = pressed.target.isConnected ? pressed.target : window
target.dispatchEvent(
new KeyboardEvent('keyup', {
key: pressed.key,
code: pressed.key,
altKey: event.altKey,
ctrlKey: event.ctrlKey,
metaKey: event.metaKey,
shiftKey: event.shiftKey,
bubbles: true,
cancelable: true
})
)
}
if (!consumedButtons.has(event.button)) {
return
}
event.preventDefault()
event.stopImmediatePropagation()
if (event.type === 'auxclick') {
consumedButtons.delete(event.button)
}
}
const onMouseRelease = (event: MouseEvent): void => {
const pressed = pressedInputs.get(event.button)
if (event.type === 'mouseup' && !pressed) {
consumedButtons.delete(event.button)
return
}
if (event.type === 'mouseup' && pressed) {
pressedInputs.delete(event.button)
const target = pressed.target.isConnected ? pressed.target : window
target.dispatchEvent(
new KeyboardEvent('keyup', {
key: pressed.key,
code: pressed.key,
altKey: event.altKey,
ctrlKey: event.ctrlKey,
metaKey: event.metaKey,
shiftKey: event.shiftKey,
bubbles: true,
cancelable: true
})
)
}
if (!consumedButtons.has(event.button)) {
return
}
event.preventDefault()
event.stopImmediatePropagation()
if (event.type === 'auxclick') {
consumedButtons.delete(event.button)
}
}

@greptile-apps

greptile-apps Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 4/5

[Medium risk] Adds mouse button shortcuts for terminal navigation.

The PR should not merge until mouse shortcuts assigned to native actions work on the paired web app.

Findings

  1. P1 Web native shortcuts do nothing ▶
  2. P2 Failed writes leave split bindings ▶
  3. P2 Mouse section loses unknown properties ▶

Summary

The PR restores mouse Back/Forward shortcuts and separates their persistence from keyboard bindings so older builds can retain keyboard shortcuts.

  • Adds mouse recording and dispatch through renderer, preload, and main-process paths.
  • Splits and rejoins desktop and web storage, with per-entry normalization and downgrade tests.
  • Web-native action handling and split-store write consistency need attention.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  Settings[Shortcut settings] --> Split[Split keyboard and mouse bindings]
  Split --> FileKeyboard[Desktop keyboard section]
  Split --> FileMouse[Desktop mouse section]
  Split --> WebKeyboard[Web keyboard storage key]
  Split --> WebMouse[Web mouse storage key]
  FileKeyboard --> Union[Rejoined action bindings]
  FileMouse --> Union
  WebKeyboard --> Union
  WebMouse --> Union
  Union --> Dispatch[Shortcut matching and dispatch]
Loading

Reviews (1) · Last reviewed commit: "Reland mouse Back/Forward shortcuts, sto..."

Comment on lines +19 to +29
if (
!mouseInput ||
!window.api.ui.dispatchMouseShortcut ||
!resolveWindowShortcutAction(mouseInput, shortcutPlatform, state.keybindings, {
context: getKeybindingContext(input.target),
terminalShortcutPolicy: state.terminalShortcutPolicy
})
) {
return false
}
window.api.ui.dispatchMouseShortcut(mouseInput)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Web native shortcuts do nothing
On the paired web app, a user can save a mouse binding for a native action such as Open Settings, but pressing the button does nothing. The synthetic keydown has no renderer handler for that action, and the web UI API does not provide dispatchMouseShortcut, so this path returns without handling it. The button may then retain its normal browser behavior. Handle these actions in the web renderer or prevent users from assigning them there.

Knowledge Base Used: Desktop application platform

Comment on lines 213 to +228
writeJson(KEYBINDINGS_STORAGE_KEY, {
version: 1,
keybindings: currentSnapshot.commonOverrides,
keybindings: commonSplit.keyboard,
platforms: {
...currentSnapshot.platformOverrides,
darwin: currentSnapshot.platformOverrides.darwin ?? {},
linux: currentSnapshot.platformOverrides.linux ?? {},
win32: currentSnapshot.platformOverrides.win32 ?? {},
[platform]: activePlatform
darwin: {},
linux: {},
win32: {},
...otherPlatforms.keyboard,
[platform]: activeSplit.keyboard
}
} satisfies WebKeybindingDocument)
writeWebMouseKeybindingDocument({
version: 1,
keybindings: commonSplit.mouse,
platforms: { ...otherPlatforms.mouse, [platform]: activeSplit.mouse }
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Failed writes leave split bindings
If the second localStorage operation fails, the keyboard document has already been saved but the mouse document still holds its old bindings. The edit reports an error, yet later reads can show a combination the user never saved. Keep the two documents consistent when either write fails.

Knowledge Base Used: Restore stable shortcut persistence after mouse-button regression

Comment on lines +270 to +277
const nextMouseSection = buildMouseSection(mouseCommon, {
...mousePlatforms,
[keybindingPlatform]: mouseActivePlatform
})
if (nextMouseSection) {
document[MOUSE_SECTION_KEY] = nextMouseSection
} else {
delete document[MOUSE_SECTION_KEY]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Mouse section loses unknown properties
An unrelated desktop shortcut edit rebuilds the entire mouse object using only keybindings and platforms. If a hand-authored or future-version section contains another property, that edit silently deletes it, even though unknown root properties survive. Preserve unrecognized mouse-section properties while pruning empty binding sections.

@pullfrog pullfrog 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.

ℹ️ No critical issues — one informational note inline.

Reviewed changes — reland of mouse Back/Forward shortcut support with the downgrade-dropped-keyboard-binding regression addressed by splitting mouse bindings into storage locations older builds ignore.

  • Desktop storage split: mouse bindings move to a root mouse key (mouse.keybindings / mouse.platforms.<os>) in ~/.orca/keybindings.json; readKeybindingFile rejoins the two sections per action.
  • Web storage split: mouse bindings move to a separate localStorage key (orca.web.keybindingsMouse.v1), since an older web bundle rebuilds its whole document rather than spreading it.
  • Per-entry read tolerance: normalizeStoredKeybindingArrayForAction drops only the unparseable entry and reports it, leaving the action unset (so it falls back to defaults) when nothing survives.
  • Dispatch plumbing: renderer synthesizes a keydown/keyup for side buttons and routes through existing focused-surface handlers plus a native ui:dispatchMouseShortcut bridge; recorder and sender/frame guards added.
  • Tests/docs/i18n: new suites for both stores and dispatch, e2e spec, reference doc, and localized recorder copy.

I read the full diff and ran the 10 new/changed suites (6 node — 56 tests, 4 renderer — 54 tests); all pass. I also confirmed #23287 did not ship in desktop releases (v1.4.215 has no src/shared/mouse-shortcut-input.ts), which bounds the severity of the note below.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

const common = isJsonObject(document.keybindings)
? { ...document.keybindings }
: { ...fallbackCommonOverrides }
: { ...fallbackCommon.keyboard }

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.

The web write path re-splits its common/other-platform sections before writing (splitOverridesByInputKind in web-keybindings-api.ts), but the desktop path only re-splits the fallback here — document.keybindings on the line above and the non-active platforms sections are copied verbatim. A mouse token already sitting in the keyboard section therefore gets written back there (and also into the new mouse section), so a later downgrade can still drop the keyboard chords stored with it.

I confirmed this with a scratch test: writing an unrelated action to a file whose keybindings held ["Mod+Shift+P","MouseBack"] left keybindings unchanged and added mouse.keybindings alongside it. This state only arises from a hand-authored file or the pre-revert #23287 build (which never shipped in a desktop release per v1.4.215), so it is not blocking — but it contradicts the "a mouse binding must never land in the keyboard section" invariant this comment states, and the web path already handles it. Re-splitting the raw sections on the desktop side too would make the two stores consistent.

Technical details
# Desktop write does not re-split existing keyboard sections

## Affected sites
- `src/main/keybindings/keybinding-file.ts:235` — `common` copies `document.keybindings` verbatim when it is an object.
- `src/main/keybindings/keybinding-file.ts:243` — `platforms` is spread from the raw document, so non-active platform sections keep any mouse token.
- `src/main/keybindings/keybinding-file.ts:270` — `buildMouseSection` then adds the same token under `mouse`, leaving it in both places.

## Required outcome
- A mouse binding present in `keybindings`/`platforms.*` should end up only in the `mouse` section after any desktop write, matching the web store.

## Suggested approach (optional)
- Run the parsed keyboard common and each platform's overrides through `splitOverridesByInputKind`, writing `keyboard` back to `keybindings`/`platforms.*` and merging `mouse` into the mouse sections. `splitBindingsByInputKind` classifies only recognized mouse tokens as mouse, so hand-authored/future unknown tokens remain in the keyboard section.

## Open questions for the human (optional)
- Was copying `document.keybindings` verbatim deliberate for forward-compatibility, and if so, is the downgrade gap documented as accepted?

@syjeon121

Copy link
Copy Markdown

Hi! I'm hoping to see this land (mouse side buttons on Windows), so I went through the open bot findings and put together fixes for the three that still apply. Sharing it as a patch in case it's useful. It applies cleanly on top of f32eacfea34.

Fixed

  1. Stale consumedButtons (CodeRabbit): if mouseup arrives for a button that has no recorded press, the consumed flag is now cleared and the event is let through. This way, when a handled gesture never gets its auxclick, a later plain mouseup isn't suppressed. (mouse-shortcut-dispatch.ts)
  2. mouse section drops unknown keys on write (Greptile P2): buildMouseSection now starts from the stored section and replaces only keybindings/platforms. Hand-authored keys like $comment are kept, the same way the root document's are. (keybinding-file.ts)
  3. Non-atomic web write (Greptile P2 / security note): writeWebKeybindingAction saves both localStorage values before writing. If either write throws (e.g. quota), it restores both and rethrows, so a revoked mouse shortcut can't stay active after a failed save. (web-keybindings-api.ts)

Each fix adds one test that fails when the fix is reverted. The keybinding and mouse suites (79 tests), oxlint, oxfmt, tsc (node + web) and check:code-quality:changed all pass.

Not changed, on purpose

  • Greptile P1 (web: mouse bindings for native actions do nothing): I don't think this is specific to mouse bindings. On the web client, the keyboard bindings for those same native actions are also no-ops (onOpenSettings, onToggleWorktreePalette, etc. are stubbed in web-ui-api.ts). It looks like an existing web gap rather than something this PR introduces.
  • Pullfrog (desktop write doesn't re-split mouse tokens hand-placed in keyboard sections): this only happens in a hand-edited file, and moving user-authored entries between sections seemed debatable, so I left it alone.
Patch (git am)
From 0509c1562a9ad78a31bb3303ee1bcc29463bc6a3 Mon Sep 17 00:00:00 2001
From: syjeon121 <[email protected]>
Date: Thu, 5 Nov 2026 15:33:15 +0900
Subject: [PATCH] fix(keybindings): address #23787 review findings for mouse
 shortcuts

- Clear a stale consumed-button flag on a release with no recorded press, so a
  gesture whose auxclick never fired can't suppress a later plain mouseup.
- Keep hand-authored keys in the keybindings.json `mouse` section through
  Settings writes, matching how the root document is preserved.
- Roll back both web localStorage keys when the second write fails, so a
  revoked mouse shortcut can't stay active after a failed save.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../keybinding-file-mouse-section.test.ts     | 24 +++++++++
 src/main/keybindings/keybinding-file.ts       | 13 +++--
 .../src/lib/mouse-shortcut-dispatch.test.ts   |  8 +++
 .../src/lib/mouse-shortcut-dispatch.ts        |  5 ++
 .../web/preload-api/web-keybindings-api.ts    | 50 +++++++++++++------
 .../web-preload-api-keybindings-mouse.test.ts | 29 +++++++++++
 6 files changed, 110 insertions(+), 19 deletions(-)

diff --git a/src/main/keybindings/keybinding-file-mouse-section.test.ts b/src/main/keybindings/keybinding-file-mouse-section.test.ts
index d77a3042b6f..06f2fbb6eaa 100644
--- a/src/main/keybindings/keybinding-file-mouse-section.test.ts
+++ b/src/main/keybindings/keybinding-file-mouse-section.test.ts
@@ -171,6 +171,30 @@ describe('keybinding-file mouse section', () => {
     expect(snapshot.diagnostics).toEqual([])
   })
 
+  it('keeps hand-authored mouse section keys through a Settings write', () => {
+    writeFileSync(
+      filePath,
+      JSON.stringify({
+        version: 1,
+        keybindings: {},
+        platforms: { darwin: {}, linux: {}, win32: {} },
+        mouse: {
+          $comment: 'side buttons',
+          platforms: { darwin: { 'worktree.palette': 'MouseBack' } }
+        }
+      })
+    )
+
+    writeKeybindingOverride(filePath, 'darwin', 'worktree.quickOpen', ['MouseForward'])
+
+    expect(section(readDocument(filePath), ['mouse'])).toEqual({
+      $comment: 'side buttons',
+      platforms: {
+        darwin: { 'worktree.palette': 'MouseBack', 'worktree.quickOpen': ['MouseForward'] }
+      }
+    })
+  })
+
   it('reports a mouse section that is not an object', () => {
     writeFileSync(
       filePath,
diff --git a/src/main/keybindings/keybinding-file.ts b/src/main/keybindings/keybinding-file.ts
index f7165e1f22e..5165bcad0d3 100644
--- a/src/main/keybindings/keybinding-file.ts
+++ b/src/main/keybindings/keybinding-file.ts
@@ -196,8 +196,15 @@ function assignSplitBindings(
 
 // Why: keep the section out of the file entirely until a mouse binding exists,
 // so an ordinary keybindings.json gains no new shape from this feature.
-function buildMouseSection(common: JsonObject, platforms: JsonObject): JsonObject | null {
-  const section: JsonObject = {}
+function buildMouseSection(
+  stored: JsonObject,
+  common: JsonObject,
+  platforms: JsonObject
+): JsonObject | null {
+  // Why: keep hand-authored keys (e.g. `$comment`) the way the root document does.
+  const section: JsonObject = { ...stored }
+  delete section.keybindings
+  delete section.platforms
   if (Object.keys(common).length > 0) {
     section.keybindings = common
   }
@@ -267,7 +274,7 @@ function writeActivePlatformSection(
     win32: isJsonObject(platforms.win32) ? platforms.win32 : {},
     [keybindingPlatform]: activePlatform
   }
-  const nextMouseSection = buildMouseSection(mouseCommon, {
+  const nextMouseSection = buildMouseSection(mouseSection, mouseCommon, {
     ...mousePlatforms,
     [keybindingPlatform]: mouseActivePlatform
   })
diff --git a/src/renderer/src/lib/mouse-shortcut-dispatch.test.ts b/src/renderer/src/lib/mouse-shortcut-dispatch.test.ts
index 55673d39ebb..50c6e6b0ac3 100644
--- a/src/renderer/src/lib/mouse-shortcut-dispatch.test.ts
+++ b/src/renderer/src/lib/mouse-shortcut-dispatch.test.ts
@@ -90,6 +90,14 @@ describe('mouse shortcut dispatch', () => {
     expect(listener.mock.calls[0][0]).toMatchObject({ key: 'MouseForward', altKey: true })
   })
 
+  it('stops consuming after a handled gesture whose auxclick never arrived', () => {
+    setup()
+    mouse('mousedown', 3)
+    expect(mouse('mouseup', 3).defaultPrevented).toBe(true)
+    expect(mouse('mouseup', 3).defaultPrevented).toBe(false)
+    expect(mouse('auxclick', 3).defaultPrevented).toBe(false)
+  })
+
   it('clears consumed gestures on blur and removes listeners on cleanup', () => {
     setup()
     mouse('mousedown', 3)
diff --git a/src/renderer/src/lib/mouse-shortcut-dispatch.ts b/src/renderer/src/lib/mouse-shortcut-dispatch.ts
index b3681a53509..ec3a9d4db92 100644
--- a/src/renderer/src/lib/mouse-shortcut-dispatch.ts
+++ b/src/renderer/src/lib/mouse-shortcut-dispatch.ts
@@ -46,6 +46,11 @@ export function registerMouseShortcutDispatch(
   // Chromium can navigate on release; consume the rest of a handled gesture without rerunning it.
   const onMouseRelease = (event: MouseEvent): void => {
     const pressed = pressedInputs.get(event.button)
+    if (event.type === 'mouseup' && !pressed) {
+      // Why: a release with no recorded press isn't ours; drop a flag left by a gesture whose auxclick never fired.
+      consumedButtons.delete(event.button)
+      return
+    }
     if (event.type === 'mouseup' && pressed) {
       pressedInputs.delete(event.button)
       const target = pressed.target.isConnected ? pressed.target : window
diff --git a/src/renderer/src/web/preload-api/web-keybindings-api.ts b/src/renderer/src/web/preload-api/web-keybindings-api.ts
index ad11e0698e2..6cad38e9fd1 100644
--- a/src/renderer/src/web/preload-api/web-keybindings-api.ts
+++ b/src/renderer/src/web/preload-api/web-keybindings-api.ts
@@ -159,6 +159,14 @@ function writeWebMouseKeybindingDocument(document: WebKeybindingDocument): void
   } satisfies WebKeybindingDocument)
 }
 
+function restoreStorageItem(key: string, value: string | null): void {
+  if (value === null) {
+    window.localStorage.removeItem(key)
+  } else {
+    window.localStorage.setItem(key, value)
+  }
+}
+
 export function writeWebKeybindingAction(
   actionId: KeybindingActionId,
   bindings: string[] | null
@@ -210,22 +218,32 @@ export function writeWebKeybindingAction(
   }
 
   const otherPlatforms = splitOtherPlatformOverrides(currentSnapshot.platformOverrides, platform)
-  writeJson(KEYBINDINGS_STORAGE_KEY, {
-    version: 1,
-    keybindings: commonSplit.keyboard,
-    platforms: {
-      darwin: {},
-      linux: {},
-      win32: {},
-      ...otherPlatforms.keyboard,
-      [platform]: activeSplit.keyboard
-    }
-  } satisfies WebKeybindingDocument)
-  writeWebMouseKeybindingDocument({
-    version: 1,
-    keybindings: commonSplit.mouse,
-    platforms: { ...otherPlatforms.mouse, [platform]: activeSplit.mouse }
-  })
+  // Why: the edit spans two keys; a quota failure on the second must not leave a half-applied
+  // edit, such as a revoked mouse shortcut that stays active.
+  const previousKeyboard = window.localStorage.getItem(KEYBINDINGS_STORAGE_KEY)
+  const previousMouse = window.localStorage.getItem(MOUSE_KEYBINDINGS_STORAGE_KEY)
+  try {
+    writeJson(KEYBINDINGS_STORAGE_KEY, {
+      version: 1,
+      keybindings: commonSplit.keyboard,
+      platforms: {
+        darwin: {},
+        linux: {},
+        win32: {},
+        ...otherPlatforms.keyboard,
+        [platform]: activeSplit.keyboard
+      }
+    } satisfies WebKeybindingDocument)
+    writeWebMouseKeybindingDocument({
+      version: 1,
+      keybindings: commonSplit.mouse,
+      platforms: { ...otherPlatforms.mouse, [platform]: activeSplit.mouse }
+    })
+  } catch (error) {
+    restoreStorageItem(KEYBINDINGS_STORAGE_KEY, previousKeyboard)
+    restoreStorageItem(MOUSE_KEYBINDINGS_STORAGE_KEY, previousMouse)
+    throw error
+  }
 
   const snapshot = getWebKeybindingSnapshot()
   notifyWebKeybindingListeners(snapshot)
diff --git a/src/renderer/src/web/web-preload-api-keybindings-mouse.test.ts b/src/renderer/src/web/web-preload-api-keybindings-mouse.test.ts
index 96525852e13..1bf32718929 100644
--- a/src/renderer/src/web/web-preload-api-keybindings-mouse.test.ts
+++ b/src/renderer/src/web/web-preload-api-keybindings-mouse.test.ts
@@ -76,6 +76,35 @@ describe('web keybindings mouse storage', () => {
     expect(storage.getItem(MOUSE_KEY)).toBeNull()
   })
 
+  it('rolls back both keys when the second write fails', async () => {
+    const { api, storage } = await installApi('Linux')
+    await api.keybindings.setAction({
+      actionId: 'worktree.palette',
+      bindings: ['Ctrl+Alt+J', 'MouseBack']
+    })
+    const keyboardBefore = storage.getItem(KEYBOARD_KEY)
+    const mouseBefore = storage.getItem(MOUSE_KEY)
+    const setItem = storage.setItem.bind(storage)
+    let failed = false
+    vi.spyOn(storage, 'setItem').mockImplementation((key, value) => {
+      if (key === MOUSE_KEY && !failed) {
+        failed = true
+        throw new Error('QuotaExceededError')
+      }
+      setItem(key, value)
+    })
+
+    await expect(
+      api.keybindings.setAction({
+        actionId: 'worktree.palette',
+        bindings: ['Ctrl+Alt+K', 'MouseForward']
+      })
+    ).rejects.toThrow('QuotaExceededError')
+
+    expect(storage.getItem(KEYBOARD_KEY)).toBe(keyboardBefore)
+    expect(storage.getItem(MOUSE_KEY)).toBe(mouseBefore)
+  })
+
   it('never creates the mouse key for keyboard-only edits', async () => {
     const { api, storage } = await installApi('Linux')
 
-- 
2.53.0.windows.1

This branch has not been deployed

No deployments
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.

2 participants