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
fix: refuse the focus restore under full-page surfaces, and drop its ACK
Bas Milius7df1a7c8c095
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 2f885aa7a..328b47b38 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -7259,16 +7259,24 @@ export function Canvas() {[])+ // The settings page is React state, and the listener below is registered once — so it reads the+ // flag through a ref rather than taking a dep and re-registering on every open/close.+ const settingsOpenRef = useRef(settingsOpen)+ settingsOpenRef.current = settingsOpen+// Cmd+Tab back into the app: hand the keyboard to the terminal that last had it (issue #557).// Terminal focus is pointer-driven (the hover guard blurs xterm on `mouseleave`), so a pointer// parked on a second display leaves the app with NO terminal focused, and returning gives the// canvas dispatcher every keystroke, where a bare Backspace is `canvas.deleteSelection`. The- // refusals (a modal is open, a text surface or a terminal already holds focus) are the pure- // `nodeToRefocus`; this effect is the DOM read plus the request.+ // refusals (a modal, the board or the settings page is up, a text surface or a terminal already+ // holds focus) are the pure `nodeToRefocus`; this effect is the DOM read plus the request.//// Deferred by a macrotask rather than read inline: Chromium restores its own previously focused// element around window activation, and deciding before it has settled would read `<body>` and// steal focus from the settings field the user actually left the app from.+ //+ // `{ ack: false }`: coming back to the window is not evidence that the user has SEEN the node,+ // and the ACK reaches past this machine (the notch capsule and the paired phone's Live Activity).useEffect(() => {let timer: ReturnType<typeof setTimeout> | undefinedconst onWindowFocus = () => {@@ -7277,9 +7285,13 @@ export function Canvas() {const target = nodeToRefocus({lastNodeId: useTerminalFocus.getState().lastNodeId,activeElement: document.activeElement as unknown as ContextElement | null,- openDialogs: openDialogCount()+ openDialogs: openDialogCount(),+ boardOpen: isKanbanOpen(useProjects.getState().activeProjectId),+ settingsOpen: settingsOpenRef.current})- if (target) useTerminalFocus.getState().request(target)+ if (target) {+ useTerminalFocus.getState().request(target, { ack: false })+ }}, 0)}window.addEventListener('focus', onWindowFocus)diff --git a/src/renderer/lib/focusRestore.test.ts b/src/renderer/lib/focusRestore.test.tsindex a226e1242..258ab9d6b 100644--- a/src/renderer/lib/focusRestore.test.ts+++ b/src/renderer/lib/focusRestore.test.ts@@ -12,6 +12,8 @@ const state = (over: Partial<FocusRestoreState> = {}): FocusRestoreState => ({lastNodeId: 'term-1',activeElement: el('BODY'),openDialogs: 0,+ boardOpen: false,+ settingsOpen: false,...over})@@ -32,6 +34,18 @@ describe('nodeToRefocus', () => {expect(nodeToRefocus(state({ openDialogs: 1 }))).toBeNull()})+ it('refuses while the kanban board is up', () => {+ // The board is an opaque overlay over a still-mounted canvas and registers no dialog, so the+ // restore would aim the keyboard at a terminal the user cannot see.+ expect(nodeToRefocus(state({ boardOpen: true }))).toBeNull()+ })++ it('refuses while the settings page is up', () => {+ // Same shape as the board: a full-page surface outside the dialog stack, and its fields are+ // only covered by the typing refusal once one of them actually has focus.+ expect(nodeToRefocus(state({ settingsOpen: true }))).toBeNull()+ })+it('refuses when a terminal already has focus', () => {const term = el('TEXTAREA', [XTERM_INPUT_CLASS])expect(nodeToRefocus(state({ activeElement: term }))).toBeNull()diff --git a/src/renderer/lib/focusRestore.ts b/src/renderer/lib/focusRestore.tsindex 78be3af7e..10b44ae93 100644--- a/src/renderer/lib/focusRestore.ts+++ b/src/renderer/lib/focusRestore.ts@@ -21,6 +21,15 @@ export interface FocusRestoreState {activeElement: ContextElement | null/** How many modals are open (`openDialogCount()`). */openDialogs: number+ /**+ * The kanban board is up for the active project (`isKanbanOpen`).+ *+ * The board is NOT in the dialog stack, so `openDialogs` cannot see it. A full-page surface+ * that covers the canvas without registering there owes a field of its own here.+ */+ boardOpen: boolean+ /** The settings page is up. Also outside the dialog stack, for the same reason as `boardOpen`. */+ settingsOpen: boolean}/**@@ -30,6 +39,11 @@ export interface FocusRestoreState {* - **A modal is open**: a confirm, the card modal (whose own terminal focuses itself), a prompt.* Stealing focus out from under one is worse than the bug this fixes, and `openDialogCount`* already answers it for every modal in the app (they all register in the dialog stack).+ * - **A full-page surface is up**: the kanban board and the settings page both paint an OPAQUE+ * layer over a still-mounted canvas, and neither registers in the dialog stack. Restoring under+ * one aims the keyboard at a terminal the user cannot see, which is the same hazard the modal+ * refusal exists for and worse than the bug: they are looking at the board and typing into a+ * pane somewhere behind it.* - **A typing surface has focus**: a settings field, a sticky's textarea, Monaco. Chromium* restores the previously focused element on activation, so this is the ordinary case of the* user having left the app from a text field; it is not ours to override.@@ -37,8 +51,15 @@ export interface FocusRestoreState {* would be a no-op at best and could move focus to a DIFFERENT node at worst.*/export function nodeToRefocus(state: FocusRestoreState): string | null {- const { lastNodeId, activeElement, openDialogs } = state- if (!lastNodeId || openDialogs > 0) return null- if (isTerminalTarget(activeElement) || isTypingTarget(activeElement)) return null+ const { lastNodeId, activeElement, openDialogs, boardOpen, settingsOpen } = state+ if (!lastNodeId || openDialogs > 0) {+ return null+ }+ if (boardOpen || settingsOpen) {+ return null+ }+ if (isTerminalTarget(activeElement) || isTypingTarget(activeElement)) {+ return null+ }return lastNodeId}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex ec114e41a..fc5626d99 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -4337,14 +4337,20 @@ export function TerminalNode({* Take the keyboard: leave the guard, focus xterm, and report the node active.** Split out of `onBodyEnter` so a deliberate CLICK can run it with no delay — see `onGuardUp`.+ *+ * `ack` (default true) also marks the node's finish read. Every gesture that reaches here aims+ * at THIS node — a dwell, a click, a sidebar or notification jump — so the read is real. The one+ * caller that passes false is the window-activation restore, which nobody aimed at anything.*/- const enterNow = () => {+ const enterNow = (opts?: { ack?: boolean }) => {if (dwellRef.current) clearTimeout(dwellRef.current)setArmed(false)termRef.current?.focus()useTerminalFocus.getState().remember(id)useAgentStatus.getState().setActive(id, true)- useAgentStatus.getState().clearUnread(id)+ if (opts?.ack !== false) {+ useAgentStatus.getState().clearUnread(id)+ }presence.reportFocus(id)}@@ -4359,8 +4365,9 @@ export function TerminalNode({useEffect(() => {if (focusReq === 0 || focusReq === lastFocusReqRef.current) returnlastFocusReqRef.current = focusReq+ const { ack } = useTerminalFocus.getState()useTerminalFocus.setState({ nodeId: null })- enterNow()+ enterNow({ ack })// enterNow closes over live refs/setters; re-running on its identity would fire spuriously.// eslint-disable-next-line react-hooks/exhaustive-deps}, [focusReq])diff --git a/src/renderer/state/terminalFocus.test.ts b/src/renderer/state/terminalFocus.test.tsindex c0b3d3422..dd80003da 100644--- a/src/renderer/state/terminalFocus.test.ts+++ b/src/renderer/state/terminalFocus.test.ts@@ -1,7 +1,7 @@import { afterEach, describe, expect, it } from 'vitest'import { useTerminalFocus } from './terminalFocus'-afterEach(() => useTerminalFocus.setState({ nodeId: null, nonce: 0, lastNodeId: null }))+afterEach(() => useTerminalFocus.setState({ nodeId: null, nonce: 0, ack: true, lastNodeId: null }))describe('useTerminalFocus', () => {it('records the requested node and bumps the nonce each time', () => {@@ -34,4 +34,15 @@ describe('useTerminalFocus', () => {// The consume clears the REQUEST, never the memory the window-activation restore reads.expect(useTerminalFocus.getState().lastNodeId).toBe('node-a')})++ it('acks by default and only skips the ack when the caller asks', () => {+ useTerminalFocus.getState().request('node-a')+ expect(useTerminalFocus.getState().ack).toBe(true)+ useTerminalFocus.getState().request('node-a', { ack: false })+ expect(useTerminalFocus.getState().ack).toBe(false)+ // A later request that says nothing acks again, so one silent restore cannot mute the next+ // deliberate jump to the same node.+ useTerminalFocus.getState().request('node-a')+ expect(useTerminalFocus.getState().ack).toBe(true)+ })})diff --git a/src/renderer/state/terminalFocus.ts b/src/renderer/state/terminalFocus.tsindex 80c808401..e667478a1 100644--- a/src/renderer/state/terminalFocus.ts+++ b/src/renderer/state/terminalFocus.ts@@ -17,6 +17,13 @@ export const useTerminalFocus = create<{nodeId: string | null/** Bumped on every request so re-requesting the same node still fires a subscriber effect. */nonce: number+ /**+ * Whether consuming the pending request should also ACK the node's finish. See `request`.+ *+ * Carried on the request rather than decided by the consumer, because only the CALLER knows+ * whether a human aimed at this node.+ */+ ack: boolean/*** The last terminal that actually took the keyboard, kept AFTER it lost focus again.*@@ -26,16 +33,32 @@ export const useTerminalFocus = create<{* out and back, where no pointer event is left to hand the keyboard over again. Clearing it on* blur would forget exactly the terminal we want back. It is never cleared explicitly: a node* that is gone or unmounted simply misses the request, the same fail-open as `request`.+ *+ * It therefore also survives a PROJECT SWITCH, so the remembered node can belong to another+ * project. That fails open today because the request is consumed by a mounted `TerminalNode`+ * and the node of an inactive project is unmounted. Load-bearing: a change that starts routing+ * a focus request across projects (switching to the node's project first, as `focusNodeById`+ * does) has to clear or qualify this, or a window activation would yank the user out of the+ * project they are looking at.*/lastNodeId: string | null- /** Ask a node's terminal to take the keyboard now. */- request(nodeId: string): void+ /**+ * Ask a node's terminal to take the keyboard now.+ *+ * `ack` (default true) also marks the node's finish read, everywhere: `clearUnread` calls+ * `ackDone`, which resolves the notch capsule's blob and the paired phone's DONE Live Activity+ * and Inbox card. That is right for a request a human aimed at a node (a sidebar click, a+ * notification tap, ⌘K) and wrong for one the app raised on its own, so the window-activation+ * restore passes `{ ack: false }`.+ */+ request(nodeId: string, opts?: { ack?: boolean }): void/** Record that this node's terminal has the keyboard (called where it takes focus). */remember(nodeId: string): void}>((set) => ({nodeId: null,nonce: 0,+ ack: true,lastNodeId: null,- request: (nodeId) => set((s) => ({ nodeId, nonce: s.nonce + 1 })),+ request: (nodeId, opts) => set((s) => ({ nodeId, nonce: s.nonce + 1, ack: opts?.ack !== false })),remember: (nodeId) => set({ lastNodeId: nodeId })}))