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
test(main): pin the keydown intercepts behaviourally, not by source text
Claude Codeffef4059df35
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex e755181ba..eff78f79a 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -125,6 +125,15 @@ passed with the code they were meant to pin removed, including one mutation thatWatch for fixtures that cannot discriminate: if every row in your fixture happens to make themutant's output identical to the real one, the test proves nothing while looking thorough.+**Never pin behaviour by reading source text.** `expect(SRC).toContain('...')` is the fixture that+can never discriminate: it is satisfied by code that is present *and wrong*. We shipped one —+`src/main/menu-accelerator-intercepts.test.ts` matched three strings inside the `before-input-event`+handler, and stayed green on a tree where a shared guard had moved out from under them and the bare+`0` key was swallowed app-wide. It was, precisely, red on the fix and green on the break. If a+module is untestable because it imports `electron` at the top, that is the thing to fix: lift the+decision into a pure function next to it (`keydown-intercept.ts`, `main-window.ts`,+`zoomShortcut.ts`) and press the keys.+Where a behaviour can only be verified on hardware we do not have in CI (a Mac, a real SSH host, aGPU), say so explicitly rather than implying coverage. Several docs carry numbered devicechecklists for exactly this.diff --git a/src/main/index.ts b/src/main/index.tsindex c32b3a320..e6f66a5eb 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -35,6 +35,7 @@ import {syntheticAnsweredEvent} from '../core/agents/pending-approvals'import { setMainWindow, getMainWindow, sendToMain, shouldHideOnClose, createCrashReloadPolicy } from './main-window'+import { installKeydownIntercepts } from './keydown-intercept'import {initNotchHud,applyNotchHudSettings,@@ -470,32 +471,10 @@ function createWindow(): BrowserWindow {}})- // Intercept Cmd/Ctrl+M (default = minimize) and route it to the renderer for the- // markdown-view toggle instead.- win.webContents.on('before-input-event', (event, input) => {- if (input.type !== 'keyDown' || !(input.meta || input.control)) return- const key = input.key.toLowerCase()- if (key === 'm') {- event.preventDefault()- win.webContents.send(IPC.appToggleMarkdown)- } else if (key === 'w' && !input.shift) {- // 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).- event.preventDefault()- win.webContents.send(IPC.appCloseNode)- } else if (input.code === 'Digit0' && !input.shift && !input.alt) {- // Repurpose Cmd/Ctrl+0 the same way. We never call `Menu.setApplicationMenu`, so Electron- // installs its DEFAULT menu, whose View → Actual Size binds this accelerator to `resetZoom`- // — the window's page zoom, not the canvas's. A menu accelerator is handled before the page- // sees the key, so without this the renderer's Digit0 branch would simply never run on the- // desktop. `before-input-event`'s preventDefault suppresses both the menu item and the page- // event, so exactly one thing happens: the canvas goes to 100%.- event.preventDefault()- // 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.- if (!input.isAutoRepeat) win.webContents.send(IPC.appZoomActualSize)- }- })+ // 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)// Open external links in the system browser — only safe schemes (no file://, no custom// protocol handlers). Reachable from remotely-fetched announcement URLs and rendereddiff --git a/src/main/keydown-intercept.test.ts b/src/main/keydown-intercept.test.tsnew file mode 100644index 000000000..a4b3a5acd--- /dev/null+++ b/src/main/keydown-intercept.test.ts@@ -0,0 +1,203 @@+import { describe, expect, it } from 'vitest'+import { IPC } from '../shared/ipc'+import {+ installKeydownIntercepts,+ keydownIntercept,+ type KeydownInterceptInput,+ type KeydownInterceptTarget+} from './keydown-intercept'++/**+ * BEHAVIOURAL. This replaces `menu-accelerator-intercepts.test.ts`, which asserted on the SOURCE+ * TEXT of `src/main/index.ts` (`expect(MAIN_SRC).toContain(...)`) and was therefore green on a tree+ * where a bare `0` keystroke was swallowed app-wide: the strings it matched were all still present,+ * because the guard that made them safe had moved out from under them. A test that reads the code+ * cannot see the code being *wrong*, only being *absent*.+ *+ * So: press keys, assert what happened. Two outcomes are observable and they are the two that+ * matter — did the window swallow the key (`preventDefault`, which takes it from the page AND the+ * default menu), and what did it forward to the renderer.+ *+ * The load-bearing half of this file is the refusals. Every chord here is built on a character+ * people type (`m`, `w`, `0`), so the difference between "intercepts ⌘0" and "intercepts 0" is one+ * modifier check and a completely unusable app.+ */++/** A `before-input-event` input with every flag off, overridable per case. */+function input(over: Partial<KeydownInterceptInput> = {}): KeydownInterceptInput {+ return {+ type: 'keyDown',+ key: '0',+ code: 'Digit0',+ meta: false,+ control: false,+ shift: false,+ alt: false,+ isAutoRepeat: false,+ ...over+ }+}++/**+ * 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[] } {+ let handler:+ | ((event: { preventDefault(): void }, input: KeydownInterceptInput) => void)+ | null = null+ const sent: string[] = []+ const win: KeydownInterceptTarget = {+ webContents: {+ on: (_event, listener) => {+ handler = listener+ },+ send: (channel) => {+ sent.push(channel)+ }+ }+ }+ installKeydownIntercepts(win)+ 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 }+}++/** Nothing happened at all: the page gets the key, and so does the menu if the page ignores it. */+const UNTOUCHED = { prevented: false, sent: [] }++describe('the main window refuses keys it does not claim', () => {+ // THE regression. #193 added the ⌘0 branch under a shared `meta || control` guard; a later+ // rewrite of that shared guard leaves `Digit0` with no modifier test of its own, and every+ // press of the zero key anywhere in the app is eaten and snaps the canvas to 100%.+ it('a bare 0 reaches the page', () => {+ expect(press()).toEqual(UNTOUCHED)+ })++ it('a bare m reaches the page', () => {+ expect(press({ key: 'm', code: 'KeyM' })).toEqual(UNTOUCHED)+ })++ it('a bare w reaches the page', () => {+ expect(press({ key: 'w', code: 'KeyW' })).toEqual(UNTOUCHED)+ })++ // Shift and Alt are not primary modifiers: `)`, `M`, `W`, and every AltGr character on a non-US+ // layout are ordinary typing.+ it.each([+ ['Shift+0 — types ")"', { shift: true, key: ')' }],+ ['Alt+0 — AltGr territory', { alt: true }],+ ['Shift+M', { shift: true, key: 'M', code: 'KeyM' }],+ ['Alt+W', { alt: true, key: 'w', code: 'KeyW' }]+ ])('%s reaches the page', (_name, over) => {+ expect(press(over)).toEqual(UNTOUCHED)+ })++ it('an unclaimed chord (⌘K) reaches the page', () => {+ expect(press({ meta: true, key: 'k', code: 'KeyK' })).toEqual(UNTOUCHED)+ })++ it('keyUp is never intercepted, even for a claimed chord', () => {+ expect(press({ type: 'keyUp', meta: true })).toEqual(UNTOUCHED)+ expect(press({ type: 'keyUp', meta: true, key: 'm', code: 'KeyM' })).toEqual(UNTOUCHED)+ expect(press({ type: 'keyUp', meta: true, key: 'w', code: 'KeyW' })).toEqual(UNTOUCHED)+ })+})++describe('⌘0 → canvas back to 100%', () => {+ it('is intercepted and forwarded', () => {+ expect(press({ meta: true })).toEqual({ prevented: true, sent: [IPC.appZoomActualSize] })+ })++ it('is intercepted under Ctrl too (Windows / Linux)', () => {+ expect(press({ control: true })).toEqual({ prevented: true, sent: [IPC.appZoomActualSize] })+ })++ // Matched on the physical key, so the chord survives a layout where the zero key prints+ // something else — the same rule the renderer's `zoomShortcutChord` follows.+ it('is matched on `code`, not the printed character', () => {+ expect(press({ meta: true, key: 'à' })).toEqual({+ prevented: true,+ sent: [IPC.appZoomActualSize]+ })+ // ...and only the digit row: the numpad zero is left to whatever else wants it.+ expect(press({ meta: true, code: 'Numpad0' })).toEqual(UNTOUCHED)+ })++ it('drops OS auto-repeat while still swallowing the key', () => {+ // Both halves matter. Forwarding a held ⌘0 would restart the 200ms zoom tween on every repeat;+ // letting it through would hand the repeat to the default menu's View ▸ Actual Size instead.+ expect(press({ meta: true, isAutoRepeat: true })).toEqual({ prevented: true, sent: [] })+ })++ it('is not claimed with Shift or Alt added', () => {+ expect(press({ meta: true, shift: true })).toEqual(UNTOUCHED)+ expect(press({ meta: true, alt: true })).toEqual(UNTOUCHED)+ })+})++describe('⌘M → markdown view, stolen back from Window ▸ Minimize', () => {+ it('is intercepted and forwarded', () => {+ expect(press({ meta: true, key: 'm', code: 'KeyM' })).toEqual({+ prevented: true,+ sent: [IPC.appToggleMarkdown]+ })+ expect(press({ control: true, key: 'm', code: 'KeyM' })).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]+ })+ })++ it('repeats keep toggling (no auto-repeat rule here, unlike ⌘0)', () => {+ expect(press({ meta: true, key: 'm', code: 'KeyM', isAutoRepeat: true })).toEqual({+ prevented: true,+ sent: [IPC.appToggleMarkdown]+ })+ })+})++describe('⌘W → close the selected node, stolen back from Window ▸ Close', () => {+ it('is intercepted and forwarded', () => {+ expect(press({ meta: true, key: 'w', code: 'KeyW' })).toEqual({+ prevented: true,+ sent: [IPC.appCloseNode]+ })+ expect(press({ control: true, key: 'w', code: 'KeyW' })).toEqual({+ prevented: true,+ sent: [IPC.appCloseNode]+ })+ })++ it('leaves ⌘⇧W to the menu (Close All Windows)', () => {+ expect(press({ meta: true, shift: 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 })+ })+})diff --git a/src/main/keydown-intercept.ts b/src/main/keydown-intercept.tsnew file mode 100644index 000000000..315110ece--- /dev/null+++ b/src/main/keydown-intercept.ts@@ -0,0 +1,115 @@+import { IPC } from '../shared/ipc'++/**+ * The main window's `before-input-event` decision as ONE pure function — the desktop half of the+ * pair whose renderer half is `src/renderer/lib/zoomShortcut.ts` (same shape: a key-state-only+ * input, an action-or-null out, and the refusals as the point of the module).+ *+ * **Why the main process gets a say at all.** We never call `Menu.setApplicationMenu`, so Electron+ * installs its DEFAULT application menu, and that menu already claims all three of these chords:+ *+ * ⌘M → Window ▸ Minimize ⌘W → Window ▸ Close ⌘0 → View ▸ Actual Size (`resetZoom`)+ *+ * A menu accelerator is handled *before* the page sees the key, so a renderer-side listener for any+ * of them would simply never run on the desktop. `before-input-event`'s `preventDefault` suppresses+ * the menu item AND the page event, which is why each claimed chord has to forward its intent to+ * the renderer over IPC itself rather than letting the key through.+ *+ * **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.+ *+ * 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+ * application menu to steal a chord back from.+ */++/** What a claimed chord asks the renderer to do. */+export type KeydownInterceptAction = 'toggle-markdown' | 'close-node' | 'zoom-actual-size'++/** The subset of Electron's `Input` the decision is made from (so tests need no Electron). */+export interface KeydownInterceptInput {+ type: string+ key: string+ code: string+ meta: boolean+ control: boolean+ shift: boolean+ alt: boolean+ /** OS auto-repeat: true on every keyDown after the first while the chord is HELD. */+ isAutoRepeat: boolean+}++/**+ * A claimed chord. `preventDefault` is implied by getting one of these at all — the key is ours,+ * so neither the menu nor the page may have it. `action` is separately nullable because a HELD ⌘0+ * must keep being swallowed (the menu is still listening) while forwarding nothing.+ */+export interface KeydownInterceptDecision {+ action: KeydownInterceptAction | null+}++/**+ * 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.+ */+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' }+ // 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) {+ // 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.+ return { action: input.isAutoRepeat ? null : 'zoom-actual-size' }+ }+ return null+}++/** The renderer channel a claimed action is forwarded on. */+export function keydownInterceptChannel(action: KeydownInterceptAction): string {+ if (action === 'toggle-markdown') return IPC.appToggleMarkdown+ if (action === 'close-node') return IPC.appCloseNode+ return IPC.appZoomActualSize+}++/** Structural view of the window this installs on (keeps the module Electron-free, like+ * `main-window.ts`). */+export interface KeydownInterceptTarget {+ webContents: {+ on(+ event: 'before-input-event',+ listener: (event: { preventDefault(): void }, input: KeydownInterceptInput) => void+ ): void+ send(channel: string, ...args: unknown[]): void+ }+}++/**+ * 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`.+ */+export function installKeydownIntercepts(win: KeydownInterceptTarget): void {+ win.webContents.on('before-input-event', (event, input) => {+ const decision = keydownIntercept(input)+ if (!decision) return+ event.preventDefault()+ if (decision.action) win.webContents.send(keydownInterceptChannel(decision.action))+ })+}diff --git a/src/main/menu-accelerator-intercepts.test.ts b/src/main/menu-accelerator-intercepts.test.tsdeleted file mode 100644index d88ae24f2..000000000--- a/src/main/menu-accelerator-intercepts.test.ts+++ /dev/null@@ -1,37 +0,0 @@-import fs from 'node:fs'-import path from 'node:path'-import { describe, expect, it } from 'vitest'--// GUARD, not a unit test. `src/main/index.ts` imports `electron` at module scope, so its-// `before-input-event` handler cannot be loaded here — but that handler is the only thing standing-// between three chords and Electron's DEFAULT application menu, which we never replace-// (`Menu.setApplicationMenu` is not called anywhere) and which claims all three:-//-// ⌘M → Window ▸ Minimize ⌘W → Window ▸ Close ⌘0 → View ▸ Actual Size (resetZoom)-//-// A menu accelerator is handled before the page sees the key, so deleting a branch here does not-// break a test or throw — the shortcut just quietly starts minimizing the window / closing it /-// resetting the WINDOW's page zoom instead of doing the app's thing. That is the failure this-// pins. (`before-input-event`'s preventDefault suppresses the menu item AND the page event, which-// is why each branch has to forward the intent to the renderer itself.)-const MAIN_SRC = fs.readFileSync(path.join(__dirname, 'index.ts'), 'utf8')--describe('the main window steals its chords back from the default menu', () => {- it('still intercepts before the page and the menu', () => {- expect(MAIN_SRC).toContain("win.webContents.on('before-input-event'")- })-- it('forwards ⌘M and ⌘W to the renderer', () => {- expect(MAIN_SRC).toContain('win.webContents.send(IPC.appToggleMarkdown)')- expect(MAIN_SRC).toContain('win.webContents.send(IPC.appCloseNode)')- })-- it('forwards ⌘0 to the renderer, and only on a FRESH press', () => {- // Matched on the physical `code`, like the renderer's half of the chord: on a non-US layout- // the zero key's `key` is not necessarily "0".- expect(MAIN_SRC).toContain("input.code === 'Digit0' && !input.shift && !input.alt")- // The repeat drop lives HERE because the forwarded signal carries no event: without it, a held- // ⌘0 would restart the 200ms zoom tween on every OS repeat.- expect(MAIN_SRC).toContain('if (!input.isAutoRepeat) win.webContents.send(IPC.appZoomActualSize)')- })-})