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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(keybindings): policy-aware dispatch + capture noting
enesa59c36214137
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 779ba72e6..6b40e73d9 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -183,7 +183,8 @@ import {activeKeybindingOverrides,chipFor,commandTooltip,- dictationBinding+ dictationBinding,+ terminalShortcutPolicy} from '../lib/keybindingOverrides'import { UsageIndicator } from '../components/UsageIndicator'import { SystemResourcePill } from '../components/SystemResourcePill'@@ -5226,6 +5227,9 @@ export function Canvas() {kanbanOpen: () => isKanbanOpen(useProjects.getState().activeProjectId),overrides: activeKeybindingOverrides,isMac,+ // Read per keystroke (the deps object is rebuilt each render anyway, but the thunk is what+ // the contract asks for): a policy change takes effect immediately, with no re-registration.+ terminalFirst: () => terminalShortcutPolicy() === 'terminal-first',handlers: {'app.commandPalette': () => { setPaletteOpen((v) => !v); return true },'app.settings': () => { setSettingsSection(undefined); setSettingsOpen(true); return true },diff --git a/src/renderer/lib/globalKeybindings.test.ts b/src/renderer/lib/globalKeybindings.test.tsindex bcf79b64e..3079e50d3 100644--- a/src/renderer/lib/globalKeybindings.test.ts+++ b/src/renderer/lib/globalKeybindings.test.ts@@ -1,6 +1,7 @@import { describe, it, expect, vi } from 'vitest'+import type { CommandId } from '@shared/keybindings'import { dispatchGlobalKeydown, type GlobalKeydownDeps, type GlobalKeyEvent } from './globalKeybindings'-import { XTERM_INPUT_CLASS } from './keyContext'+import { XTERM_INPUT_CLASS, type ContextElement } from './keyContext'const ev = (over: Partial<GlobalKeyEvent>): GlobalKeyEvent => ({metaKey: false, ctrlKey: false, shiftKey: false, altKey: false, key: '',@@ -9,13 +10,22 @@ const ev = (over: Partial<GlobalKeyEvent>): GlobalKeyEvent => ({...over})const noGesture = () => false+const noGestures = {+ keyedDictation: noGesture, zoom: noGesture, projectJump: noGesture, copy: noGesture+}+/** xterm's hidden helper textarea — what `activeElement` reports whenever a terminal owns+ * the keyboard, i.e. the only element shape that makes `ctx.terminal` true. */+const xtermEl = (): ContextElement => ({+ tagName: 'TEXTAREA', classList: { contains: (n: string) => n === XTERM_INPUT_CLASS }+})const deps = (over: Partial<GlobalKeydownDeps> = {}): GlobalKeydownDeps => ({activeElement: () => null,kanbanOpen: () => false,overrides: () => ({}),isMac: true,+ terminalFirst: () => false,handlers: {},- gestures: { keyedDictation: noGesture, zoom: noGesture, projectJump: noGesture, copy: noGesture },+ gestures: { ...noGestures },...over})@@ -51,10 +61,7 @@ describe('dispatchGlobalKeydown', () => {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 } })- })+ const terminal = deps({ gestures: g, activeElement: xtermEl })dispatchGlobalKeydown(ev({ metaKey: true, key: 't' }), terminal)expect(dictation).toHaveBeenCalledTimes(1)})@@ -134,4 +141,55 @@ describe('dispatchGlobalKeydown', () => {expect(dispatchGlobalKeydown(ev({ metaKey: true, key: 'k' }), d)).toBe(true)expect(fit).toHaveBeenCalled()})+ it('terminal-first: trailing gestures are not offered while a terminal has focus', () => {+ // The registry half of terminal-first lives in the resolver; the gestures never went+ // through it, so without this gate Cmd+0 would still zoom the canvas out from under a+ // user who reserved every chord for the shell.+ const zoom = vi.fn(() => true)+ const d = deps({+ terminalFirst: () => true,+ activeElement: xtermEl,+ gestures: { ...noGestures, zoom }+ })+ expect(dispatchGlobalKeydown(ev({ metaKey: true, key: '0' }), d)).toBe(false)+ expect(zoom).not.toHaveBeenCalled()+ })+ it('app-first: a terminal-context claim reports a capture exactly at claim time', () => {+ const captured: string[] = []+ const d = deps({+ activeElement: xtermEl,+ handlers: { 'app.commandPalette': () => true },+ onTerminalCapture: (id) => captured.push(id)+ })+ dispatchGlobalKeydown(ev({ metaKey: true, key: 'k' }), d)+ expect(captured).toEqual(['app.commandPalette'])+ })+ it('no capture report outside terminal focus, on decline, or under terminal-first', () => {+ const captured: string[] = []+ const base = { onTerminalCapture: (id: CommandId) => captured.push(id) }+ // Plain app focus: nothing was taken from a terminal.+ dispatchGlobalKeydown(ev({ metaKey: true, key: 'k' }),+ deps({ ...base, handlers: { 'app.commandPalette': () => true } }))+ // Declined: the chord fell through to the PTY, so nothing was captured.+ dispatchGlobalKeydown(ev({ metaKey: true, key: 'k' }),+ deps({ ...base, activeElement: xtermEl, handlers: { 'app.commandPalette': () => false } }))+ // A TERMINAL-scope claim under terminal-first is the terminal's own key — legitimate+ // ownership, not a capture.+ dispatchGlobalKeydown(ev({ metaKey: true, key: 'f' }),+ deps({ ...base, activeElement: xtermEl, terminalFirst: () => true,+ handlers: { 'terminal.find': () => true } }))+ expect(captured).toEqual([])+ })+ it('a terminal-scope claim under APP-first is ownership too, not a capture', () => {+ // The scope check is the load-bearing half: gating only on `!terminalFirst` would report+ // Cmd+F ("Find in terminal") as a chord app-first stole from the terminal.+ const captured: string[] = []+ const d = deps({+ activeElement: xtermEl,+ handlers: { 'terminal.find': () => true },+ onTerminalCapture: (id: CommandId) => captured.push(id)+ })+ expect(dispatchGlobalKeydown(ev({ metaKey: true, key: 'f' }), d)).toBe(true)+ expect(captured).toEqual([])+ })})diff --git a/src/renderer/lib/globalKeybindings.ts b/src/renderer/lib/globalKeybindings.tsindex 45807749d..cfa87bf41 100644--- a/src/renderer/lib/globalKeybindings.ts+++ b/src/renderer/lib/globalKeybindings.ts@@ -26,8 +26,17 @@* registry and is offered to zoom → projectJump → copy. Those gestures receive the RAW event* with no context, so **each trailing gesture closure owes its own focus/typing guard**; keyed* dictation is the only gesture this module guards.+ *+ * 3. **The terminal-shortcut policy is applied in TWO places, because the gestures bypass the+ * resolver.** `resolveCommandForKeyEvent` honors `ctx.terminalFirst` for registry commands;+ * the trailing gestures never go through it, so this module gates them separately. A future+ * gesture appended to that chain inherits the gate for free — one added ABOVE the registry+ * (as keyed dictation is) does not, and owes its own.*/-import { resolveCommandForKeyEvent, type CommandId, type KeybindingOverrides } from '@shared/keybindings'+import {+ resolveCommandForKeyEvent, COMMANDS_BY_ID,+ 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). */@@ -49,7 +58,15 @@ export interface GlobalKeydownDeps {kanbanOpen: () => booleanoverrides: () => KeybindingOverridesisMac: boolean+ /** The user's `terminalShortcutPolicy`, read live: true = 'terminal-first'. A thunk, not a+ * value, so a policy change takes effect on the next keystroke without re-registering the+ * window listener. */+ terminalFirst: () => booleanhandlers: CommandHandlers+ /** Called when a registry handler CLAIMS a chord that a focused terminal would otherwise+ * have received — i.e. app-first took it. Terminal-scope claims and terminal-first are not+ * captures (see the call site). Optional: a caller that shows no notice omits it. */+ onTerminalCapture?: (id: CommandId) => void/** 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@@ -65,8 +82,7 @@ export interface GlobalKeydownDeps {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- // Task 2 threads the real policy (a deps thunk); app-first until then, which is today's behavior.- const ctx = keyDispatchContextFor(deps.activeElement(), deps.kanbanOpen(), false)+ const ctx = keyDispatchContextFor(deps.activeElement(), deps.kanbanOpen(), deps.terminalFirst())// 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@@ -75,12 +91,28 @@ export function dispatchGlobalKeydown(e: GlobalKeyEvent, deps: GlobalKeydownDepsconst handler = deps.handlers[id]if (handler && handler()) {e.preventDefault()+ // App-first just took this chord from a focused terminal: the once-per-command notice.+ // The scope check is the load-bearing one — a terminal-scope claim (find, copy) is the+ // terminal's OWN key, not a capture, and gating on the policy alone would report ⌘F as+ // stolen. `!ctx.terminalFirst` is deliberate redundancy: the RESOLVER already refuses+ // every non-terminal-scope command under terminal-first, so no test can distinguish it+ // today (measured — removing it leaves the suite green). It STATES the condition here so+ // the notice stays honest if that resolver rule is ever loosened, the same way the+ // resolver's own isHoldChord skip states a contract it does not currently need.+ if (ctx.terminal && !ctx.terminalFirst && COMMANDS_BY_ID.get(id)?.scope !== 'terminal') {+ deps.onTerminalCapture?.(id)+ }return true}// Resolved but unhandled/declined: fall through to the platform, never to a gesture that// could reinterpret the same chord.return false}+ // terminal-first: the trailing gestures are APP gestures (zoom, project jump, copy) and the+ // resolver never saw them, so the policy has to be applied here too — otherwise Cmd+0 still+ // zooms out from under a user who reserved every chord for the shell. Each gesture keeps its+ // own guards for the app-first case; this is an additional gate, not a replacement.+ if (ctx.terminal && ctx.terminalFirst) return falseif (deps.gestures.zoom(e)) return trueif (deps.gestures.projectJump(e)) return trueif (deps.gestures.copy(e)) return truediff --git a/src/renderer/lib/keybindingOverrides.test.ts b/src/renderer/lib/keybindingOverrides.test.tsindex d4b6393f3..c2ea47fea 100644--- a/src/renderer/lib/keybindingOverrides.test.ts+++ b/src/renderer/lib/keybindingOverrides.test.ts@@ -4,7 +4,8 @@ import { matchesShortcut, type ShortcutKeyEvent } from '@shared/shortcut'import { useSettings } from '../state/settings'import {activeKeybindingOverrides, effectiveBindings, commandKeys, commandTooltip, chipFor,- setKeybindingOverride, commandKeysFor, dictationBinding+ setKeybindingOverride, commandKeysFor, dictationBinding,+ terminalShortcutPolicy, noteTerminalCapture} from './keybindingOverrides'const setKb = (kb: unknown) =>@@ -126,6 +127,59 @@ describe('setKeybindingOverride', () => {})})+// NODE ENV, deliberately: this file runs without jsdom (see the note on noteTerminalCapture),+// so only the SETTINGS side is asserted here. The 'nodeterm:shortcut-captured' event is+// window-guarded and its dispatch is covered by the banner's jsdom test.+describe('terminalShortcutPolicy / noteTerminalCapture', () => {+ const seen = () => useSettings.getState().settings.seenShortcutCaptureNotices+ const setSettings = (patch: Record<string, unknown>) =>+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS, ...patch } as never })++ it('normalizes the setting', () => {+ expect(terminalShortcutPolicy()).toBe('app-first')+ setSettings({ terminalShortcutPolicy: 'terminal-first' })+ expect(terminalShortcutPolicy()).toBe('terminal-first')+ })+ it('a hand-edited garbage policy reads as app-first, not as the raw value', () => {+ // settings.json is hand-editable, so the compile-time type is not a runtime guarantee —+ // and the unknown value must degrade to today's behavior, never to terminal-first.+ setSettings({ terminalShortcutPolicy: 'shell-first' })+ expect(terminalShortcutPolicy()).toBe('app-first')+ })+ it('notes a capture once, persists the id, and is silent under terminal-first', () => {+ noteTerminalCapture('app.commandPalette')+ noteTerminalCapture('app.commandPalette')+ expect(seen()).toEqual(['app.commandPalette'])+ setSettings({+ terminalShortcutPolicy: 'terminal-first',+ seenShortcutCaptureNotices: ['app.commandPalette']+ })+ noteTerminalCapture('canvas.undo')+ expect(seen()).toEqual(['app.commandPalette'])+ })+ it('appends to the ids already seen rather than replacing them', () => {+ setSettings({ seenShortcutCaptureNotices: ['app.settings'] })+ noteTerminalCapture('app.commandPalette')+ expect(seen()).toEqual(['app.settings', 'app.commandPalette'])+ })+ it('a hand-edited seenShortcutCaptureNotices of the wrong shape reads as empty', () => {+ // `.includes` on a string would answer TRUE for any substring of it, silently swallowing+ // the first notice; on a non-array it would throw inside a keydown handler.+ setSettings({ seenShortcutCaptureNotices: 'garbage' })+ noteTerminalCapture('app.commandPalette')+ expect(seen()).toEqual(['app.commandPalette'])+ })+ it('drops non-string entries from a hand-edited list instead of carrying them forward', () => {+ setSettings({ seenShortcutCaptureNotices: ['app.settings', 7, null] })+ noteTerminalCapture('app.commandPalette')+ expect(seen()).toEqual(['app.settings', 'app.commandPalette'])+ })+ it('does not throw with no window (the guard node-env dispatch depends on)', () => {+ expect(typeof window).toBe('undefined')+ expect(() => noteTerminalCapture('app.commandPalette')).not.toThrow()+ })+})+describe('commandKeysFor / dictationBinding', () => {it('lists every effective binding', () => {expect(commandKeysFor('canvas.deleteSelection', true)).toEqual([['Delete'], ['Backspace']])diff --git a/src/renderer/lib/keybindingOverrides.ts b/src/renderer/lib/keybindingOverrides.tsindex a9c7c477f..abc6ca3cc 100644--- a/src/renderer/lib/keybindingOverrides.ts+++ b/src/renderer/lib/keybindingOverrides.ts@@ -6,8 +6,8 @@* ShortcutsPanel, and tooltips cannot disagree.*/import {- getEffectiveBindings, sanitizeKeybindingOverrides,- type CommandId, type KeybindingOverrides+ getEffectiveBindings, sanitizeKeybindingOverrides, normalizeTerminalShortcutPolicy,+ type CommandId, type KeybindingOverrides, type TerminalShortcutPolicy} from '@shared/keybindings'import { shortcutKeyParts } from '@shared/shortcut'import { isMacPlatform } from '@shared/platform-utils'@@ -99,3 +99,34 @@ export function commandKeysFor(id: CommandId, isMac: boolean = isMacPlatform()):export function dictationBinding(): string {return effectiveBindings('speech.dictation')[0] ?? ''}++/** Who wins while an xterm has focus. Read through the normalizer, NOT as the raw field: the+ * setting is hand-editable JSON, so its compile-time type is not a runtime guarantee, and an+ * unknown value must degrade to `app-first` (today's behavior) rather than reach dispatch. */+export function terminalShortcutPolicy(): TerminalShortcutPolicy {+ return normalizeTerminalShortcutPolicy(useSettings.getState().settings.terminalShortcutPolicy)+}++/** Once per command, ever (persisted in settings so Server Edition shares it): record that+ * app-first captured this command's chord from a focused terminal, and tell the banner.+ * Silent under terminal-first — nothing is being taken from the terminal there.+ *+ * `seenShortcutCaptureNotices` is hand-editable too, so its SHAPE is guarded before use: a+ * string would make `.includes` answer true for any substring (swallowing the first notice),+ * and a number/object would throw inside a keydown handler. Anything that is not an array of+ * strings is treated as empty and REPLACED by a clean array on the next write.+ *+ * The event is window-guarded because this module is imported by node-environment unit+ * tests (the same guard `state/settings.ts` carries for its save timer); the settings write+ * is the durable half and happens either way. */+export function noteTerminalCapture(id: CommandId): void {+ if (terminalShortcutPolicy() !== 'app-first') return+ const state = useSettings.getState()+ const raw = state.settings.seenShortcutCaptureNotices+ const seen = Array.isArray(raw) ? raw.filter((x): x is string => typeof x === 'string') : []+ if (seen.includes(id)) return+ state.update({ seenShortcutCaptureNotices: [...seen, id] })+ if (typeof window !== 'undefined') {+ window.dispatchEvent(new CustomEvent('nodeterm:shortcut-captured', { detail: { commandId: id } }))+ }+}