Skip to content

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.

fix: restore terminal keyboard focus when the window is activated

Bas Milius68c9d7a37564
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index b77cca41e..2f885aa7a 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -207,6 +207,8 @@ import {
} from '../lib/globalKeybindings'
import { isTerminalTarget, type ContextElement } from '../lib/keyContext'
import { installTerminalFocusMirror } from '../lib/terminalFocusMirror'
+import { nodeToRefocus } from '../lib/focusRestore'
+import { openDialogCount } from '../components/dialog-stack'
import {
applyWindowTitle,
composeWindowTitle,
@@ -7257,6 +7259,36 @@ export function Canvas() {
[]
)
+ // 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.
+ //
+ // 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.
+ useEffect(() => {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const onWindowFocus = () => {
+ if (timer) clearTimeout(timer)
+ timer = setTimeout(() => {
+ const target = nodeToRefocus({
+ lastNodeId: useTerminalFocus.getState().lastNodeId,
+ activeElement: document.activeElement as unknown as ContextElement | null,
+ openDialogs: openDialogCount()
+ })
+ if (target) useTerminalFocus.getState().request(target)
+ }, 0)
+ }
+ window.addEventListener('focus', onWindowFocus)
+ return () => {
+ if (timer) clearTimeout(timer)
+ window.removeEventListener('focus', onWindowFocus)
+ }
+ }, [])
+
// Active session → native window title (issue #414, opt-in `settings.windowTitleActiveSession`):
// lets window-title-based time trackers (ActivityWatch) tell sessions apart. Two latest-wins
// signals feed the active node — keyboard focus landing inside a node's DOM (the tracker), and
diff --git a/src/renderer/lib/focusRestore.test.ts b/src/renderer/lib/focusRestore.test.ts
new file mode 100644
index 000000000..a226e1242
--- /dev/null
+++ b/src/renderer/lib/focusRestore.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from 'vitest'
+import { nodeToRefocus, type FocusRestoreState } from './focusRestore'
+import { XTERM_INPUT_CLASS } from './keyContext'
+
+const el = (tagName: string, cls: string[] = [], contentEditable = false) => ({
+ tagName,
+ isContentEditable: contentEditable,
+ classList: { contains: (name: string) => cls.includes(name) }
+})
+
+const state = (over: Partial<FocusRestoreState> = {}): FocusRestoreState => ({
+ lastNodeId: 'term-1',
+ activeElement: el('BODY'),
+ openDialogs: 0,
+ ...over
+})
+
+describe('nodeToRefocus', () => {
+ it('restores the last focused terminal when nothing else owns the keyboard', () => {
+ expect(nodeToRefocus(state())).toBe('term-1')
+ })
+
+ it('restores when focus sits on a non-typing element (a button, the canvas pane)', () => {
+ expect(nodeToRefocus(state({ activeElement: el('BUTTON') }))).toBe('term-1')
+ })
+
+ it('refuses without a remembered terminal', () => {
+ expect(nodeToRefocus(state({ lastNodeId: null }))).toBeNull()
+ })
+
+ it('refuses while a modal is open', () => {
+ expect(nodeToRefocus(state({ openDialogs: 1 }))).toBeNull()
+ })
+
+ it('refuses when a terminal already has focus', () => {
+ const term = el('TEXTAREA', [XTERM_INPUT_CLASS])
+ expect(nodeToRefocus(state({ activeElement: term }))).toBeNull()
+ })
+
+ it('refuses when a text field or editor has focus', () => {
+ expect(nodeToRefocus(state({ activeElement: el('INPUT') }))).toBeNull()
+ expect(nodeToRefocus(state({ activeElement: el('TEXTAREA') }))).toBeNull()
+ expect(nodeToRefocus(state({ activeElement: el('DIV', [], true) }))).toBeNull()
+ })
+
+ it('restores when nothing at all is focused', () => {
+ expect(nodeToRefocus(state({ activeElement: null }))).toBe('term-1')
+ })
+})
diff --git a/src/renderer/lib/focusRestore.ts b/src/renderer/lib/focusRestore.ts
new file mode 100644
index 000000000..78be3af7e
--- /dev/null
+++ b/src/renderer/lib/focusRestore.ts
@@ -0,0 +1,44 @@
+/**
+ * Which terminal (if any) should take the keyboard back when the window is activated again.
+ *
+ * Issue #557. Terminal focus in this app is pointer-driven: `TerminalNode`'s hover guard focuses
+ * xterm on a dwell or a click and BLURS it again on `mouseleave`. On a multi-monitor desk the
+ * pointer routinely leaves the node on its way to another display, so by the time the user
+ * Cmd+Tabs away the terminal has already lost focus, and coming back there is no pointer event
+ * left to hand it over. `document.activeElement` is `<body>`, the guard is armed again, and the
+ * next keystroke goes to the global dispatcher, where a bare Backspace is `canvas.deleteSelection`
+ * and opens the delete-node confirm over a terminal the user believed they were typing into.
+ *
+ * The decision is pure so the interesting refusals are testable without a window that can be
+ * activated: this runs on window activation, where reading the DOM by hand proves very little.
+ */
+import { isTerminalTarget, isTypingTarget, type ContextElement } from './keyContext'
+
+export interface FocusRestoreState {
+ /** The last terminal that held the keyboard (`useTerminalFocus.lastNodeId`). */
+ lastNodeId: string | null
+ /** Who holds focus at the moment the window came back. */
+ activeElement: ContextElement | null
+ /** How many modals are open (`openDialogCount()`). */
+ openDialogs: number
+}
+
+/**
+ * The node to hand the keyboard to, or `null` to leave focus exactly where the browser put it.
+ *
+ * Every refusal is "something else is already owning, or about to own, the keyboard":
+ * - **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 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.
+ * - **A terminal already has focus**: the pointer never left, so nothing was lost. Restoring
+ * 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
+ return lastNodeId
+}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index c665743fe..ec114e41a 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -4342,6 +4342,7 @@ export function TerminalNode({
if (dwellRef.current) clearTimeout(dwellRef.current)
setArmed(false)
termRef.current?.focus()
+ useTerminalFocus.getState().remember(id)
useAgentStatus.getState().setActive(id, true)
useAgentStatus.getState().clearUnread(id)
presence.reportFocus(id)
@@ -4374,6 +4375,7 @@ export function TerminalNode({
}
setArmed(false)
termRef.current?.focus()
+ useTerminalFocus.getState().remember(id)
useAgentStatus.getState().setActive(id, true)
useAgentStatus.getState().clearUnread(id)
// "I am working in this node" — the same signal the agent-status active flag uses, i.e. the
@@ -4494,6 +4496,7 @@ export function TerminalNode({
// A paste came from THIS window, which already has it.
if (opts.raiseWindow) window.nodeTerminal.focusWindow()
term.focus()
+ useTerminalFocus.getState().remember(id)
term.paste(paths.join(' ') + ' ')
useAgentStatus.getState().setActive(id, true)
presence.reportFocus(id)
diff --git a/src/renderer/state/terminalFocus.test.ts b/src/renderer/state/terminalFocus.test.ts
index 97997d1a5..c0b3d3422 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 }))
+afterEach(() => useTerminalFocus.setState({ nodeId: null, nonce: 0, lastNodeId: null }))
describe('useTerminalFocus', () => {
it('records the requested node and bumps the nonce each time', () => {
@@ -25,4 +25,13 @@ describe('useTerminalFocus', () => {
expect(useTerminalFocus.getState().nodeId).toBeNull()
// The nonce is untouched, so no node's `s.nodeId === id ? s.nonce : 0` selector fires again.
})
+
+ it('remembers the last focused terminal and keeps it across a one-shot request', () => {
+ useTerminalFocus.getState().remember('node-a')
+ expect(useTerminalFocus.getState().lastNodeId).toBe('node-a')
+ useTerminalFocus.getState().request('node-a')
+ useTerminalFocus.setState({ nodeId: null })
+ // The consume clears the REQUEST, never the memory the window-activation restore reads.
+ expect(useTerminalFocus.getState().lastNodeId).toBe('node-a')
+ })
})
diff --git a/src/renderer/state/terminalFocus.ts b/src/renderer/state/terminalFocus.ts
index 6d6244d12..80c808401 100644
--- a/src/renderer/state/terminalFocus.ts
+++ b/src/renderer/state/terminalFocus.ts
@@ -17,10 +17,25 @@ export const useTerminalFocus = create<{
nodeId: string | null
/** Bumped on every request so re-requesting the same node still fires a subscriber effect. */
nonce: number
+ /**
+ * The last terminal that actually took the keyboard, kept AFTER it lost focus again.
+ *
+ * This is the memory the window-activation restore reads (`lib/focusRestore.ts`). It must
+ * deliberately survive a blur: the case it exists for is a pointer that left the node (a second
+ * display, issue #557), which blurs the terminal through `onBodyLeave`, followed by a Cmd+Tab
+ * 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`.
+ */
+ lastNodeId: string | null
/** Ask a node's terminal to take the keyboard now. */
request(nodeId: string): void
+ /** Record that this node's terminal has the keyboard (called where it takes focus). */
+ remember(nodeId: string): void
}>((set) => ({
nodeId: null,
nonce: 0,
- request: (nodeId) => set((s) => ({ nodeId, nonce: s.nonce + 1 }))
+ lastNodeId: null,
+ request: (nodeId) => set((s) => ({ nodeId, nonce: s.nonce + 1 })),
+ remember: (nodeId) => set({ lastNodeId: nodeId })
}))