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(main): suspend keydown interception while a shortcut recorder is armed
enes581ca6e26603
diff --git a/src/main/index.ts b/src/main/index.tsindex ad45c533b..ee3e87938 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -292,6 +292,18 @@ const currentInterceptBindings = (): KeydownInterceptBindings =>settingsStore.onChange((s) => {interceptBindings = resolveInterceptBindings(s.keybindings, interceptIsMac)})+// Settings' shortcut recorder is armed: stand every intercept down so the chord the user presses+// reaches the recorder. Without it, recording ⌘W CLOSES THE SELECTED NODES — a claimed chord never+// reaches the page, so the recorder's own preventDefault cannot save it.+// A module-level `let` read through a closure, exactly like `interceptBindings` above: the window+// is created later and can be recreated (macOS dock reopen), so nothing may capture a value.+// FAIL-SAFE DIRECTION: every uncertainty resolves to `false` (intercepts on). A renderer that+// crashes or a window that closes while armed clears it — see `createWindow` — because the+// alternative is ⌘W/⌘M/⌘0 dead app-wide with no component left alive to release the bit.+let shortcutRecording = false+const clearShortcutRecording = (): void => {+ shortcutRecording = false+}const sshStore = new SshStore()const ptyManager = new PtyManager()// Dictation: local whisper.cpp models live under userData, one dir per install (same convention@@ -622,6 +634,11 @@ function createWindow(): BrowserWindow {// client to co-attach to that node would inherit a frozen terminal. The tmux sessions// themselves keep running, exactly as they do on quit (killAll).ptyManager.dropClient(presenceId)+ // The window that armed the recorder is gone, so nothing can ever disarm it. Leaving the bit+ // set would suppress ⌘W/⌘M/⌘0 for the NEXT window too (the flag outlives the window; a dock+ // reopen builds a fresh one). Same shape as the dropClient above: state this window owned,+ // released where its departure is observed.+ clearShortcutRecording()})// A crashed/killed renderer is the same story, minus the window: drop its subscriptions so the// reloaded renderer reattaches to live sessions instead of inheriting the dead one's state.@@ -632,6 +649,9 @@ function createWindow(): BrowserWindow {const crashReload = createCrashReloadPolicy()win.webContents.on('render-process-gone', (_event, details) => {ptyManager.dropClient(presenceId)+ // A dead renderer sends no disarm. The reloaded page mounts no recorder, so without this the+ // user would come back to an app where ⌘W does nothing at all.+ clearShortcutRecording()if (quitting || win.isDestroyed()) returnconst action = crashReload(details.reason, Date.now())if (action === 'reload') {@@ -686,7 +706,7 @@ function createWindow(): BrowserWindow {// 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. The first two// are the user's effective `node.toggleMarkdown` / `node.close` bindings (⌘0 is not remappable).- installKeydownIntercepts(win, currentInterceptBindings, interceptIsMac)+ installKeydownIntercepts(win, currentInterceptBindings, interceptIsMac, () => shortcutRecording)// Open external links in the system browser — only safe schemes (no file://, no custom// protocol handlers). Reachable from remotely-fetched announcement URLs and rendered@@ -912,6 +932,16 @@ app.whenReady().then(async () => {ipcMain.on(IPC.appCloseWindow, () => BrowserWindow.getFocusedWindow()?.close())+ // Settings' shortcut recorder arming/disarming. Guarded on the sender being the live main window+ // (the same `getMainWindow()?.webContents.id !== event.sender.id` test `registerElectronGitHubControl`+ // uses): a <webview> guest — a browser node showing an arbitrary page — is a webContents in this+ // process too, and this bit disables the app's own keyboard shortcuts. Resolved at call time, not+ // captured, because the window can be closed and recreated on macOS.+ ipcMain.on(IPC.uiShortcutRecording, (event, active: boolean) => {+ if (getMainWindow()?.webContents.id !== event.sender.id) return+ shortcutRecording = active === true+ })+// Bring the window forward after a file is dropped into a terminal. On macOS a drag-drop from// another app does NOT activate the destination app, so without this the drag-source keeps OS// keyboard focus and the user types into the wrong application. `getMainWindow()` (not thediff --git a/src/main/keydown-intercept.test.ts b/src/main/keydown-intercept.test.tsindex 18ebed969..24501bfa1 100644--- a/src/main/keydown-intercept.test.ts+++ b/src/main/keydown-intercept.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest'import { IPC } from '../shared/ipc'+import { MAIN_INTERCEPTED_COMMAND_IDS } from '../shared/keybindings'import {installKeydownIntercepts,keydownIntercept,@@ -57,10 +58,28 @@ function press(): { prevented: boolean; sent: string[] } {const isMac = opts.isMac ?? trueconst bindings = opts.bindings ?? (isMac ? DEFAULTS : DEFAULTS_PC)+ // Not recording: the ordinary state of the app, and the baseline every case below asserts+ // against. The armed state has its own describe block at the bottom of this file.+ const seam = install(() => bindings, isMac, () => false)+ seam.fire(over)+ return { prevented: seam.prevented.length > 0, sent: seam.sent }+}++/**+ * ONE installation whose listener can be fired repeatedly — the shape a live window has, and the+ * only way to press the same key on both sides of a state change (the recording bit flipping under+ * a running window is exactly what `press`, which installs per call, cannot show).+ */+function install(+ getBindings: () => KeydownInterceptBindings,+ isMac: boolean,+ isRecording: () => boolean+): { fire: (over?: Partial<KeydownInterceptInput>) => void; prevented: string[]; sent: string[] } {let handler:| ((event: { preventDefault(): void }, input: KeydownInterceptInput) => void)| null = nullconst sent: string[] = []+ const prevented: string[] = []const win: KeydownInterceptTarget = {webContents: {on: (_event, listener) => {@@ -71,14 +90,16 @@ function press(}}}- installKeydownIntercepts(win, () => bindings, isMac)+ installKeydownIntercepts(win, getBindings, isMac, isRecording)if (!handler) throw new Error('installKeydownIntercepts registered no before-input-event listener')- let prevented = false- ;(handler as (e: { preventDefault(): void }, i: KeydownInterceptInput) => void)(- { preventDefault: () => (prevented = true) },- input(over)- )- return { prevented, sent }+ const fire = (over: Partial<KeydownInterceptInput> = {}): void => {+ const i = input(over)+ ;(handler as (e: { preventDefault(): void }, i: KeydownInterceptInput) => void)(+ { preventDefault: () => prevented.push(i.code) },+ i+ )+ }+ return { fire, prevented, sent }}/** Nothing happened at all: the page gets the key, and so does the menu if the page ignores it. */@@ -300,4 +321,52 @@ describe('binding-driven intercept', () => {)expect(press({ meta: true, key: 'w', code: 'KeyW' }, { bindings: remapped })).toEqual(UNTOUCHED)})++ // LIST DRIFT. `MAIN_INTERCEPTED_COMMAND_IDS` is what the Settings UI checks a candidate binding+ // against for the app-wide shadow warning (`findMainInterceptShadowing`), and nothing else ties+ // it to the commands THIS module actually resolves. A third intercept added here without the id+ // added there would be swallowed app-wide with the recorder cheerfully reporting no conflict.+ it('MAIN_INTERCEPTED_COMMAND_IDS is exactly the set this module resolves', () => {+ expect(Object.keys(DEFAULTS)).toHaveLength(MAIN_INTERCEPTED_COMMAND_IDS.length)+ // Unbinding a listed command must visibly change what this module resolves — i.e. it is read+ // here, not merely claimed.+ for (const id of MAIN_INTERCEPTED_COMMAND_IDS) {+ expect(resolveInterceptBindings({ [id]: [] }, true), id).not.toEqual(DEFAULTS)+ }+ })+})++/**+ * THE bug this suppression exists to close: the Settings shortcut recorder asks the user to PRESS+ * the chord they want to bind, and pressing ⌘W there used to reach `app:close-node` — deleting the+ * selected nodes instead of recording a keystroke. A claimed chord never reaches the page at all,+ * so the recorder's own `preventDefault`/`stopPropagation` cannot help: main has to stand down.+ */+describe('an armed shortcut recorder suspends every interception', () => {+ it('suppresses while armed and resumes on disarm', () => {+ let recording = true+ const seam = install(() => DEFAULTS, true, () => recording)+ seam.fire({ meta: true, key: 'w', code: 'KeyW' })+ seam.fire({ meta: true, key: 'm', code: 'KeyM' })+ seam.fire({ meta: true, code: 'Digit0' })+ // Not swallowed either: `preventDefault` would take the key from the recorder as well as the+ // menu, so the suppression must return BEFORE it, not merely skip the send.+ expect(seam.prevented).toEqual([])+ expect(seam.sent).toEqual([])+ recording = false+ seam.fire({ meta: true, key: 'w', code: 'KeyW' })+ expect(seam.sent).toEqual([IPC.appCloseNode])+ expect(seam.prevented).toEqual(['KeyW'])+ })++ it('is read per event, not captured at install time', () => {+ // The bit lives in a module-level `let` in index.ts that the renderer flips over IPC long+ // after the window was created; a captured boolean would make the whole feature inert.+ let recording = false+ const seam = install(() => DEFAULTS, true, () => recording)+ seam.fire({ meta: true, key: 'w', code: 'KeyW' })+ recording = true+ seam.fire({ meta: true, key: 'w', code: 'KeyW' })+ expect(seam.sent).toEqual([IPC.appCloseNode])+ })})diff --git a/src/main/keydown-intercept.ts b/src/main/keydown-intercept.tsindex 787b584c8..5c49d444f 100644--- a/src/main/keydown-intercept.ts+++ b/src/main/keydown-intercept.ts@@ -28,7 +28,10 @@ import { matchesShortcut } from '../shared/shortcut'* **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.+ * renderer's dispatcher on its own. That closed list is ALSO written down in+ * `shared/keybindings.ts` as `MAIN_INTERCEPTED_COMMAND_IDS` (the Settings UI's app-wide shadow+ * warning reads it, and cannot derive it from here — main is not importable from the renderer);+ * a third intercept added here owes that list an entry, which `keydown-intercept.test.ts` pins.** 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@@ -181,13 +184,22 @@ export interface KeydownInterceptTarget {* `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).+ *+ * `isRecording` is the same shape and for the same reason — the renderer flips it over IPC while+ * this window is alive. **It is checked BEFORE `preventDefault`, not before the send**: a claimed+ * chord never reaches the page at all, so while the Settings shortcut recorder is armed the only+ * way it can SEE ⌘W is for this listener to leave the key completely alone. Swallowing but not+ * forwarding would still hand the recorder nothing — and forwarding is the live bug, since ⌘W+ * pressed into the recorder deletes the canvas's selected nodes.*/export function installKeydownIntercepts(win: KeydownInterceptTarget,getBindings: () => KeydownInterceptBindings,- isMac: boolean+ isMac: boolean,+ isRecording: () => boolean): void {win.webContents.on('before-input-event', (event, input) => {+ if (isRecording()) returnconst decision = keydownIntercept(input, getBindings(), isMac)if (!decision) returnevent.preventDefault()diff --git a/src/preload/index.test.ts b/src/preload/index.test.tsindex 53dc9247e..ccaf9447f 100644--- a/src/preload/index.test.ts+++ b/src/preload/index.test.ts@@ -88,6 +88,16 @@ describe('preload sshProject passphrase wiring', () => {expect(h.invoke).toHaveBeenCalledWith(IPC.sessionMemory, { projectId: 'p2', remote: false })})+ // The recorder's release leg is a `false`, and main reads it as `active === true`. A preload+ // that dropped the argument, or sent on the wrong channel, would leave ⌘W/⌘M/⌘0 suppressed+ // app-wide after Settings closed — with every other test in the tree still green.+ it('shortcuts.setRecording sends both edges on its own channel', () => {+ api.shortcuts.setRecording(true)+ expect(h.send).toHaveBeenCalledWith(IPC.uiShortcutRecording, true)+ api.shortcuts.setRecording(false)+ expect(h.send).toHaveBeenCalledWith(IPC.uiShortcutRecording, false)+ })+it('onPassphraseDismiss subscribes the dismiss channel and forwards the requestId', () => {const got: { requestId: string }[] = []const off = api.sshProject.onPassphraseDismiss((e) => got.push(e))diff --git a/src/preload/index.ts b/src/preload/index.tsindex 45e1fdf5c..290ebd9c0 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -593,6 +593,11 @@ const api: NodeTerminalApi = {},// Per-node subscriptions (each terminal/editor listens) — multiplexed so they don't pile up// ipcRenderer listeners and trip the MaxListeners warning.+ shortcuts: {+ // Fire-and-forget: nothing waits on the answer, and a dropped disarm is covered by main's own+ // window/renderer-death resets (index.ts `clearShortcutRecording`).+ setRecording: (active: boolean) => ipcRenderer.send(IPC.uiShortcutRecording, active)+ },onMarkdownToggle: subscribe(IPC.appToggleMarkdown),onCloseNode: subscribe(IPC.appCloseNode),onZoomActualSize: subscribe(IPC.appZoomActualSize),diff --git a/src/renderer/bridge/stubs.test.ts b/src/renderer/bridge/stubs.test.tsindex 9cd7f4858..540d354dc 100644--- a/src/renderer/bridge/stubs.test.ts+++ b/src/renderer/bridge/stubs.test.ts@@ -98,6 +98,10 @@ describe('bridge stubs', () => {s.setBadgeCount(3)s.contextLink.setLinks({} as never)s.sendAgentControlResult({} as never)+ // The shortcut recorder calls this on every arm AND on unmount; a throw here would leave+ // Settings unusable in the browser, where there is no main-process intercept to suspend.+ s.shortcuts.setRecording(true)+ s.shortcuts.setRecording(false)}).not.toThrow()})})diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 6188df37a..54099284d 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -353,6 +353,13 @@ export function buildStubApi(): Omit<listDevices: U('pairing.listDevices'),revokeDevice: U('pairing.revokeDevice')},+ shortcuts: {+ // Deliberate no-op (not a gap): the recording bit exists to stand the DESKTOP's+ // `before-input-event` intercepts down, and a browser tab has no application menu to steal+ // ⌘W/⌘M/⌘0 back from — nothing intercepts here, so there is nothing to suspend. The+ // recorder's own preventDefault/stopPropagation is the whole path in this shell.+ setRecording: noop+ },onMarkdownToggle: noopUnsub,onCloseNode: noopUnsub,// Deliberate no-op (not a gap): a browser tab has no application menu to steal ⌘0, so thediff --git a/src/renderer/components/settings/ShortcutRecorderButton.tsx b/src/renderer/components/settings/ShortcutRecorderButton.tsxindex 36c7bbcc3..a0c8bc6b2 100644--- a/src/renderer/components/settings/ShortcutRecorderButton.tsx+++ b/src/renderer/components/settings/ShortcutRecorderButton.tsx@@ -1,20 +1,24 @@/*** Generalized shortcut recorder: click to arm, press a chord. Keyed chords commit on keydown;* for allowHoldChord commands a modifier-only chord commits on full release (hold-to-talk).- * While armed it sets data-shortcut-recording (the window dispatcher bails on it via- * defaultPrevented — every key here is preventDefault'ed). The main-process recording bit- * (so ⌘W/⌘M/⌘0 interception cannot swallow the capture) is Task 5's: `window.nodeTerminal- * .shortcuts` does not exist on `NodeTerminalApi` yet, and that type lives in- * `src/shared/types.ts` — a file this task does not own. An optional-chained call does NOT- * typecheck against a member the interface never declares, so the three call sites are marked- * below rather than shipped broken.*- * **That bit is GLOBAL, so it owes an unmount release.** Chromium does not reliably fire `blur`- * on a focused element that is REMOVED from the DOM, so closing Settings while the recorder is- * armed can skip `onBlur` entirely — leaving the main-process bit set with no component left to+ * **Two separate mechanisms hold the keys off, one per process.** In the RENDERER it is this+ * component's own `preventDefault` + `stopPropagation` on every key it sees — the window+ * dispatcher bails on `defaultPrevented`, so nothing else in the page acts on the chord. The+ * `data-shortcut-recording` attribute is NOT part of that path: nothing reads it, and it is kept+ * only as the DOM-visible signal that the recorder is armed (tests, debugging, styling hooks). In+ * MAIN it is `shortcuts.setRecording`, because a chord the window intercepts in+ * `before-input-event` (⌘W, ⌘M, ⌘0) never reaches the page at all — no amount of renderer-side+ * preventing can catch a key the page was never given. Recording ⌘W without it DELETES THE+ * SELECTED NODES.+ *+ * **The main-process bit is GLOBAL, so it owes an unmount release.** Chromium does not reliably+ * fire `blur` on a focused element that is REMOVED from the DOM, so closing Settings while the+ * recorder is armed can skip `onBlur` entirely — leaving the bit set with no component left to* clear it, suppressing ⌘W/⌘M/⌘0 app-wide until the next arm/disarm cycle. `release` (below) is* the teardown both `stop()` and the unmount cleanup run; it touches refs only, so it is stable- * and safe to run when the recorder was never armed.+ * and safe to run when the recorder was never armed (`setRecording(false)` on a shell that was+ * never told `true` is a plain no-op).*/import { useCallback, useEffect, useRef, useState } from 'react'import { COMMANDS_BY_ID, normalizeBindingForCommand, type CommandId } from '@shared/keybindings'@@ -42,9 +46,9 @@ export function ShortcutRecorderButton({// and idempotent ⇒ running it on an unmount that was never armed is a no-op.const release = useCallback((): void => {stateRef.current = { mods: null }- // Task 5 wires the main-process recording bit here: setRecording(false)+ window.nodeTerminal.shortcuts.setRecording(false)}, [])- // Task 5: setRecording(false) must also be called from this unmount cleanup — see the header.+ // The unmount leg — the one that matters most (Settings closed mid-recording fires no blur).useEffect(() => release, [release])const stop = (): void => {@@ -56,7 +60,7 @@ export function ShortcutRecorderButton({stateRef.current = { mods: null }setCapturing(true)setHint('')- // Task 5 wires the main-process recording bit here: setRecording(true)+ window.nodeTerminal.shortcuts.setRecording(true)}const commit = (combo: string): void => {const r = normalizeBindingForCommand(def, combo, isMac)@@ -87,6 +91,8 @@ export function ShortcutRecorderButton({return (<buttontype="button"+ // Observability only — no dispatcher reads it (see the header). Keeps the armed state+ // visible to tests and to anyone inspecting the DOM.data-shortcut-recording={capturing || undefined}className="min-w-[120px] cursor-pointer rounded-md border border-border bg-panel-header px-3 py-1.5 text-[13px] font-medium text-text outline-none hover:bg-[rgba(255,255,255,0.06)]"onClick={start}diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex b815d7bf1..09cf5ac14 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -69,6 +69,12 @@ export const IPC = {* Electron's default View menu binds that accelerator to `resetZoom`, which resets the WINDOW's* page zoom rather than the canvas's. */appZoomActualSize: 'app:zoom-actual-size',+ /** Renderer → main: the Settings shortcut recorder is armed (`true`) or disarmed (`false`).+ * While armed the main window's `before-input-event` intercepts above stand down entirely, so+ * the chord the user is recording — ⌘W and ⌘M among them — reaches the recorder instead of+ * closing their selected nodes. Fire-and-forget `send`; desktop-only (a browser tab has no+ * application menu to steal a chord back from, so the Server Edition stubs it). */+ uiShortcutRecording: 'ui:shortcut-recording',appCloseWindow: 'app:close-window',/** Main → renderer: the native application menu's "Settings…" item (⌘,) was clicked. The* renderer opens the settings page — same path as the in-canvas gear button / Cmd+, keydown. */diff --git a/src/shared/types.ts b/src/shared/types.tsindex 49c419526..5542fe9d0 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -2467,6 +2467,19 @@ export interface PresenceApi {onPeer(listener: (diff: PeerDiff) => void): () => void}+/** Keyboard-shortcut plumbing the RENDERER cannot do for itself. */+export interface ShortcutsApi {+ /** Tell the shell that a shortcut recorder is armed (`true`) or released (`false`), so the+ * desktop's `before-input-event` intercepts stand down and the chord being recorded — ⌘W and+ * ⌘M among them — reaches the recorder instead of closing the user's selected nodes. A claimed+ * chord never reaches the page, so the recorder's own preventDefault cannot substitute for+ * this. Fire-and-forget. **The `false` leg is not optional**: the bit is global, so a recorder+ * that arms and never releases leaves those chords dead app-wide. Server Edition: a documented+ * no-op (a browser tab has no application menu to steal a chord back from, so nothing+ * intercepts). */+ setRecording(active: boolean): void+}+export interface NodeTerminalApi {pty: PtyApiworkspace: WorkspaceApi@@ -2508,6 +2521,7 @@ export interface NodeTerminalApi {handoff: HandoffApipairing: PairingApipresence: PresenceApi+ shortcuts: ShortcutsApi/** Fires when the user presses Cmd/Ctrl+M (toggle markdown view). Returns unsubscribe. */onMarkdownToggle(listener: () => void): () => void/** Fires when the user presses Cmd/Ctrl+W (close selected node). Returns unsubscribe. */