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): stand the intercepts down under terminal-first while a terminal is focused
enes14e27a793547
diff --git a/src/main/index.ts b/src/main/index.tsindex 816a98e1f..d1f31f853 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -91,9 +91,14 @@ import { setMainWindow, getMainWindow, sendToMain, closeAction, createCrashReloaimport {installKeydownIntercepts,navigationClearsRecording,+ policyStandsDown,resolveInterceptBindings,type KeydownInterceptBindings} from './keydown-intercept'+import {+ normalizeTerminalShortcutPolicy,+ type TerminalShortcutPolicy+} from '../shared/keybindings'import {initNotchHud,applyNotchHudSettings,@@ -290,23 +295,47 @@ const interceptIsMac = process.platform === 'darwin'let interceptBindings: KeydownInterceptBindings | null = nullconst currentInterceptBindings = (): KeydownInterceptBindings =>(interceptBindings ??= resolveInterceptBindings(settingsStore.get().keybindings, interceptIsMac))+// The user's terminal-shortcut policy, memoized on exactly the same terms and for exactly the same+// reason as `interceptBindings` above: lazily on first keystroke (module load is before+// `settingsStore.init()`, where every stored value still reads as DEFAULT_SETTINGS), recomputed on+// `onChange`, never per keystroke. Normalized through the shared helper so an unknown value from a+// hand-edited settings.json reads as the default `app-first` — i.e. as "keep intercepting", which+// is the direction that leaves the app working.+let interceptPolicy: TerminalShortcutPolicy | null = null+const currentInterceptPolicy = (): TerminalShortcutPolicy =>+ (interceptPolicy ??= normalizeTerminalShortcutPolicy(settingsStore.get().terminalShortcutPolicy))settingsStore.onChange((s) => {interceptBindings = resolveInterceptBindings(s.keybindings, interceptIsMac)+ interceptPolicy = normalizeTerminalShortcutPolicy(s.terminalShortcutPolicy)})-// 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). The alternative is-// ⌘W/⌘M/⌘0 dead app-wide with no component left alive to release the bit, so EVERY way the page-// that armed it can stop existing owes a clear — `createWindow` wires three (window `closed`,-// `render-process-gone`, and a main-frame navigation, i.e. ⌘R). That is three known paths, not a-// proof of exhaustiveness: a fourth would show up as "⌘W stopped working after I did X", so add-// its reset beside the others rather than assuming this list is closed.+// TWO bits the RENDERER owns and main only mirrors. Both are module-level `let`s 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.+//+// 1. `shortcutRecording` — 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.+// 2. `terminalFocused` — an xterm holds keyboard focus, which under the `terminal-first` policy+// means the intercepts stand down so the terminal gets the chord. `before-input-event` fires+// before any renderer handler could answer, so the answer has to be sitting here in advance;+// `renderer/lib/terminalFocusMirror.ts` keeps it current and change-deduped.+//+// FAIL-SAFE DIRECTION, and it is the same one for both: every uncertainty resolves to `false`+// (intercepts ON — the app as it behaved before either feature). The alternative is ⌘W/⌘M/⌘0+// silently handed back to the application MENU app-wide, with no component left alive to release+// the bit. So EVERY way the page that set one can stop existing owes a clear, and `createWindow`+// wires three — window `closed`, `render-process-gone`, and a main-frame navigation (⌘R). That is+// three known paths, not a proof of exhaustiveness: a fourth would show up as "⌘W stopped working+// after I did X", so add its reset beside the others rather than assuming this list is closed.+// The two bits are cleared TOGETHER, by one function called at all three sites, because they die+// for the same reason (the page is gone) and a reset that remembered only one of them would be+// invisible until a user hit the policy path.let shortcutRecording = false-const clearShortcutRecording = (): void => {+let terminalFocused = false+const clearRendererKeyState = (): void => {shortcutRecording = false+ terminalFocused = false}const sshStore = new SshStore()const ptyManager = new PtyManager()@@ -638,11 +667,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()+ // The window that armed the recorder — or reported a focused terminal — is gone, so nothing+ // can ever release either bit. Leaving one set would suppress ⌘W/⌘M/⌘0 for the NEXT window too+ // (the flags outlive 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.+ clearRendererKeyState()})// 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.@@ -653,9 +682,10 @@ 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()+ // A dead renderer sends no disarm and no focus-lost report. The reloaded page mounts no+ // recorder and no terminal, so without this the user would come back to an app where ⌘W does+ // nothing at all (recording) or minimizes the window (stood down).+ clearRendererKeyState()if (quitting || win.isDestroyed()) returnconst action = crashReload(details.reason, Date.now())if (action === 'reload') {@@ -710,16 +740,26 @@ 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, () => shortcutRecording)-- // The THIRD way the page that armed a recorder can go away: a reload. The View menu above- // restores `{role:'reload'}` / `{role:'forceReload'}`, and ⌘R/⌘⇧R are accelerators — handled- // above the page, so the recorder cannot preventDefault its way out of one, and a same-process- // reload fires neither `closed` nor `render-process-gone`. `navigationClearsRecording` is the- // (tested) filter: a same-document navigation is the SAME page with the recorder still armed,- // and a subframe is not this page at all.+ // The two suspensions are separate thunks on purpose (see `installKeydownIntercepts`): the+ // recorder suspends ALWAYS, the policy only while the mirror says a terminal has focus. Both are+ // read per keystroke — the settings memo and the mirror both change under a live window.+ installKeydownIntercepts(+ win,+ currentInterceptBindings,+ interceptIsMac,+ () => shortcutRecording,+ () => policyStandsDown(currentInterceptPolicy(), terminalFocused)+ )++ // The THIRD way the page that armed a recorder (or reported terminal focus) can go away: a+ // reload. The View menu above restores `{role:'reload'}` / `{role:'forceReload'}`, and ⌘R/⌘⇧R are+ // accelerators — handled above the page, so the recorder cannot preventDefault its way out of+ // one, and a same-process reload fires neither `closed` nor `render-process-gone`.+ // `navigationClearsRecording` is the (tested) filter: a same-document navigation is the SAME page+ // with the recorder still armed and the terminal still focused, and a subframe is not this page+ // at all.win.webContents.on('did-start-navigation', (details) => {- if (navigationClearsRecording(details)) clearShortcutRecording()+ if (navigationClearsRecording(details)) clearRendererKeyState()})// Open external links in the system browser — only safe schemes (no file://, no custom@@ -956,6 +996,16 @@ app.whenReady().then(async () => {shortcutRecording = active === true})+ // The terminal-focus mirror, under the SAME sender guard and for a sharper version of the same+ // reason: a <webview> guest is a webContents in this process, and this bit decides whether the+ // window claims ⌘W/⌘M/⌘0 at all — an arbitrary page in a browser node could otherwise hand+ // itself the window's shortcuts by claiming a terminal is focused. `focused === true` so a+ // malformed payload reads as NOT focused, the fail-safe direction (intercepts on).+ ipcMain.on(IPC.uiTerminalFocus, (event, focused: boolean) => {+ if (getMainWindow()?.webContents.id !== event.sender.id) return+ terminalFocused = focused === 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 b39b5a0a5..475b5f0f5 100644--- a/src/main/keydown-intercept.test.ts+++ b/src/main/keydown-intercept.test.ts@@ -5,6 +5,7 @@ import {installKeydownIntercepts,keydownIntercept,navigationClearsRecording,+ policyStandsDown,resolveInterceptBindings,type KeydownInterceptBindings,type KeydownInterceptInput,@@ -59,9 +60,11 @@ 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)+ // Neither recording nor stood down: the ordinary state of the app, and the baseline every case+ // below asserts against. Each suspended state has its own describe block at the bottom of this+ // file. Both thunks are spelled out rather than defaulted, so a THIRD suspension added to+ // `installKeydownIntercepts` cannot silently inherit "off" here.+ const seam = install(() => bindings, isMac, () => false, () => false)seam.fire(over)return { prevented: seam.prevented.length > 0, sent: seam.sent }}@@ -74,7 +77,8 @@ function press(function install(getBindings: () => KeydownInterceptBindings,isMac: boolean,- isRecording: () => boolean+ isRecording: () => boolean,+ isStoodDown: () => boolean): { fire: (over?: Partial<KeydownInterceptInput>) => void; prevented: string[]; sent: string[] } {let handler:| ((event: { preventDefault(): void }, input: KeydownInterceptInput) => void)@@ -91,7 +95,7 @@ function install(}}}- installKeydownIntercepts(win, getBindings, isMac, isRecording)+ installKeydownIntercepts(win, getBindings, isMac, isRecording, isStoodDown)if (!handler) throw new Error('installKeydownIntercepts registered no before-input-event listener')const fire = (over: Partial<KeydownInterceptInput> = {}): void => {const i = input(over)@@ -346,7 +350,7 @@ describe('binding-driven intercept', () => {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)+ const seam = install(() => DEFAULTS, true, () => recording, () => false)seam.fire({ meta: true, key: 'w', code: 'KeyW' })seam.fire({ meta: true, key: 'm', code: 'KeyM' })seam.fire({ meta: true, code: 'Digit0' })@@ -368,7 +372,7 @@ describe('an armed shortcut recorder suspends every interception', () => {// This mirrors index.ts's wiring exactly — the listener runs the same predicate.it('a reload while armed restores interception; an in-page navigation does not', () => {let recording = true- const seam = install(() => DEFAULTS, true, () => recording)+ const seam = install(() => DEFAULTS, true, () => recording, () => false)const onNavigation = (d: { isMainFrame: boolean; isSameDocument: boolean }): void => {if (navigationClearsRecording(d)) recording = false}@@ -397,10 +401,107 @@ describe('an armed shortcut recorder suspends every interception', () => {// 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)+ const seam = install(() => DEFAULTS, true, () => recording, () => false)seam.fire({ meta: true, key: 'w', code: 'KeyW' })recording = trueseam.fire({ meta: true, key: 'w', code: 'KeyW' })expect(seam.sent).toEqual([IPC.appCloseNode])})})++/**+ * The SECOND suspension, and a different fact from the first. `terminal-first` is the user saying+ * "while I am typing in a terminal, the terminal gets the chord" — so main must stop claiming keys+ * it would otherwise steal from the page, for exactly as long as an xterm holds keyboard focus.+ *+ * It is a separate thunk rather than an `||` folded into `isRecording` because the two suspend for+ * unrelated reasons and on unrelated schedules: recording is a Settings dialog being armed and+ * suspends ALWAYS, the policy one is a live focus mirror and suspends only while the mirror says a+ * terminal is focused. One boolean would make "recording still works when the policy is off" — the+ * first case below — untestable, and would hide a future bug where one reason silently ate the+ * other.+ */+describe('terminal-first stands every interception down while a terminal is focused', () => {+ it('suppresses all three chords while stood down, and resumes when it flips back', () => {+ let stoodDown = true+ const seam = install(() => DEFAULTS, true, () => false, () => stoodDown)+ seam.fire({ meta: true, key: 'w', code: 'KeyW' })+ seam.fire({ meta: true, key: 'm', code: 'KeyM' })+ seam.fire({ meta: true, code: 'Digit0' })+ // ⌘0 is in the list on purpose: it is the one chord with no registry command behind it, so a+ // stand-down written against `getBindings` alone would leave it claimed — and the canvas would+ // still snap to 100% under a user who asked their terminal to own the key.+ // Not swallowed either: `preventDefault` takes the key from the PAGE as well as the menu, and+ // the page is who the terminal-first policy is standing down FOR, so the suppression must+ // return before it rather than merely skip the send.+ expect(seam.prevented).toEqual([])+ expect(seam.sent).toEqual([])+ // Focus leaves the terminal (or the user switches back to app-first): every chord is ours again.+ stoodDown = false+ seam.fire({ meta: true, key: 'w', code: 'KeyW' })+ seam.fire({ meta: true, key: 'm', code: 'KeyM' })+ seam.fire({ meta: true, code: 'Digit0' })+ expect(seam.sent).toEqual([IPC.appCloseNode, IPC.appToggleMarkdown, IPC.appZoomActualSize])+ expect(seam.prevented).toEqual(['KeyW', 'KeyM', 'Digit0'])+ })++ it('the two suspensions are independent — either one alone suppresses', () => {+ let recording = false+ let stoodDown = false+ const seam = install(() => DEFAULTS, true, () => recording, () => stoodDown)+ // Recording alone, with the policy off: the Settings recorder must keep working for a user who+ // never chose terminal-first (i.e. everybody, by default).+ recording = true+ seam.fire({ meta: true, key: 'w', code: 'KeyW' })+ expect(seam.sent).toEqual([])+ // Stood down alone, with no recorder armed: the policy suspension does not depend on the other.+ recording = false+ stoodDown = true+ seam.fire({ meta: true, key: 'w', code: 'KeyW' })+ expect(seam.sent).toEqual([])+ // Neither: back to the ordinary app.+ stoodDown = false+ seam.fire({ meta: true, key: 'w', code: 'KeyW' })+ expect(seam.sent).toEqual([IPC.appCloseNode])+ })++ it('is read per event, not captured at install time', () => {+ // Same reason as the recording bit's twin test: the focus mirror flips a module-level `let` in+ // index.ts over IPC while the window lives. A captured boolean would make the policy inert for+ // whichever value happened to be true at `createWindow` time — i.e. always inert, since the+ // window is built before any renderer has reported focus.+ let stoodDown = false+ const seam = install(() => DEFAULTS, true, () => false, () => stoodDown)+ seam.fire({ meta: true, key: 'w', code: 'KeyW' })+ stoodDown = true+ seam.fire({ meta: true, key: 'w', code: 'KeyW' })+ expect(seam.sent).toEqual([IPC.appCloseNode])+ })+})++/**+ * The composition index.ts hands to the 5th parameter, as a pure function so it can be pressed.+ * The BYTE-IDENTICAL claim of this whole change lives here: on the shipped default (`app-first`)+ * it is false whatever the mirror says, so nothing about the intercepts changes for a user who+ * never touched the setting — including one whose renderer is reporting terminal focus all day.+ */+describe('policyStandsDown', () => {+ it('stands down only under terminal-first, and only while a terminal is focused', () => {+ expect(policyStandsDown('terminal-first', true)).toBe(true)+ expect(policyStandsDown('terminal-first', false)).toBe(false)+ })++ it('app-first never stands down, focused or not', () => {+ expect(policyStandsDown('app-first', true)).toBe(false)+ expect(policyStandsDown('app-first', false)).toBe(false)+ })++ // The fail-safe direction, stated as a test: main starts at `terminalFocused = false` and every+ // reset returns it there, so a mirror that never reported — or a page that died mid-report —+ // leaves the intercepts ON (the pre-feature behaviour), never off.+ it('the reset value (not focused) means intercepts stay on under either policy', () => {+ for (const policy of ['app-first', 'terminal-first'] as const) {+ expect(policyStandsDown(policy, false)).toBe(false)+ }+ })+})diff --git a/src/main/keydown-intercept.ts b/src/main/keydown-intercept.tsindex 498cf4a27..c257d4f2a 100644--- a/src/main/keydown-intercept.ts+++ b/src/main/keydown-intercept.ts@@ -1,5 +1,9 @@import { IPC } from '../shared/ipc'-import { getEffectiveBindings, sanitizeKeybindingOverrides } from '../shared/keybindings'+import {+ getEffectiveBindings,+ sanitizeKeybindingOverrides,+ type TerminalShortcutPolicy+} from '../shared/keybindings'import { matchesShortcut } from '../shared/shortcut'/**@@ -195,6 +199,31 @@ export function navigationClearsRecording(details: {return details.isMainFrame && !details.isSameDocument}+/**+ * PURE. Does the user's `terminalShortcutPolicy` mean this window must stop claiming chords right+ * now? The composition `index.ts` hands to `installKeydownIntercepts`' 5th parameter, exported so+ * it can be pressed instead of living untested inside a closure in a 5000-line file.+ *+ * **Both halves are refusals and both matter.** `app-first` is the shipped default, so it must be+ * false whatever the mirror reports — that is the byte-identical guarantee of this feature: a user+ * who never touched the setting sees exactly the pre-feature intercepts, even though their+ * renderer is reporting terminal focus all day. And `terminalFocused` is a MIRROR of the+ * renderer's `document.activeElement`, which is why `false` is its reset value everywhere: a page+ * that died mid-report, a window that never had one, a reload — all resolve to "intercepts on",+ * never to "intercepts off with nothing alive to turn them back on".+ *+ * Why the policy is read here rather than the intercepts simply being uninstalled under+ * `terminal-first`: the policy is a live setting and the focus changes per keystroke, so there is+ * nothing static to install against — and an app-first user's window must not be a different+ * window from a terminal-first user's.+ */+export function policyStandsDown(+ policy: TerminalShortcutPolicy,+ terminalFocused: boolean+): boolean {+ return policy === 'terminal-first' && terminalFocused+}+/** The renderer channel a claimed action is forwarded on. */export function keydownInterceptChannel(action: KeydownInterceptAction): string {if (action === 'toggle-markdown') return IPC.appToggleMarkdown@@ -240,15 +269,32 @@ export interface KeydownInterceptTarget {* suspending the MENU while recording (`Menu.setApplicationMenu(null)` around the armed window, or* per-item `enabled:false`) — a change to `buildAppMenu`, not to this module. Known limitation;* see the PR body.+ *+ * `isStoodDown` is the SECOND suspension and the same shape again, but a different fact:+ * `policyStandsDown(policy, terminalFocused)` — the user chose `terminal-first` AND an xterm+ * currently holds keyboard focus in the renderer. It is a separate parameter rather than an `||`+ * folded into `isRecording` because the two suspend for unrelated reasons on unrelated schedules+ * (a Settings dialog being armed vs. a live focus mirror), and one boolean would make "the+ * recorder still works for an app-first user" — the overwhelmingly common case — impossible to+ * assert. Both are checked BEFORE `preventDefault` for the same reason: a claimed chord never+ * reaches the page at all, and the page is exactly who terminal-first stands down FOR.+ *+ * **The stand-down leg cannot be more reliable than the mirror behind it**, and the mirror is a+ * renderer reporting over fire-and-forget IPC. Every uncertainty therefore resolves to NOT stood+ * down (intercepts on = the pre-feature app): `index.ts` starts `terminalFocused` false and every+ * way the page can stop existing resets it there. Getting that direction backwards would leave ⌘W+ * and ⌘M with the application MENU — closing and minimizing the window — with no live component+ * able to correct it.*/export function installKeydownIntercepts(win: KeydownInterceptTarget,getBindings: () => KeydownInterceptBindings,isMac: boolean,- isRecording: () => boolean+ isRecording: () => boolean,+ isStoodDown: () => boolean): void {win.webContents.on('before-input-event', (event, input) => {- if (isRecording()) return+ if (isRecording() || isStoodDown()) returnconst decision = keydownIntercept(input, getBindings(), isMac)if (!decision) returnevent.preventDefault()diff --git a/src/preload/index.test.ts b/src/preload/index.test.tsindex ccaf9447f..8e83ea05f 100644--- a/src/preload/index.test.ts+++ b/src/preload/index.test.ts@@ -98,6 +98,24 @@ describe('preload sshProject passphrase wiring', () => {expect(h.send).toHaveBeenCalledWith(IPC.uiShortcutRecording, false)})+ // Same story for the focus mirror, and its OWN channel matters: main keeps the two bits apart+ // (one suspends always, the other only under `terminal-first`), so a preload that folded the+ // mirror onto the recording channel would disable ⌘W/⌘M/⌘0 for every user the moment they+ // clicked into a terminal — with the whole suite still green.+ it('shortcuts.setTerminalFocused sends both edges on its own channel', () => {+ const before = h.send.mock.calls.length+ api.shortcuts.setTerminalFocused(true)+ api.shortcuts.setTerminalFocused(false)+ // The whole call list, not two `toHaveBeenCalledWith`s: what must be true is that the mirror+ // touched the terminal-focus channel and NOTHING else — folding it onto `ui:shortcut-recording`+ // would disable ⌘W/⌘M/⌘0 for every user the moment they clicked into a terminal, and a+ // per-call assertion would stay green through exactly that.+ expect(h.send.mock.calls.slice(before)).toEqual([+ [IPC.uiTerminalFocus, true],+ [IPC.uiTerminalFocus, 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 9d1d9f1e5..ebe0793d7 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -598,7 +598,11 @@ const api: NodeTerminalApi = {// this page can stop existing — window closed, renderer died, main-frame navigation (⌘R) —// but those are a backstop for a page that VANISHED, not a general safety net: an ordinary// disarm that never sends leaves the shortcuts suppressed until one of them happens.- setRecording: (active: boolean) => ipcRenderer.send(IPC.uiShortcutRecording, active)+ setRecording: (active: boolean) => ipcRenderer.send(IPC.uiShortcutRecording, active),+ // The terminal-focus mirror, same fire-and-forget shape and the same fail-safe reading on the+ // far side: main starts at "not focused" and the three page-death resets return it there, so a+ // report that never arrives costs the terminal-first policy, not the app's shortcuts.+ setTerminalFocused: (focused: boolean) => ipcRenderer.send(IPC.uiTerminalFocus, focused)},onMarkdownToggle: subscribe(IPC.appToggleMarkdown),onCloseNode: subscribe(IPC.appCloseNode),diff --git a/src/renderer/bridge/stubs.test.ts b/src/renderer/bridge/stubs.test.tsindex 540d354dc..8087cabdd 100644--- a/src/renderer/bridge/stubs.test.ts+++ b/src/renderer/bridge/stubs.test.ts@@ -102,6 +102,11 @@ describe('bridge stubs', () => {// Settings unusable in the browser, where there is no main-process intercept to suspend.s.shortcuts.setRecording(true)s.shortcuts.setRecording(false)+ // The focus mirror fires on every click into and out of a terminal, so a throw here would+ // break the browser canvas on the first keystroke — and the browser has no main-process+ // intercept for it to suspend in the first place.+ s.shortcuts.setTerminalFocused(true)+ s.shortcuts.setTerminalFocused(false)}).not.toThrow()})})diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 54099284d..7c6c05c15 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -358,7 +358,12 @@ export function buildStubApi(): Omit<// `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+ setRecording: noop,+ // Deliberate no-op for the same reason, one step further: the mirror exists so the DESKTOP's+ // intercepts can stand down under `terminal-first`, and there are no intercepts here to+ // stand down. The policy itself still works in the browser — it is enforced by the+ // renderer's own dispatcher (`keyDispatchContextFor`), which reads focus directly.+ setTerminalFocused: noop},onMarkdownToggle: noopUnsub,onCloseNode: noopUnsub,diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex cb111da81..f413e915d 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -180,6 +180,7 @@ import {type GlobalKeydownDeps} from '../lib/globalKeybindings'import { isTerminalTarget, type ContextElement } from '../lib/keyContext'+import { installTerminalFocusMirror } from '../lib/terminalFocusMirror'import {activeKeybindingOverrides,chipFor,@@ -5315,6 +5316,25 @@ export function Canvas() {return () => window.removeEventListener('keydown', onKey)}, [])+ // Mirror "an xterm has keyboard focus" to main, so the DESKTOP's `before-input-event` intercepts+ // can stand down under the `terminal-first` policy: that intercept fires before any renderer+ // handler could tell it, so the answer has to already be in main. The mirror is deliberately NOT+ // gated on the policy — main composes `policy === 'terminal-first' && terminalFocused`, so a user+ // who flips the setting with a terminal already focused gets the new behaviour on their very next+ // keystroke, rather than after the next focus change. Under the shipped `app-first` default main's+ // half is false regardless, so nothing about this app's shortcuts changes.+ // The logic (change-dedup, the microtask-settled read, the window-blur leg and the re-check that+ // catches a focused terminal being torn out of the DOM by a park / offscreen release / delete)+ // lives in `lib/terminalFocusMirror.ts`, where it is pressed against a real DOM. Server Edition:+ // the bridge stubs `setTerminalFocused` — there is no main-process intercept there to suspend.+ useEffect(+ () =>+ installTerminalFocusMirror({+ report: (focused) => window.nodeTerminal.shortcuts.setTerminalFocused(focused)+ }),+ []+ )+// ⌘/Ctrl+0 on the DESKTOP never reaches the keydown handler above: Electron's default View menu// binds the accelerator to `resetZoom`, and a menu accelerator is handled before the page sees// the key. `main/index.ts` intercepts it in `before-input-event` — exactly as it already does fordiff --git a/src/renderer/lib/terminalFocusMirror.test.ts b/src/renderer/lib/terminalFocusMirror.test.tsnew file mode 100644index 000000000..0ea064d13--- /dev/null+++ b/src/renderer/lib/terminalFocusMirror.test.ts@@ -0,0 +1,185 @@+// @vitest-environment jsdom+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { XTERM_INPUT_CLASS } from './keyContext'+import { TERMINAL_FOCUS_RECHECK_MS, installTerminalFocusMirror } from './terminalFocusMirror'++/**+ * REAL DOM (jsdom), because every question this module answers is a question about focus event+ * ORDER and about what `document.activeElement` says at each point — and a hand-rolled fake would+ * simply encode whatever the author assumed. The three facts below were MEASURED against jsdom+ * before this module was written, and each one decides a line of it:+ *+ * 1. `focusout` fires with `document.activeElement` already reset to `<body>` — the incoming+ * element is not focused yet. So an immediate read during focusout answers "no terminal" for+ * EVERY focus move, including terminal → terminal.+ * 2. A microtask scheduled from that same `focusout` reads the SETTLED element. So deferring the+ * read collapses a terminal → terminal hop into no change at all.+ * 3. Removing the focused element from the document fires NO focusout whatsoever; activeElement+ * silently becomes `<body>`. That is the stuck-state path this app actually walks — a parked,+ * released or deleted terminal node tears its xterm out of the DOM — and it is why the+ * mirror carries a re-check that does not depend on an event arriving.+ */++const report = vi.fn<(focused: boolean) => void>()+let stop: (() => void) | null = null++function terminalTextarea(): HTMLTextAreaElement {+ const ta = document.createElement('textarea')+ ta.className = XTERM_INPUT_CLASS+ document.body.append(ta)+ return ta+}++function ordinaryInput(): HTMLInputElement {+ const el = document.createElement('input')+ document.body.append(el)+ return el+}++/** Let the mirror's deferred read run. */+const settle = (): Promise<void> => Promise.resolve()++beforeEach(() => {+ vi.useFakeTimers()+ report.mockClear()+ document.body.innerHTML = ''+})++afterEach(() => {+ stop?.()+ stop = null+ vi.useRealTimers()+})++describe('installTerminalFocusMirror', () => {+ it('reports true when an xterm textarea takes focus, and false when it loses it', async () => {+ const term = terminalTextarea()+ const input = ordinaryInput()+ stop = installTerminalFocusMirror({ report })+ expect(report).toHaveBeenCalledWith(false) // the initial read: nothing focused yet++ report.mockClear()+ term.focus()+ await settle()+ expect(report.mock.calls).toEqual([[true]])++ report.mockClear()+ input.focus()+ await settle()+ expect(report.mock.calls).toEqual([[false]])+ })++ it('is change-deduped: focus moving between two terminals reports nothing at all', async () => {+ const a = terminalTextarea()+ const b = terminalTextarea()+ stop = installTerminalFocusMirror({ report })+ a.focus()+ await settle()+ report.mockClear()++ // The measured trap: `focusout` fires with activeElement === <body>, so an IMMEDIATE read here+ // would report false-then-true on every hop between terminals — a window, however brief, in+ // which main re-arms the intercepts under a terminal that never lost focus. Two chords land in+ // that window in practice (⌘W closing a node mid-edit is the one users would file).+ b.focus()+ await settle()+ expect(report).not.toHaveBeenCalled()+ })++ it('reports the CURRENT state once at install, before any event fires', async () => {+ terminalTextarea().focus()+ stop = installTerminalFocusMirror({ report })+ // Focus predates the mirror (the canvas mounts after a reload with a terminal already focused).+ // Without this initial read main would sit on its `false` until the user clicked away and back.+ expect(report.mock.calls).toEqual([[true]])+ })++ it('reports false when the window loses focus, and re-reports on regain', async () => {+ const term = terminalTextarea()+ stop = installTerminalFocusMirror({ report })+ term.focus()+ await settle()+ report.mockClear()++ // A window blur leaves `document.activeElement` on the terminal, so the ordinary read would+ // keep saying true. The fail-safe direction is "not focused" — main's intercepts belong to the+ // window that has the keyboard.+ window.dispatchEvent(new Event('blur'))+ expect(report.mock.calls).toEqual([[false]])++ // ...and coming back must re-engage. Without this leg the mirror would be stuck FALSE for a+ // terminal that still holds focus — the intercepts would keep claiming ⌘W under a user who+ // asked their terminal to have it, with no event left to correct it.+ report.mockClear()+ window.dispatchEvent(new Event('focus'))+ await settle()+ expect(report.mock.calls).toEqual([[true]])+ })++ it('the re-check does not undo a window blur', async () => {+ const term = terminalTextarea()+ stop = installTerminalFocusMirror({ report })+ term.focus()+ await settle()+ window.dispatchEvent(new Event('blur'))+ report.mockClear()++ // `document.activeElement` is STILL the terminal while the window sits in the background, so a+ // re-check that only asked the DOM would report `true` again two seconds later and make the+ // blur leg decoration. Whether this window has the keyboard is a separate fact and is tracked+ // as one.+ vi.advanceTimersByTime(TERMINAL_FOCUS_RECHECK_MS * 3)+ expect(report).not.toHaveBeenCalled()++ window.dispatchEvent(new Event('focus'))+ await settle()+ expect(report.mock.calls).toEqual([[true]])+ })++ it('recovers when the focused terminal is removed from the DOM without any focus event', async () => {+ const term = terminalTextarea()+ stop = installTerminalFocusMirror({ report })+ term.focus()+ await settle()+ report.mockClear()++ // Park / offscreen release / node delete all rip the xterm out from under a focus that may+ // still be on it. jsdom fires NOTHING here (measured), and the browsers disagree about whether+ // they fire `blur` — so the mirror may not lean on an event. Left uncorrected this is the worst+ // failure this feature has: main believes a terminal is focused forever, stands its intercepts+ // down forever, and ⌘W/⌘M go to the application MENU — closing and minimizing the window.+ term.remove()+ expect(report).not.toHaveBeenCalled() // nothing observed it yet — that is the whole problem++ vi.advanceTimersByTime(TERMINAL_FOCUS_RECHECK_MS)+ expect(report.mock.calls).toEqual([[false]])+ })++ it('the re-check is silent while nothing changed', async () => {+ terminalTextarea().focus()+ stop = installTerminalFocusMirror({ report })+ await settle()+ report.mockClear()+ vi.advanceTimersByTime(TERMINAL_FOCUS_RECHECK_MS * 5)+ // Change-deduped, so the safety net costs zero IPC in the steady state — which is what makes+ // a timer an acceptable price for closing the case above.+ expect(report).not.toHaveBeenCalled()+ })++ it('stops completely on teardown — no listeners, no timer', async () => {+ const term = terminalTextarea()+ stop = installTerminalFocusMirror({ report })+ stop()+ stop = null+ report.mockClear()++ term.focus()+ await settle()+ window.dispatchEvent(new Event('blur'))+ window.dispatchEvent(new Event('focus'))+ vi.advanceTimersByTime(TERMINAL_FOCUS_RECHECK_MS * 3)+ // A leaked listener on a remounted canvas would double-report, and a leaked interval would+ // keep a torn-down page's answer flowing to main after the mirror was supposed to be gone.+ expect(report).not.toHaveBeenCalled()+ })+})diff --git a/src/renderer/lib/terminalFocusMirror.ts b/src/renderer/lib/terminalFocusMirror.tsnew file mode 100644index 000000000..93f8d16ab--- /dev/null+++ b/src/renderer/lib/terminalFocusMirror.ts@@ -0,0 +1,133 @@+/**+ * Mirror "an xterm currently has keyboard focus" from the renderer to the main process, so the+ * window's `before-input-event` intercepts can stand down under the `terminal-first` shortcut+ * policy (`src/main/keydown-intercept.ts`).+ *+ * **Why main cannot answer this itself.** `before-input-event` fires BEFORE the page sees the key,+ * so by the time any renderer handler could look at `document.activeElement` main has already+ * decided whether to `preventDefault`. The answer has to be standing there in advance, which makes+ * it a mirror — a fact main holds a possibly-stale copy of — and every design choice below is+ * about that staleness.+ *+ * **Fail-safe direction: NOT focused.** A missing, stale or never-sent mirror must read as "no+ * terminal is focused", i.e. the intercepts stay ON and the app behaves exactly as it did before+ * this feature. The opposite direction is the expensive one: main would stand down forever, ⌘W and+ * ⌘M would go to the application MENU (close window / minimize), and no live component would be+ * left to correct it. Main enforces its half (a `false` initial value plus a reset on every way+ * the page can stop existing); this module enforces the renderer's half by never leaving a `true`+ * standing on an event that may not arrive.+ *+ * Extracted from `Canvas.tsx` rather than written inline as an effect **because the interesting+ * cases are the ones no manual test walks**: focus hopping between two terminals, a window blur,+ * and a focused terminal being torn out of the DOM by a park / offscreen release / node delete.+ * `terminalFocusMirror.test.ts` presses all three against a real (jsdom) DOM.+ */+import { isTerminalTarget, type ContextElement } from './keyContext'++/**+ * How often the mirror re-reads focus with no event to prompt it. This exists for ONE measured+ * case: removing the focused element from the document fires **no** focus event at all (jsdom+ * fires nothing; browsers disagree about whether they fire `blur`), and this app removes focused+ * xterm textareas routinely — terminal park, the offscreen release, and node deletion all do it.+ * Without a re-check that case leaves the mirror stuck on `true` permanently.+ *+ * The read is `document.activeElement` plus one `classList.contains`, and the report is+ * change-deduped, so the steady-state cost of this net is a property read per interval and zero+ * IPC. 2s is picked so a stuck `true` self-heals well inside the time it takes a user to notice a+ * terminal vanished and reach for a chord.+ */+export const TERMINAL_FOCUS_RECHECK_MS = 2000++export interface TerminalFocusMirrorOptions {+ /** Where the answer goes. Called ONLY when the answer changed — main holds a boolean, so+ * re-sending the same value is pure IPC noise on a canvas that changes focus constantly. */+ report: (focused: boolean) => void+ /** Overridable purely for tests; see the deferred read in `schedule` below. */+ recheckMs?: number+}++/**+ * Start mirroring. Returns the teardown — it removes every listener AND clears the re-check timer;+ * a leaked one of either would keep reporting from a canvas that has been replaced.+ */+export function installTerminalFocusMirror(opts: TerminalFocusMirrorOptions): () => void {+ const { report, recheckMs = TERMINAL_FOCUS_RECHECK_MS } = opts+ let last: boolean | null = null+ let stopped = false+ /**+ * Does this WINDOW have the keyboard? Tracked as its own flag because `document.activeElement`+ * does not answer it — an element keeps being the active element while the whole window sits in+ * the background, so without this the re-check below would quietly re-report `true` two seconds+ * after the blur leg pushed `false`, and the blur leg would be decoration.+ *+ * Seeded `true` rather than from `document.hasFocus()`: that answers differently across+ * environments (jsdom says `false` for a perfectly ordinary document — measured), and of the two+ * ways to be wrong at mount only one is expensive. A wrong `true` costs nothing — an unfocused+ * window receives no `before-input-event` at all, and the `focus` leg re-reads the moment it does+ * — whereas a wrong `false` would leave the policy silently dead over a terminal that is focused+ * and fires no further focus event.+ */+ let windowFocused = true++ const focusedNow = (): boolean =>+ windowFocused && isTerminalTarget(document.activeElement as unknown as ContextElement | null)++ /** Report `focused` if it differs from what main was last told. */+ const push = (focused: boolean): void => {+ if (stopped || focused === last) return+ last = focused+ report(focused)+ }++ /**+ * Read `document.activeElement` **in a microtask**, not inline.+ *+ * MEASURED (jsdom, and the same order the HTML spec prescribes): `focusout` is dispatched with+ * `activeElement` already reset to `<body>` — the incoming element is not focused yet — and the+ * matching `focusin` follows afterwards. An inline read therefore answers "no terminal" for+ * every single focus move, including terminal → terminal, so main would re-arm its intercepts+ * for the gap between the two events. A microtask scheduled from `focusout` reads the SETTLED+ * element (measured), which collapses a terminal → terminal hop into no report at all and still+ * answers `<body>` when focus genuinely went nowhere.+ */+ const readSoon = (): void => {+ queueMicrotask(() => push(focusedNow()))+ }++ const onFocusIn = (): void => readSoon()+ const onFocusOut = (): void => readSoon()+ /** The window lost the keyboard. `document.activeElement` stays on the terminal, so the answer+ * has to come from `windowFocused` — and it must be recorded there, not just pushed, or the+ * re-check would undo it on its next tick. */+ const onWindowBlur = (): void => {+ windowFocused = false+ push(focusedNow())+ }+ /** ...and the matching re-engage. Regaining window focus does not reliably fire `focusin` on the+ * element that still holds focus, so without this leg the mirror would sit stuck at `false`+ * over a focused terminal — the safe direction, but a policy that silently stopped working. */+ const onWindowFocus = (): void => {+ windowFocused = true+ readSoon()+ }++ window.addEventListener('focusin', onFocusIn)+ window.addEventListener('focusout', onFocusOut)+ window.addEventListener('blur', onWindowBlur)+ window.addEventListener('focus', onWindowFocus)+ const timer = setInterval(() => push(focusedNow()), recheckMs)++ // The state BEFORE any event: the canvas mounts after a reload with focus already somewhere, and+ // main is sitting on its `false` until told otherwise. Synchronous on purpose — this is the one+ // read with no focus transition to settle.+ push(focusedNow())++ return () => {+ stopped = true+ window.removeEventListener('focusin', onFocusIn)+ window.removeEventListener('focusout', onFocusOut)+ window.removeEventListener('blur', onWindowBlur)+ window.removeEventListener('focus', onWindowFocus)+ clearInterval(timer)+ }+}diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 09cf5ac14..9958428d3 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -75,6 +75,15 @@ export const IPC = {* 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',+ /** Renderer → main: an xterm does (`true`) / does not (`false`) currently hold keyboard focus.+ * A MIRROR, not a request: under the `terminal-first` shortcut policy the intercepts above must+ * stand down while the user is typing in a terminal, and `before-input-event` fires before any+ * renderer handler could tell main so — the answer has to already be there. Change-deduped by+ * the sender, fire-and-forget `send`, and read fail-safe: main starts at `false` and every way+ * the page can stop existing resets it there, so a stale mirror means intercepts ON (the+ * pre-policy app), never a window whose ⌘W has silently gone back to the application menu.+ * Desktop-only, for the same reason as the recording bit — the Server Edition stubs it. */+ uiTerminalFocus: 'ui:terminal-focus',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 7490c588e..50f9dcbd1 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -2496,6 +2496,15 @@ export interface ShortcutsApi {* no-op (a browser tab has no application menu to steal a chord back from, so nothing* intercepts). */setRecording(active: boolean): void+ /** Mirror whether an xterm currently holds keyboard focus, so the desktop's intercepts can stand+ * down under the `terminal-first` shortcut policy — `before-input-event` fires before any+ * renderer handler could answer, so main needs the answer in advance. Sent on CHANGE only.+ * Fire-and-forget, and **not optional**: the mirror is the only thing that makes the policy+ * reach the three main-intercepted chords. Read fail-safe on the far side (a missing or stale+ * mirror = not focused = intercepts on), so the failure mode of never sending is the app+ * behaving as it did before the policy existed. Server Edition: a documented no-op, like+ * `setRecording` — a browser tab has no application menu to steal a chord back from. */+ setTerminalFocused(focused: boolean): void}export interface NodeTerminalApi {