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(main): keydown intercept resolves node.close/toggleMarkdown from settings

enes8794ff62168b
diff --git a/src/main/index.ts b/src/main/index.ts
index 7f4aba1f7..ad45c533b 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -88,7 +88,11 @@ import {
syntheticAnsweredEvent
} from '../core/agents/pending-approvals'
import { setMainWindow, getMainWindow, sendToMain, closeAction, createCrashReloadPolicy } from './main-window'
-import { installKeydownIntercepts } from './keydown-intercept'
+import {
+ installKeydownIntercepts,
+ resolveInterceptBindings,
+ type KeydownInterceptBindings
+} from './keydown-intercept'
import {
initNotchHud,
applyNotchHudSettings,
@@ -276,6 +280,18 @@ function isSafeExternalUrl(url: unknown): url is string {
}
const settingsStore = new SettingsStore()
+// ⌘M / ⌘W are registry commands (`node.toggleMarkdown` / `node.close`), so what the window
+// intercepts follows the user's settings. Resolved LAZILY (first keystroke, long after
+// `settingsStore.init()` in `whenReady`) rather than at module load, where `get()` would still be
+// DEFAULT_SETTINGS and every override would be missed until the next save; recomputed on
+// `onChange`, which fires after a successful save. Never per keystroke — sanitize is real work.
+const interceptIsMac = process.platform === 'darwin'
+let interceptBindings: KeydownInterceptBindings | null = null
+const currentInterceptBindings = (): KeydownInterceptBindings =>
+ (interceptBindings ??= resolveInterceptBindings(settingsStore.get().keybindings, interceptIsMac))
+settingsStore.onChange((s) => {
+ interceptBindings = resolveInterceptBindings(s.keybindings, interceptIsMac)
+})
const sshStore = new SshStore()
const ptyManager = new PtyManager()
// Dictation: local whisper.cpp models live under userData, one dir per install (same convention
@@ -668,8 +684,9 @@ function createWindow(): BrowserWindow {
// Steal ⌘M / ⌘W / ⌘0 back from Electron's default application menu (minimize / close /
// resetZoom) and forward each to the renderer instead. The decision — and, importantly, what it
- // must REFUSE — is in `keydown-intercept.ts`, where it can be pressed by a test.
- installKeydownIntercepts(win)
+ // must REFUSE — is in `keydown-intercept.ts`, where it can be pressed by a test. The first two
+ // are the user's effective `node.toggleMarkdown` / `node.close` bindings (⌘0 is not remappable).
+ installKeydownIntercepts(win, currentInterceptBindings, interceptIsMac)
// Open external links in the system browser — only safe schemes (no file://, no custom
// protocol handlers). Reachable from remotely-fetched announcement URLs and rendered
diff --git a/src/main/keydown-intercept.test.ts b/src/main/keydown-intercept.test.ts
index a4b3a5acd..bc9ce6ee4 100644
--- a/src/main/keydown-intercept.test.ts
+++ b/src/main/keydown-intercept.test.ts
@@ -3,6 +3,8 @@ import { IPC } from '../shared/ipc'
import {
installKeydownIntercepts,
keydownIntercept,
+ resolveInterceptBindings,
+ type KeydownInterceptBindings,
type KeydownInterceptInput,
type KeydownInterceptTarget
} from './keydown-intercept'
@@ -38,12 +40,23 @@ function input(over: Partial<KeydownInterceptInput> = {}): KeydownInterceptInput
}
}
+/** The shipped bindings, per platform. `node.close` / `node.toggleMarkdown` default to `Cmd+W` /
+ * `Cmd+M` on both, but `Cmd` RESOLVES differently — ⌘ on mac, Control elsewhere — which is what
+ * makes `press(…, { isMac: false })` below the Windows/Linux run of the same chord. */
+const DEFAULTS = resolveInterceptBindings(undefined, true)
+const DEFAULTS_PC = resolveInterceptBindings(undefined, false)
+
/**
* Press a key at the real installation seam: register the handler on a fake window exactly as
* `createWindow` does, then dispatch. Covers the wiring (`preventDefault` is called, the channel is
* sent on `webContents`), not just the pure decision.
*/
-function press(over: Partial<KeydownInterceptInput> = {}): { prevented: boolean; sent: string[] } {
+function press(
+ over: Partial<KeydownInterceptInput> = {},
+ opts: { bindings?: KeydownInterceptBindings; isMac?: boolean } = {}
+): { prevented: boolean; sent: string[] } {
+ const isMac = opts.isMac ?? true
+ const bindings = opts.bindings ?? (isMac ? DEFAULTS : DEFAULTS_PC)
let handler:
| ((event: { preventDefault(): void }, input: KeydownInterceptInput) => void)
| null = null
@@ -58,7 +71,7 @@ function press(over: Partial<KeydownInterceptInput> = {}): { prevented: boolean;
}
}
}
- installKeydownIntercepts(win)
+ installKeydownIntercepts(win, () => bindings, isMac)
if (!handler) throw new Error('installKeydownIntercepts registered no before-input-event listener')
let prevented = false
;(handler as (e: { preventDefault(): void }, i: KeydownInterceptInput) => void)(
@@ -116,6 +129,10 @@ describe('⌘0 → canvas back to 100%', () => {
it('is intercepted under Ctrl too (Windows / Linux)', () => {
expect(press({ control: true })).toEqual({ prevented: true, sent: [IPC.appZoomActualSize] })
+ expect(press({ control: true }, { isMac: false })).toEqual({
+ prevented: true,
+ sent: [IPC.appZoomActualSize]
+ })
})
// Matched on the physical key, so the chord survives a layout where the zero key prints
@@ -147,24 +164,22 @@ describe('⌘M → markdown view, stolen back from Window ▸ Minimize', () => {
prevented: true,
sent: [IPC.appToggleMarkdown]
})
- expect(press({ control: true, key: 'm', code: 'KeyM' })).toEqual({
+ // Windows / Linux: the same `Cmd+M` binding resolves to Control there.
+ expect(press({ control: true, key: 'm', code: 'KeyM' }, { isMac: false })).toEqual({
prevented: true,
sent: [IPC.appToggleMarkdown]
})
})
- // The shipped breadth of this branch: unlike ⌘W and ⌘0 it tests no Shift/Alt, so ⌘⇧M and ⌘⌥M
- // toggle too. Pinned as-is — narrowing it is a real behaviour change (⌘⇧M would go back to the
- // menu) and should turn this red on purpose rather than slip through.
- it('also claims ⌘⇧M and ⌘⌥M', () => {
- expect(press({ meta: true, shift: true, key: 'M', code: 'KeyM' })).toEqual({
- prevented: true,
- sent: [IPC.appToggleMarkdown]
- })
- expect(press({ meta: true, alt: true, key: 'm', code: 'KeyM' })).toEqual({
- prevented: true,
- sent: [IPC.appToggleMarkdown]
- })
+ // D-STRICT DELTA (named in the PR body). The old branch was `key === 'm'` under a
+ // `meta || control` guard, so ⌘⇧M, ⌘⌥M and — on mac — ⌃M all toggled too. Matching a real
+ // binding is exact on all four modifier flags, so each of those is now a different chord and
+ // goes back to the page/menu. This is the behaviour change; assert it rather than leave it to
+ // a reader of the diff.
+ it('no longer claims ⌘⇧M, ⌘⌥M, or ⌃M on mac', () => {
+ expect(press({ meta: true, shift: true, key: 'M', code: 'KeyM' })).toEqual(UNTOUCHED)
+ expect(press({ meta: true, alt: true, key: 'm', code: 'KeyM' })).toEqual(UNTOUCHED)
+ expect(press({ control: true, key: 'm', code: 'KeyM' })).toEqual(UNTOUCHED)
})
it('repeats keep toggling (no auto-repeat rule here, unlike ⌘0)', () => {
@@ -181,7 +196,7 @@ describe('⌘W → close the selected node, stolen back from Window ▸ Close',
prevented: true,
sent: [IPC.appCloseNode]
})
- expect(press({ control: true, key: 'w', code: 'KeyW' })).toEqual({
+ expect(press({ control: true, key: 'w', code: 'KeyW' }, { isMac: false })).toEqual({
prevented: true,
sent: [IPC.appCloseNode]
})
@@ -190,14 +205,87 @@ describe('⌘W → close the selected node, stolen back from Window ▸ Close',
it('leaves ⌘⇧W to the menu (Close All Windows)', () => {
expect(press({ meta: true, shift: true, key: 'W', code: 'KeyW' })).toEqual(UNTOUCHED)
})
+
+ // Same D-strict delta as ⌘M's: ⌃W was swallowed app-wide on mac (where it is readline's
+ // delete-word, not a menu accelerator) and now reaches the page.
+ it('no longer claims ⌃W on mac', () => {
+ expect(press({ control: true, key: 'w', code: 'KeyW' })).toEqual(UNTOUCHED)
+ })
})
describe('the decision is pure', () => {
// Same function, called directly: a caller that is not a BrowserWindow (a future menu, a test,
// the next intercept) gets the same answer, and `null` unambiguously means "not ours".
it('returns null for anything unclaimed and an action for a claimed chord', () => {
- expect(keydownIntercept(input())).toBeNull()
- expect(keydownIntercept(input({ meta: true }))).toEqual({ action: 'zoom-actual-size' })
- expect(keydownIntercept(input({ meta: true, isAutoRepeat: true }))).toEqual({ action: null })
+ expect(keydownIntercept(input(), DEFAULTS, true)).toBeNull()
+ expect(keydownIntercept(input({ meta: true }), DEFAULTS, true)).toEqual({
+ action: 'zoom-actual-size'
+ })
+ expect(keydownIntercept(input({ meta: true, isAutoRepeat: true }), DEFAULTS, true)).toEqual({
+ action: null
+ })
+ })
+})
+
+describe('binding-driven intercept', () => {
+ it('defaults reproduce today: Cmd+M and Cmd+W intercept, Shift variants do not', () => {
+ expect(keydownIntercept(input({ meta: true, key: 'm', code: 'KeyM' }), DEFAULTS, true)).toEqual({
+ action: 'toggle-markdown'
+ })
+ expect(keydownIntercept(input({ meta: true, key: 'w', code: 'KeyW' }), DEFAULTS, true)).toEqual({
+ action: 'close-node'
+ })
+ expect(keydownIntercept(input({ meta: true, shift: true, key: 'w', code: 'KeyW' }), DEFAULTS, true)).toBeNull()
+ // D-strict delta, named in the PR body: ⌘⇧M no longer intercepts (old code ignored shift on m).
+ expect(keydownIntercept(input({ meta: true, shift: true, key: 'm', code: 'KeyM' }), DEFAULTS, true)).toBeNull()
+ })
+
+ it('an unbound command stops intercepting (Electron default returns)', () => {
+ const unbound = resolveInterceptBindings({ 'node.close': [] }, true)
+ expect(keydownIntercept(input({ meta: true, key: 'w', code: 'KeyW' }), unbound, true)).toBeNull()
+ expect(keydownIntercept(input({ meta: true, key: 'm', code: 'KeyM' }), unbound, true)).toEqual({
+ action: 'toggle-markdown'
+ })
+ })
+
+ it('a remap moves the interception', () => {
+ const remapped = resolveInterceptBindings({ 'node.toggleMarkdown': ['Cmd+Shift+M'] }, true)
+ expect(keydownIntercept(input({ meta: true, key: 'm', code: 'KeyM' }), remapped, true)).toBeNull()
+ expect(keydownIntercept(input({ meta: true, shift: true, key: 'm', code: 'KeyM' }), remapped, true)).toEqual({
+ action: 'toggle-markdown'
+ })
+ })
+
+ // The reason the primary-modifier half of the old shared gate could NOT stay where it was: an
+ // Alt-only chord is a valid binding per the registry's rules, this intercept is its only
+ // dispatcher (the chord never reaches the renderer — the page does not see a claimed key), so a
+ // `meta || control` gate above the matchers would make the remap dead everywhere with no error.
+ it('an Alt-only remap fires, and the bare key still does not', () => {
+ const alt = resolveInterceptBindings({ 'node.toggleMarkdown': ['Alt+M'] }, true)
+ expect(keydownIntercept(input({ alt: true, key: 'm', code: 'KeyM' }), alt, true)).toEqual({
+ action: 'toggle-markdown'
+ })
+ expect(keydownIntercept(input({ key: 'm', code: 'KeyM' }), alt, true)).toBeNull()
+ })
+
+ it('garbage overrides fall back to defaults', () => {
+ expect(resolveInterceptBindings({ 'node.close': ['garbage+++'] }, true)).toEqual(DEFAULTS)
+ })
+
+ it('the Digit0 zoom gesture is untouched by bindings', () => {
+ const unbound = resolveInterceptBindings({ 'node.close': [], 'node.toggleMarkdown': [] }, true)
+ expect(keydownIntercept(input({ meta: true, code: 'Digit0' }), unbound, true)).toEqual({
+ action: 'zoom-actual-size'
+ })
+ // ...and it keeps the primary-modifier requirement it used to inherit from the shared gate.
+ expect(keydownIntercept(input({ code: 'Digit0' }), unbound, true)).toBeNull()
+ })
+
+ it('a remapped binding is dispatched at the install seam too', () => {
+ const remapped = resolveInterceptBindings({ 'node.close': ['Cmd+Shift+K'] }, true)
+ expect(press({ meta: true, shift: true, key: 'K', code: 'KeyK' }, { bindings: remapped })).toEqual(
+ { prevented: true, sent: [IPC.appCloseNode] }
+ )
+ expect(press({ meta: true, key: 'w', code: 'KeyW' }, { bindings: remapped })).toEqual(UNTOUCHED)
})
})
diff --git a/src/main/keydown-intercept.ts b/src/main/keydown-intercept.ts
index 315110ece..56b657d33 100644
--- a/src/main/keydown-intercept.ts
+++ b/src/main/keydown-intercept.ts
@@ -1,4 +1,6 @@
import { IPC } from '../shared/ipc'
+import { getEffectiveBindings, sanitizeKeybindingOverrides } from '../shared/keybindings'
+import { matchesShortcut } from '../shared/shortcut'
/**
* The main window's `before-input-event` decision as ONE pure function — the desktop half of the
@@ -18,10 +20,15 @@ import { IPC } from '../shared/ipc'
* **Why it is pure and lives here rather than in the callback.** Deleting a branch from an inline
* callback breaks nothing and throws nothing — the shortcut just quietly starts minimizing the
* window / closing it / resetting the WINDOW's page zoom instead of doing the app's thing. Worse,
- * the guard below is *shared* by three branches, so a change to it silently re-decides chords it
- * was not aimed at: loosen it and this window starts swallowing **bare** keystrokes app-wide, and
- * `index.ts` merges that kind of edit without a conflict. Both failures are invisible to a test
- * that reads the source; they are one assertion each against this function.
+ * a modifier test here is what keeps a branch off ordinary typing, so loosening one silently makes
+ * this window swallow **bare** keystrokes app-wide, and `index.ts` merges that kind of edit without
+ * a conflict. Both failures are invisible to a test that reads the source; they are one assertion
+ * each against this function.
+ *
+ * **This module stays the closed list of main-intercepted chords.** ⌘M and ⌘W are now resolved
+ * from the keybinding registry (`node.toggleMarkdown` / `node.close`), so the USER decides which
+ * chord they are — but nothing else is intercepted here, because everything else reaches the
+ * renderer's dispatcher on its own.
*
* Desktop-only by construction (it exists to fight a native menu), so it stays in `src/main` next
* to `main-window.ts` rather than moving to `src/core` — the Server Edition's browser shell has no
@@ -53,26 +60,88 @@ export interface KeydownInterceptDecision {
action: KeydownInterceptAction | null
}
+/** The effective chords for the two REMAPPABLE commands this module intercepts. `readonly
+ * string[]` in shortcut.ts's canonical spelling; `[]` means the user unbound the command, which
+ * must read as "do not claim the key" — Electron's own menu item comes back. */
+export interface KeydownInterceptBindings {
+ closeNode: readonly string[]
+ toggleMarkdown: readonly string[]
+}
+
+/**
+ * Effective M/W chords from raw settings overrides (sanitized here so a hand-edited settings.json
+ * cannot crash or hijack the intercept — this runs on the way to `before-input-event`, the one
+ * code path where a throw eats every keystroke in the window).
+ */
+export function resolveInterceptBindings(
+ rawOverrides: unknown,
+ isMac: boolean
+): KeydownInterceptBindings {
+ const { overrides } = sanitizeKeybindingOverrides(rawOverrides, isMac)
+ return {
+ closeNode: getEffectiveBindings('node.close', overrides, isMac),
+ toggleMarkdown: getEffectiveBindings('node.toggleMarkdown', overrides, isMac)
+ }
+}
+
+/** Electron's `Input` flags in the shape `matchesShortcut` reads. */
+function toShortcutEvent(input: KeydownInterceptInput): {
+ metaKey: boolean
+ ctrlKey: boolean
+ shiftKey: boolean
+ altKey: boolean
+ key: string
+} {
+ return {
+ metaKey: input.meta,
+ ctrlKey: input.control,
+ shiftKey: input.shift,
+ altKey: input.alt,
+ key: input.key
+ }
+}
+
/**
* PURE. What this `before-input-event` input means, or `null` to leave the key completely alone
* (no `preventDefault` — the page and, failing that, the menu get it).
*
- * The primary-modifier requirement is deliberately in the shared guard *and* is the only thing
- * standing between the branches below and ordinary typing: `m`, `w` and `0` are all characters a
- * user types. Any rewrite that moves the modifier decision into the individual branches has to
- * give **every** branch one — see `keydown-intercept.test.ts`, which presses each of them bare.
+ * **Every branch owns its own modifier requirement, and must.** The old shared guard was
+ * `type !== 'keyDown' || !(input.meta || input.control)`, which is exactly the check standing
+ * between these branches and ordinary typing — `m`, `w` and `0` are all characters a user types.
+ * It could not survive user-remappable bindings: `Alt+M` is a VALID binding per the registry's
+ * rules, and this module is its ONLY dispatcher (a chord we claim never reaches the renderer),
+ * so a primary-modifier gate above the matchers would make such a remap silently dead everywhere.
+ * So the two remappable chords are matched EXACTLY (all four modifier flags, `matchesShortcut`),
+ * which is a modifier requirement per binding, and the hardcoded `Digit0` branch below carries
+ * the `meta || control` test it used to inherit. `keydown-intercept.test.ts` presses each of them
+ * bare; keep it that way.
*/
-export function keydownIntercept(input: KeydownInterceptInput): KeydownInterceptDecision | null {
- if (input.type !== 'keyDown' || !(input.meta || input.control)) return null
- const key = input.key.toLowerCase()
- if (key === 'm') return { action: 'toggle-markdown' }
+export function keydownIntercept(
+ input: KeydownInterceptInput,
+ bindings: KeydownInterceptBindings,
+ isMac: boolean
+): KeydownInterceptDecision | null {
+ if (input.type !== 'keyDown') return null
+ // Matched against the user's effective bindings (defaults ⌘M / ⌘W). `matchesShortcut` is exact
+ // on meta/ctrl/alt/shift, so ⌘⇧M and ⌘⌥M — which the old `key === 'm'` branch also swallowed —
+ // are now different chords and go back to the page. Parsing is memoized in shortcut.ts, so this
+ // stays cheap on main's input path.
+ const ev = toShortcutEvent(input)
+ if (bindings.toggleMarkdown.some((s) => matchesShortcut(ev, s, isMac))) {
+ return { action: 'toggle-markdown' }
+ }
// Repurpose Cmd/Ctrl+W: the renderer closes the selected node(s); if none are selected it asks
- // us to close the window (the standard behavior). ⇧ is left to the menu's Close All Windows.
- if (key === 'w' && !input.shift) return { action: 'close-node' }
- // Matched on the physical `code`, like the renderer's half of the chord (`zoomShortcutChord`):
- // on a non-US layout the zero key's `key` is not necessarily "0". Alt is excluded because AltGr
- // reports as ctrl+alt and must keep typing a real character.
- if (input.code === 'Digit0' && !input.shift && !input.alt) {
+ // us to close the window (the standard behavior). ⇧ is left to the menu's Close All Windows —
+ // now by the binding being `Cmd+W` and the match being exact, rather than by a `!input.shift`.
+ if (bindings.closeNode.some((s) => matchesShortcut(ev, s, isMac))) {
+ return { action: 'close-node' }
+ }
+ // NOT remappable: this is the renderer's `zoomShortcutChord` half of a canvas gesture, not a
+ // registry command. Matched on the physical `code`, like that half: on a non-US layout the zero
+ // key's `key` is not necessarily "0". Alt is excluded because AltGr reports as ctrl+alt and must
+ // keep typing a real character; `meta || control` is the primary-modifier test it used to
+ // inherit from the shared guard, and without it every bare `0` in the app is swallowed (#193).
+ if (input.code === 'Digit0' && (input.meta || input.control) && !input.shift && !input.alt) {
// Auto-repeat is dropped here rather than in the renderer, so a held chord cannot restart the
// 200ms zoom tween — the same rule `zoomShortcutChord` applies to the keydown path. Still
// claimed, so a held ⌘0 does not fall through to `resetZoom` on the second repeat.
@@ -104,10 +173,18 @@ export interface KeydownInterceptTarget {
* Wire `keydownIntercept` to `win`. The whole side-effecting half is these four lines, so a test
* that calls this with a fake window exercises registration, the refusal, the `preventDefault` and
* the forwarded channel together — everything except the single call site in `index.ts`.
+ *
+ * `getBindings` is read per event rather than captured: settings change while the window lives, and
+ * it returns a cached object (`index.ts` recomputes it on `settingsStore.onChange`, not here — a
+ * sanitize per keystroke would be real work on the input path).
*/
-export function installKeydownIntercepts(win: KeydownInterceptTarget): void {
+export function installKeydownIntercepts(
+ win: KeydownInterceptTarget,
+ getBindings: () => KeydownInterceptBindings,
+ isMac: boolean
+): void {
win.webContents.on('before-input-event', (event, input) => {
- const decision = keydownIntercept(input)
+ const decision = keydownIntercept(input, getBindings(), isMac)
if (!decision) return
event.preventDefault()
if (decision.action) win.webContents.send(keydownInterceptChannel(decision.action))