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(keybindings): pure global keydown dispatcher

enes6b7d480011b5
diff --git a/src/renderer/lib/globalKeybindings.test.ts b/src/renderer/lib/globalKeybindings.test.ts
new file mode 100644
index 000000000..957ca446f
--- /dev/null
+++ b/src/renderer/lib/globalKeybindings.test.ts
@@ -0,0 +1,115 @@
+import { describe, it, expect, vi } from 'vitest'
+import { dispatchGlobalKeydown, type GlobalKeydownDeps, type GlobalKeyEvent } from './globalKeybindings'
+import { XTERM_INPUT_CLASS } from './keyContext'
+
+const ev = (over: Partial<GlobalKeyEvent>): GlobalKeyEvent => ({
+ metaKey: false, ctrlKey: false, shiftKey: false, altKey: false, key: '',
+ defaultPrevented: false,
+ preventDefault() { this.defaultPrevented = true },
+ ...over
+})
+const noGesture = () => false
+const deps = (over: Partial<GlobalKeydownDeps> = {}): GlobalKeydownDeps => ({
+ activeElement: () => null,
+ kanbanOpen: () => false,
+ overrides: () => ({}),
+ isMac: true,
+ handlers: {},
+ gestures: { keyedDictation: noGesture, zoom: noGesture, projectJump: noGesture, copy: noGesture },
+ ...over
+})
+
+describe('dispatchGlobalKeydown', () => {
+ it('bails on defaultPrevented without touching anything', () => {
+ const dictation = vi.fn()
+ const d = deps({ gestures: { keyedDictation: dictation, zoom: noGesture, projectJump: noGesture, copy: noGesture } })
+ expect(dispatchGlobalKeydown(ev({ metaKey: true, key: 'k', defaultPrevented: true }), d)).toBe(false)
+ expect(dictation).not.toHaveBeenCalled()
+ })
+ it('runs a claimed registry handler and preventDefaults', () => {
+ const e = ev({ metaKey: true, key: 'k' })
+ const palette = vi.fn(() => true)
+ expect(dispatchGlobalKeydown(e, deps({ handlers: { 'app.commandPalette': palette } }))).toBe(true)
+ expect(e.defaultPrevented).toBe(true)
+ })
+ it('a declining handler leaves the key alone (falls through to the platform)', () => {
+ const e = ev({ metaKey: true, key: 'k' })
+ expect(dispatchGlobalKeydown(e, deps({ handlers: { 'app.commandPalette': () => false } }))).toBe(false)
+ expect(e.defaultPrevented).toBe(false)
+ })
+ it('a resolved command with no registered handler is not claimed', () => {
+ const e = ev({ metaKey: true, key: 'w' }) // node.close: main-intercepted on desktop, browser-owned in SE
+ expect(dispatchGlobalKeydown(e, deps())).toBe(false)
+ expect(e.defaultPrevented).toBe(false)
+ })
+ it('keyed dictation wins over a colliding registry default, but not while typing or in terminal', () => {
+ const dictation = vi.fn((e: GlobalKeyEvent) => { e.preventDefault(); return true })
+ const term = vi.fn(() => true)
+ const g = { keyedDictation: dictation, zoom: noGesture, projectJump: noGesture, copy: noGesture }
+ const d = deps({ gestures: g, handlers: { 'node.newTerminal': term } })
+ expect(dispatchGlobalKeydown(ev({ metaKey: true, key: 't' }), d)).toBe(true)
+ expect(term).not.toHaveBeenCalled()
+ const typing = deps({ gestures: g, activeElement: () => ({ tagName: 'INPUT' }) })
+ expect(dispatchGlobalKeydown(ev({ metaKey: true, key: 't' }), typing)).toBe(false)
+ const terminal = deps({
+ gestures: g,
+ activeElement: () => ({ tagName: 'TEXTAREA', classList: { contains: (n: string) => n === XTERM_INPUT_CLASS } })
+ })
+ dispatchGlobalKeydown(ev({ metaKey: true, key: 't' }), terminal)
+ expect(dictation).toHaveBeenCalledTimes(1)
+ })
+ it('typing blocks canvas AND app commands (the announced D-typing guard fix)', () => {
+ const palette = vi.fn(() => true)
+ const undo = vi.fn(() => true)
+ const typing = deps({
+ activeElement: () => ({ tagName: 'DIV', isContentEditable: true }),
+ handlers: { 'app.commandPalette': palette, 'canvas.undo': undo }
+ })
+ expect(dispatchGlobalKeydown(ev({ metaKey: true, key: 'z' }), typing)).toBe(false)
+ expect(undo).not.toHaveBeenCalled()
+ expect(dispatchGlobalKeydown(ev({ metaKey: true, key: 'k' }), typing)).toBe(false)
+ expect(palette).not.toHaveBeenCalled()
+ // NOTE: app-scope commands lack allowWhileTyping in the registry, so typing blocks them
+ // too — that IS the announced D-typing delta (today Cmd+K fires while renaming a node).
+ })
+ it('kanban keeps app commands live and canvas commands inert', () => {
+ const toggle = vi.fn(() => true)
+ const undo = vi.fn(() => true)
+ const d = deps({ kanbanOpen: () => true, handlers: { 'view.kanbanToggle': toggle, 'canvas.undo': undo } })
+ expect(dispatchGlobalKeydown(ev({ metaKey: true, shiftKey: true, key: 'b' }), d)).toBe(true)
+ expect(dispatchGlobalKeydown(ev({ metaKey: true, key: 'z' }), d)).toBe(false)
+ expect(undo).not.toHaveBeenCalled()
+ })
+ // The claim protocol's second half: a RESOLVED chord is spent, whoever declined it. The two
+ // tests above only prove it is not claimed — with claiming gestures wired in, a fall-through
+ // into them would reinterpret the same chord as a zoom/jump/copy.
+ it('a resolved command never reaches a gesture, declined or unhandled', () => {
+ const claimAll = vi.fn(() => true)
+ const g = { keyedDictation: noGesture, zoom: claimAll, projectJump: claimAll, copy: claimAll }
+ const declined = ev({ metaKey: true, key: 'k' })
+ expect(dispatchGlobalKeydown(declined, deps({ gestures: g, handlers: { 'app.commandPalette': () => false } }))).toBe(false)
+ const unhandled = ev({ metaKey: true, key: 'w' })
+ expect(dispatchGlobalKeydown(unhandled, deps({ gestures: g }))).toBe(false)
+ expect(claimAll).not.toHaveBeenCalled()
+ })
+ it('gestures run after a registry miss, in zoom → projectJump → copy order', () => {
+ const order: string[] = []
+ const g = {
+ keyedDictation: noGesture,
+ zoom: () => { order.push('zoom'); return false },
+ projectJump: () => { order.push('jump'); return false },
+ copy: () => { order.push('copy'); return false }
+ }
+ expect(dispatchGlobalKeydown(ev({ key: '!' , shiftKey: true }), deps({ gestures: g }))).toBe(false)
+ expect(order).toEqual(['zoom', 'jump', 'copy'])
+ })
+ it('overrides reroute dispatch', () => {
+ const fit = vi.fn(() => true)
+ const d = deps({
+ overrides: () => ({ 'app.commandPalette': [], 'canvas.fitAll': ['Cmd+K'] }),
+ handlers: { 'canvas.fitAll': fit }
+ })
+ expect(dispatchGlobalKeydown(ev({ metaKey: true, key: 'k' }), d)).toBe(true)
+ expect(fit).toHaveBeenCalled()
+ })
+})
diff --git a/src/renderer/lib/globalKeybindings.ts b/src/renderer/lib/globalKeybindings.ts
new file mode 100644
index 000000000..fb5531c10
--- /dev/null
+++ b/src/renderer/lib/globalKeybindings.ts
@@ -0,0 +1,78 @@
+/**
+ * The single window-keydown dispatcher for registry commands plus the registry-less gestures
+ * Canvas carries (keyed dictation, Cmd+0 / Shift+1 zoom, Cmd+1-9 project jump, Cmd+C copy). One
+ * pass, documented order; an unclaimed chord falls through to the focused surface / PTY — never to
+ * another command. Pure so node-env tests can drive it without a DOM; Canvas supplies the live
+ * accessors and handler closures.
+ *
+ * Two contracts this module exists to state, both load-bearing:
+ *
+ * 1. **Gesture order.** Keyed dictation runs BEFORE the registry (a custom keyed chord may
+ * deliberately collide with a registry default and must keep winning — it predates the
+ * registry), and zoom → projectJump → copy run AFTER a registry miss, in that exact order.
+ * This mirrors today's if-chain in Canvas, so consolidating the listeners changes no outcome.
+ *
+ * 2. **Claim protocol.** `preventDefault()` is called ONLY when a handler actually claims the key
+ * (returns true). A command that resolved but whose handler declined — or that has no handler
+ * registered at all — falls through to the PLATFORM (the focused surface, the terminal, the
+ * browser/main-process accelerator), and NEVER to a gesture that could reinterpret the same
+ * chord as something else.
+ */
+import { resolveCommandForKeyEvent, type CommandId, type KeybindingOverrides } from '@shared/keybindings'
+import { keyDispatchContextFor, type ContextElement } from './keyContext'
+
+/** Structural key event so node-env tests need no DOM (a real KeyboardEvent satisfies it). */
+export interface GlobalKeyEvent {
+ metaKey: boolean
+ ctrlKey: boolean
+ shiftKey: boolean
+ altKey: boolean
+ key: string
+ defaultPrevented: boolean
+ preventDefault(): void
+}
+
+/** A handler returns true when it CLAIMED the key; false leaves the chord to the platform. */
+export type CommandHandlers = Partial<Record<CommandId, () => boolean>>
+
+export interface GlobalKeydownDeps {
+ activeElement: () => ContextElement | null
+ kanbanOpen: () => boolean
+ overrides: () => KeybindingOverrides
+ isMac: boolean
+ handlers: CommandHandlers
+ /** Registry-less chords, tried in this exact order (matches today's if-chain order):
+ * keyed dictation BEFORE the registry (a custom keyed chord may collide with a default
+ * and must keep winning), zoom/projectJump/copy AFTER a registry miss. Each returns true
+ * when it claimed the key (and did its own preventDefault where it needs one). */
+ gestures: {
+ keyedDictation: (e: GlobalKeyEvent) => boolean
+ zoom: (e: GlobalKeyEvent) => boolean
+ projectJump: (e: GlobalKeyEvent) => boolean
+ copy: (e: GlobalKeyEvent) => boolean
+ }
+}
+
+export function dispatchGlobalKeydown(e: GlobalKeyEvent, deps: GlobalKeydownDeps): boolean {
+ // A child handler (find bar, dialogs, terminal) that already claimed the key wins outright.
+ if (e.defaultPrevented) return false
+ const ctx = keyDispatchContextFor(deps.activeElement(), deps.kanbanOpen())
+ // Keyed dictation predates the registry and may deliberately collide with a default; it
+ // keeps first claim, but only in plain app focus (its old guard blocked inputs AND xterm).
+ if (!ctx.typing && !ctx.terminal && !ctx.kanbanOpen && deps.gestures.keyedDictation(e)) return true
+ const id = resolveCommandForKeyEvent(e, ctx, deps.overrides(), deps.isMac)
+ if (id) {
+ const handler = deps.handlers[id]
+ if (handler && handler()) {
+ e.preventDefault()
+ return true
+ }
+ // Resolved but unhandled/declined: fall through to the platform, never to a gesture that
+ // could reinterpret the same chord.
+ return false
+ }
+ if (deps.gestures.zoom(e)) return true
+ if (deps.gestures.projectJump(e)) return true
+ if (deps.gestures.copy(e)) return true
+ return false
+}