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.

feat(canvas): opt-in click-to-focus for terminal nodes (#757)

Erik Zwep96772d700c29
diff --git a/CLAUDE.md b/CLAUDE.md
index 7a11ead8b..f35b3a026 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1261,6 +1261,18 @@ session.
- The xterm container is `nodrag nowheel`; a transparent **hover-guard** overlay sits on top
until you dwell `settings.panHoverDelay` (so quick drag = move node, scroll = pan). After
the dwell the guard is removed and xterm takes input. The header stays draggable.
+- **Click to focus** (`settings.terminalFocusFollowsPointer`, default ON = the dwell above; issue
+ #757, Settings → Behavior). Off, the pointer decides nothing: no dwell, and `mouseleave` no
+ longer blurs, re-arms or releases. A click (`onGuardUp` → `enterNow`) or a "go to node" takes the
+ keyboard, and the node's active flag, presence focus AND guard then follow DOM focus through a
+ `focusin`/`focusout` listener on the node root (`lib/terminalFocusMode.ts` `focusLossOutcome`):
+ focus moving inside the node or the WINDOW blurring (Cmd+Tab) keeps it, a press on the node's own
+ chrome (header drag — React Flow focuses its wrapper) hands it back to the xterm, anything else —
+ another node, a field, the empty canvas (`onPaneClick` blurs the xterm textarea,
+ `shouldReleasePaneFocus`) — releases it and re-arms the guard. Only a literal `false` in
+ settings.json selects it (`resolveFocusFollowsPointer`). The ⌘/ shortcuts panel prints "Click" instead of
+ the dwell. Renderer only: Desktop + Server Edition identical; kanban card modal N/A (it has no
+ hover guard); Mobile N/A.
- **Where the wheel stops being the terminal's is decided by HIT TEST, per packet** — `Canvas.tsx`
answers `overNativeScrollable` with `target?.closest('.nowheel')`, and React Flow's own
`panOnScroll` walks the same class (`noWheelClassName`). Two consequences, and issue #767 reported
diff --git a/src/renderer/components/ShortcutsPanel.test.tsx b/src/renderer/components/ShortcutsPanel.test.tsx
index 1fe745b0d..8abdac1c8 100644
--- a/src/renderer/components/ShortcutsPanel.test.tsx
+++ b/src/renderer/components/ShortcutsPanel.test.tsx
@@ -21,7 +21,8 @@ const BASE: Omit<ShortcutSectionsOptions, 'bindingsFor'> = {
panHoverDelay: DEFAULT_SETTINGS.panHoverDelay,
dragMode: 'select',
doubleClickFocus: true,
- wheelZoom: false
+ wheelZoom: false,
+ focusFollowsPointer: true
}
const build = (
@@ -190,6 +191,16 @@ describe('buildShortcutSections — platform and non-command rows', () => {
.toEqual(['Hover 0.6s'])
})
+ it('says "click" instead of a hover dwell when focus does not follow the pointer (#757)', () => {
+ // Click-to-focus: no dwell ever hands over the keyboard, so printing "Hover 0.6s" would
+ // advertise a gesture that does nothing.
+ const click = build(() => [], { focusFollowsPointer: false, panHoverDelay: 600 })
+ expect(rowFor(click, 'Enter the terminal (type / select)')).toEqual(['Click'])
+ expect(rowFor(click, 'Move the terminal (before it focuses)')).toEqual(['Drag'])
+ const hover = build(() => [], { focusFollowsPointer: true, panHoverDelay: 600 })
+ expect(rowFor(hover, 'Move the terminal (before it focuses)')).toEqual(['Quick drag'])
+ })
+
it('names the force-select modifier per platform (Option on mac, Shift elsewhere)', () => {
const label = 'Select in the emulator (apps that grab the mouse)'
expect(rowFor(build(() => [], { isMac: true }), label)).toEqual(['⌥', 'drag'])
diff --git a/src/renderer/components/ShortcutsPanel.tsx b/src/renderer/components/ShortcutsPanel.tsx
index f3c5605b8..30a929747 100644
--- a/src/renderer/components/ShortcutsPanel.tsx
+++ b/src/renderer/components/ShortcutsPanel.tsx
@@ -20,7 +20,8 @@
* the two zoom chords (`lib/zoomShortcut.ts`), the ⌘1-9 project jump (`lib/projectJump.ts`) and
* the terminal's own behaviors. They are literal because the registry does not know them — but
* they are still DERIVED from settings wherever the behavior is: the hover dwell prints
- * `settings.panHoverDelay`, and the drag rows follow `settings.canvasDragMode`, because the panel
+ * `settings.panHoverDelay` (or "Click" when `settings.terminalFocusFollowsPointer` is off, #757),
+ * and the drag rows follow `settings.canvasDragMode`, because the panel
* used to claim a fixed 0.6 s and a right-drag pan that React Flow (`panOnDrag={[1]}` — middle
* button only) has never done.
*
@@ -44,6 +45,7 @@ import { isMacPlatform, keyLabel } from '@shared/platform-utils'
import { isBrowserRuntime } from '../bridge/runtime'
import { effectiveBindings } from '../lib/keybindingOverrides'
import { useSettings } from '../state/settings'
+import { resolveFocusFollowsPointer } from '../lib/terminalFocusMode'
import { IconClose } from './icons'
export interface ShortcutsPanelProps {
@@ -81,6 +83,9 @@ export interface ShortcutSectionsOptions {
doubleClickFocus: boolean
/** `settings.wheelZoom` — a plain wheel zooms too. */
wheelZoom: boolean
+ /** `settings.terminalFocusFollowsPointer` (issue #757). Off = click to focus: no hover dwell
+ * ever takes the keyboard, so the dwell row would advertise a gesture that does nothing. */
+ focusFollowsPointer: boolean
/** Canonical effective binding strings for a command; `[]` when unbound or disabled. */
bindingsFor: (id: CommandId) => readonly string[]
}
@@ -147,14 +152,19 @@ function extraRows(group: CommandGroup, o: ShortcutSectionsOptions): ShortcutRow
}
/** Terminal facts the registry knows nothing about: tmux owns the mouse, xterm owns two remaps,
- * and the hover guard owns the first ~half second. Each verified against the code that
+ * and the hover guard owns the first ~half second (or, in click-to-focus mode, everything until
+ * the first click). Each verified against the code that
* implements it (see CLAUDE.md "tmux owns the mouse" and terminal/terminal-config.ts). */
function behaviorRows(o: ShortcutSectionsOptions): ShortcutRow[] {
const seconds = Math.round(o.panHoverDelay / 100) / 10
const forceSelect = o.isMac ? '⌥' : 'Shift'
+ // Click to focus (#757): the terminal takes the keyboard on a click and keeps it until you click
+ // elsewhere, so ANY drag over an unfocused terminal moves it — there is no "quick" window.
+ const enter = o.focusFollowsPointer ? [`Hover ${seconds}s`] : ['Click']
+ const move = o.focusFollowsPointer ? ['Quick drag'] : ['Drag']
return [
- row([`Hover ${seconds}s`], 'Enter the terminal (type / select)'),
- row(['Quick drag'], 'Move the terminal (before it focuses)'),
+ row(enter, 'Enter the terminal (type / select)'),
+ row(move, 'Move the terminal (before it focuses)'),
row(['Wheel'], "Scroll tmux's own history"),
row(['Drag'], 'Select — copies to the system clipboard'),
row([forceSelect, 'drag'], 'Select in the emulator (apps that grab the mouse)'),
@@ -213,6 +223,9 @@ export function ShortcutsPanel({ onClose, onCustomize }: ShortcutsPanelProps) {
const dragMode = useSettings((s) => s.settings.canvasDragMode)
const doubleClickFocus = useSettings((s) => s.settings.doubleClickFocus)
const wheelZoom = useSettings((s) => s.settings.wheelZoom)
+ const focusFollowsPointer = resolveFocusFollowsPointer(
+ useSettings((s) => s.settings.terminalFocusFollowsPointer)
+ )
const isMac = isMacPlatform()
const sections = buildShortcutSections({
isMac,
@@ -221,6 +234,7 @@ export function ShortcutsPanel({ onClose, onCustomize }: ShortcutsPanelProps) {
dragMode: dragMode === 'pan' ? 'pan' : 'select',
doubleClickFocus,
wheelZoom,
+ focusFollowsPointer,
bindingsFor: effectiveBindings
})
diff --git a/src/renderer/components/settings/sections/BehaviorSection.tsx b/src/renderer/components/settings/sections/BehaviorSection.tsx
index 88de51467..b1d9308d8 100644
--- a/src/renderer/components/settings/sections/BehaviorSection.tsx
+++ b/src/renderer/components/settings/sections/BehaviorSection.tsx
@@ -35,6 +35,10 @@ const ROWS = {
keywords: ['snap', 'grid', 'align', 'arrange', 'auto', 'mode']
},
panHover: { title: 'Pan-hover delay (ms)', keywords: ['pan', 'hover', 'delay', 'focus', 'guard'] },
+ focusFollowsPointer: {
+ title: 'Terminal focus follows pointer',
+ keywords: ['focus', 'hover', 'pointer', 'click', 'follows', 'x11', 'mouse', 'keyboard', 'terminal', 'mac']
+ },
doubleClick: { title: 'Double-click to focus', keywords: ['double', 'click', 'focus'] },
focusZoom: {
title: 'Zoom when going to a node',
@@ -198,9 +202,31 @@ export function BehaviorSection({ isActive }: { isActive: boolean }): React.JSX.
}
/>
</SearchableRow>
+ <SearchableRow {...ROWS.focusFollowsPointer}>
+ <FieldRow
+ label="Terminal focus follows pointer"
+ description={
+ settings.terminalFocusFollowsPointer
+ ? 'On: hovering a terminal for the pan-hover delay gives it the keyboard, and moving the pointer off it takes the keyboard away. Turn off for click to focus.'
+ : 'Off (click to focus): click a terminal to type in it. It keeps the keyboard until you click another node, the empty canvas or a field — moving the pointer away changes nothing.'
+ }
+ control={
+ <Switch
+ checked={settings.terminalFocusFollowsPointer}
+ onChange={(v) => update({ terminalFocusFollowsPointer: v })}
+ ariaLabel="Terminal focus follows pointer"
+ />
+ }
+ />
+ </SearchableRow>
<SearchableRow {...ROWS.panHover}>
<FieldRow
label="Pan-hover delay (ms)"
+ description={
+ settings.terminalFocusFollowsPointer
+ ? undefined
+ : 'Not used in click-to-focus mode (Terminal focus follows pointer is off): hovering never takes the keyboard.'
+ }
control={
<NumberField
value={settings.panHoverDelay}
diff --git a/src/renderer/lib/paneFocus.test.ts b/src/renderer/lib/paneFocus.test.ts
index 7a116d5b2..a2b54391b 100644
--- a/src/renderer/lib/paneFocus.test.ts
+++ b/src/renderer/lib/paneFocus.test.ts
@@ -26,6 +26,15 @@ describe('shouldReleasePaneFocus', () => {
expect(shouldReleasePaneFocus(monacoInput)).toBe(true)
})
+ it("releases a focused terminal's xterm textarea, which click to focus relies on (#757)", () => {
+ // With focus-follows-pointer off, a terminal keeps the keyboard until the user clicks
+ // elsewhere; a click on the empty canvas is one of those "elsewhere"s, and xterm's input is a
+ // hidden <textarea class="xterm-helper-textarea">. If this ever stopped answering true for it,
+ // the canvas could no longer take the keyboard back from a terminal in that mode.
+ const xtermInput = { tagName: 'TEXTAREA', isContentEditable: false, className: 'xterm-helper-textarea' }
+ expect(shouldReleasePaneFocus(xtermInput as unknown as Element)).toBe(true)
+ })
+
it('leaves anything else alone', () => {
// Blurring a focused button or node div would fight the browser's own focus handling for no
// gain: neither of them eats a keystroke.
diff --git a/src/renderer/lib/terminalFocusMode.test.ts b/src/renderer/lib/terminalFocusMode.test.ts
new file mode 100644
index 000000000..3959b48fa
--- /dev/null
+++ b/src/renderer/lib/terminalFocusMode.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'fs'
+import { join } from 'path'
+import { DEFAULT_SETTINGS } from '@shared/types'
+import {
+ focusLossOutcome,
+ hoverTakesKeyboard,
+ pointerLeaveReleases,
+ resolveFocusFollowsPointer
+} from './terminalFocusMode'
+
+/**
+ * Issue #757 — "option to disable X Window focus-follows-pointer (Mac-style click to select what
+ * UI element has the input focus)". A terminal node's keyboard used to follow the POINTER: a hover
+ * dwell took it, leaving the node took it away. `settings.terminalFocusFollowsPointer` keeps that
+ * (the default) or switches to click-to-focus, where the pointer decides nothing and the clicked
+ * terminal keeps the keyboard until the user clicks somewhere else.
+ */
+describe('terminal focus mode (#757)', () => {
+ it('defaults to focus-follows-pointer, so nobody’s terminal changes behaviour on upgrade', () => {
+ expect(DEFAULT_SETTINGS.terminalFocusFollowsPointer).toBe(true)
+ })
+
+ describe('resolveFocusFollowsPointer', () => {
+ it('switches to click to focus only on a literal false', () => {
+ expect(resolveFocusFollowsPointer(false)).toBe(false)
+ expect(resolveFocusFollowsPointer(true)).toBe(true)
+ // settings.json is hand-editable: a mangled value keeps the default, never flips the mode.
+ expect(resolveFocusFollowsPointer(undefined)).toBe(true)
+ expect(resolveFocusFollowsPointer('false')).toBe(true)
+ expect(resolveFocusFollowsPointer(null)).toBe(true)
+ })
+ })
+
+ describe('hoverTakesKeyboard', () => {
+ it('lets a hover dwell take the keyboard only while focus follows the pointer', () => {
+ expect(hoverTakesKeyboard(true)).toBe(true)
+ expect(hoverTakesKeyboard(false)).toBe(false)
+ })
+ })
+
+ describe('pointerLeaveReleases', () => {
+ it('takes the keyboard away on mouseleave only while focus follows the pointer', () => {
+ expect(pointerLeaveReleases(true)).toBe(true)
+ // Click-to-focus: the pointer wandering to another card, the canvas or a second display
+ // must leave the typed-into terminal exactly as it is.
+ expect(pointerLeaveReleases(false)).toBe(false)
+ })
+ })
+
+ describe('focusLossOutcome', () => {
+ // Plain objects stand in for DOM nodes: all the helper asks of `nodeRoot` is `contains`.
+ const lost = { id: 'xterm-textarea' }
+ const header = { id: 'rename-input' }
+ const elsewhere = { id: 'other-node-textarea' }
+ const ownWrapper = { id: 'react-flow-node-wrapper' }
+ const body = { id: 'body' }
+ const nodeRoot = { contains: (n: unknown) => n === lost || n === header }
+ const ev = (over: Partial<Parameters<typeof focusLossOutcome>[0]>) =>
+ focusLossOutcome({
+ nodeRoot,
+ lost,
+ gained: null,
+ activeElement: body,
+ windowFocused: true,
+ pressedInOwnNode: false,
+ ...over
+ })
+
+ it('releases when focus moved to something outside the node (another card, a field)', () => {
+ expect(ev({ gained: elsewhere, activeElement: elsewhere })).toBe('release')
+ })
+
+ it('releases when a click sent focus nowhere (the empty canvas blurs the xterm, #86)', () => {
+ expect(ev({ gained: null, activeElement: body })).toBe('release')
+ })
+
+ it('keeps it when focus only moved inside the same node (header field, ⌘M composer)', () => {
+ expect(ev({ gained: header, activeElement: header })).toBe('keep')
+ // …even when the press that moved it was on this node.
+ expect(ev({ gained: header, activeElement: header, pressedInOwnNode: true })).toBe('keep')
+ })
+
+ it('reclaims the keyboard when the user pressed this node’s own chrome (header drag)', () => {
+ // The wrapper is focusable in React Flow, so a header press moves focus to it — outside
+ // `.term-node`, where the next Backspace would be the canvas's delete-selection.
+ expect(ev({ gained: ownWrapper, activeElement: ownWrapper, pressedInOwnNode: true })).toBe('reclaim')
+ // A non-focusable wrapper sends focus to <body> instead; same press, same answer.
+ expect(ev({ gained: null, activeElement: body, pressedInOwnNode: true })).toBe('reclaim')
+ })
+
+ it('keeps it when the WINDOW lost focus (Cmd+Tab away): the terminal still owns the keyboard', () => {
+ // Chromium fires blur/focusout on the focused element when the window deactivates, but the
+ // element stays `document.activeElement` and gets focus back on return. Releasing here would
+ // drop the node's active flag on every app switch.
+ expect(ev({ activeElement: lost, windowFocused: false })).toBe('keep')
+ expect(ev({ activeElement: lost, windowFocused: true })).toBe('keep')
+ expect(ev({ activeElement: body, windowFocused: false })).toBe('keep')
+ })
+
+ it('answers keep without a node root (unmounted mid-event) rather than guessing', () => {
+ expect(ev({ nodeRoot: null })).toBe('keep')
+ })
+ })
+
+ // The decisions above are only worth something if the node and the settings page use them. A
+ // source check, like `focusRestore.test.ts`: TerminalNode cannot be mounted without an xterm.
+ describe('wiring', () => {
+ const read = (rel: string) => readFileSync(join(process.cwd(), rel), 'utf8')
+
+ it('TerminalNode reads the setting live and routes hover, leave and focus loss through it', () => {
+ const src = read('src/renderer/nodes/TerminalNode.tsx')
+ expect(src).toContain('useSettings((s) => s.settings.terminalFocusFollowsPointer)')
+ expect(src).toContain('hoverTakesKeyboard(focusFollowsPointer)')
+ expect(src).toContain('pointerLeaveReleases(focusFollowsPointer)')
+ expect(src).toContain('focusLossOutcome(')
+ })
+
+ it('Settings → Behavior offers the toggle, findable by search', () => {
+ const src = read('src/renderer/components/settings/sections/BehaviorSection.tsx')
+ expect(src).toContain('update({ terminalFocusFollowsPointer: v })')
+ for (const k of ['focus', 'hover', 'pointer', 'click', 'follows', 'x11']) {
+ expect(src).toMatch(new RegExp(`focusFollowsPointer: \\{[^}]*'${k}'`))
+ }
+ })
+ })
+})
diff --git a/src/renderer/lib/terminalFocusMode.ts b/src/renderer/lib/terminalFocusMode.ts
new file mode 100644
index 000000000..13c0747bd
--- /dev/null
+++ b/src/renderer/lib/terminalFocusMode.ts
@@ -0,0 +1,105 @@
+/**
+ * Who decides which terminal node holds the keyboard: the POINTER, or a CLICK.
+ *
+ * Issue #757 — "option to disable X Window focus-follows-pointer (Mac-style click to select what
+ * UI element has the input focus)". `TerminalNode`'s hover guard has always tied the keyboard to
+ * the pointer: dwelling `settings.panHoverDelay` over a terminal focuses its xterm, and
+ * `mouseleave` blurs it again and drops the node's agent-status active flag and presence focus. On
+ * a crowded canvas that is the X11 "focus follows mouse" model, and a user who reaches for another
+ * card, a second display or the sidebar while an agent is mid-prompt loses the keyboard every time.
+ *
+ * `settings.terminalFocusFollowsPointer` (default ON — the long-standing behaviour) picks the model:
+ *
+ * - **ON — focus follows the pointer.** Unchanged: hover dwell takes the keyboard, leaving the
+ * node gives it back.
+ * - **OFF — click to focus.** The pointer decides nothing. A click on the terminal (the guard's
+ * `onGuardUp` → `enterNow`, issue #87) or a "go to node" request takes the keyboard, and the
+ * terminal KEEPS it until focus really goes somewhere else: another node, the empty canvas
+ * (whose `onPaneClick` blurs the xterm textarea, issue #86), a text field. The node's active
+ * flag, presence focus and hover guard then follow that DOM focus instead of the pointer — see
+ * `focusLossOutcome`.
+ *
+ * Pure so the decisions are testable without a mounted xterm; `TerminalNode` owns the effects.
+ */
+
+/**
+ * The setting as read from a hand-editable settings.json: only a literal `false` switches to click
+ * to focus. Anything else (absent, a string, null) keeps the long-standing default, so a mangled
+ * file can never silently change how every terminal takes the keyboard.
+ */
+export function resolveFocusFollowsPointer(value: unknown): boolean {
+ return value !== false
+}
+
+/** Does a hover dwell over the body hand the keyboard to the terminal? */
+export function hoverTakesKeyboard(focusFollowsPointer: boolean): boolean {
+ return focusFollowsPointer
+}
+
+/**
+ * Does the pointer leaving the body take the keyboard away (blur the xterm, re-arm the guard,
+ * drop the active flag and presence focus)? Click-to-focus leaves all of that to `focusLossOutcome`.
+ */
+export function pointerLeaveReleases(focusFollowsPointer: boolean): boolean {
+ return focusFollowsPointer
+}
+
+/** The slice of a node's root element this module reads. */
+export interface NodeRootLike {
+ contains(other: unknown): boolean
+}
+
+export interface FocusLossEvent {
+ /** The node's root (`.term-node`), or null if it is gone. */
+ nodeRoot: NodeRootLike | null
+ /** The element that lost focus (`focusout`'s target). */
+ lost: unknown
+ /** Where focus went (`focusout`'s `relatedTarget`); null for "nowhere" AND for a window blur. */
+ gained: unknown
+ /** `document.activeElement` at the time of the event. */
+ activeElement: unknown
+ /** `document.hasFocus()` at the time of the event. */
+ windowFocused: boolean
+ /** A press landed on THIS node (its React Flow wrapper, header included) in the same task — the
+ * focus change is that press's default action, not a click somewhere else. */
+ pressedInOwnNode: boolean
+}
+
+/** What a `focusout` inside the node means in click-to-focus mode. */
+export type FocusLossOutcome =
+ /** Nothing changed that the node must act on. */
+ | 'keep'
+ /** The user clicked this node's own chrome: hand the keyboard straight back to its terminal. */
+ | 'reclaim'
+ /** The keyboard really went somewhere else: release the node. */
+ | 'release'
+
+/**
+ * Click to focus: what did a `focusout` inside this node mean?
+ *
+ * The one place the node's "I hold the keyboard" state is released in that mode, so it must tell
+ * a real move from its look-alikes:
+ *
+ * - **Focus stayed inside the node** (the header's rename field, a header button, the ⌘M view's
+ * composer). The user is still working HERE → `keep`.
+ * - **The window lost focus** (Cmd+Tab, a click on another app). Chromium fires `blur`/`focusout`
+ * on the focused element, but that element remains `document.activeElement` and is focused
+ * again on return — the terminal never stopped owning the keyboard → `keep`.
+ * - **A press on this node's own chrome** (dragging it by the header, clicking its border). The
+ * browser moves focus to the React Flow wrapper (it is focusable) or to `<body>`, and either
+ * way the keystroke after it would land on the canvas — where a bare Backspace is
+ * `canvas.deleteSelection`. #757 asks that the terminal keep the keyboard until the user clicks a
+ * DIFFERENT card, so this hands it back → `reclaim`.
+ *
+ * Everything else — focus on another node's xterm or a text field, or on `<body>` because a click
+ * landed on the empty canvas — is the user clicking elsewhere, which is exactly what #757 wants to
+ * be the ONLY way to leave → `release`. A node that is gone answers `keep` rather than guessing.
+ */
+export function focusLossOutcome(e: FocusLossEvent): FocusLossOutcome {
+ if (!e.nodeRoot) return 'keep'
+ if (!e.windowFocused) return 'keep'
+ if (e.activeElement === e.lost) return 'keep'
+ if (e.gained && e.nodeRoot.contains(e.gained)) return 'keep'
+ if (e.pressedInOwnNode) return 'reclaim'
+ return 'release'
+}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index d33dcd434..709fc8b2a 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -208,6 +208,12 @@ import { useTerminalSearch } from '../terminal/useTerminalSearch'
import { useCopyFeedback } from '../terminal/useCopyFeedback'
import { ContextMeter } from '../components/ContextMeter'
import { isZoomModifierHeld } from '../lib/zoomModifier'
+import {
+ focusLossOutcome,
+ hoverTakesKeyboard,
+ pointerLeaveReleases,
+ resolveFocusFollowsPointer
+} from '../lib/terminalFocusMode'
import { isHidden } from '../lib/ui-visibility'
import { useTerminalGlass } from '../lib/useTerminalGlass'
import { isLiquidGlass } from '../lib/appTheme'
@@ -1306,6 +1312,12 @@ export function TerminalNode({
// Scoped selectors (not the whole settings object) so this node only re-renders when a
// field it actually uses changes — not on every unrelated settings edit.
const panHoverDelay = useSettings((s) => s.settings.panHoverDelay)
+ // Issue #757: does the keyboard follow the pointer (hover dwell in, mouseleave out — the default)
+ // or a click (Mac-style: the clicked terminal keeps it until focus really moves elsewhere)? Read
+ // live, so toggling it in Settings applies to every mounted node without a remount.
+ const focusFollowsPointer = resolveFocusFollowsPointer(
+ useSettings((s) => s.settings.terminalFocusFollowsPointer)
+ )
// One shallow-compared subscription for the whole appearance slice — see useXtermVisualSettings.
// Scoped to the OWNING project so its `terminal.theme` / `terminal.fontFamily` layer over the
// global settings for this node, and for no other project's nodes.
@@ -5231,6 +5243,10 @@ export function TerminalNode({
}, [focusReq])
const onBodyEnter = () => {
if (dwellRef.current) clearTimeout(dwellRef.current)
+ // Click to focus (#757): hovering never takes the keyboard. A click still does, at once, through
+ // the guard (`onGuardUp` → `enterNow`); a drag that started on the guard comes back here and,
+ // correctly, arms nothing.
+ if (!hoverTakesKeyboard(focusFollowsPointer)) return
const enter = () => {
// While Cmd/Ctrl is held the user is zooming the canvas — don't grab focus / enter the
// terminal; just keep checking until the modifier is released.
@@ -5252,11 +5268,111 @@ export function TerminalNode({
}
const onBodyLeave = () => {
if (dwellRef.current) clearTimeout(dwellRef.current)
+ // Click to focus (#757): the pointer wandering off — to another card, the sidebar, a second
+ // display — leaves the terminal exactly as it is. It keeps the keyboard, the guard stays down
+ // and the node stays active; all of that is released by the focus-loss listener below, which
+ // follows where the KEYBOARD goes rather than where the mouse goes.
+ if (!pointerLeaveReleases(focusFollowsPointer)) return
setArmed(true)
termRef.current?.blur()
useAgentStatus.getState().setActive(id, false)
presence.releaseFocus(id)
}
+ /**
+ * Click to focus (#757): the node's "I hold the keyboard" state follows DOM focus, not the
+ * pointer.
+ *
+ * With focus-follows-pointer, `onBodyLeave` is where the terminal gives the keyboard back and
+ * where the agent-status active flag (unread decisions) and presence focus ("I am working here")
+ * are released. Click to focus removes that trigger on purpose, so without this listener a node
+ * would stay "active" forever after the user clicked into another one. The honest signal is where
+ * focus actually went: another node's xterm (its `enterNow` focuses it), a sticky or a settings
+ * field, or `<body>` because a click on the empty canvas blurred the xterm textarea
+ * (`Canvas.onPaneClick` → `shouldReleasePaneFocus`, issue #86 — the textarea is a TEXTAREA, so it
+ * is released there too). `focusLossOutcome` refuses the look-alikes: focus moving inside this
+ * node (the ⌘M composer, the rename field) and the window itself losing focus (Cmd+Tab — the
+ * terminal still owns the keyboard and gets it back on return). A press on this node's OWN chrome
+ * (dragging it by the header) moves focus to its React Flow wrapper or to `<body>`, which would
+ * hand the next keystroke to the canvas; the issue asks for the keyboard to stay until a
+ * DIFFERENT card is clicked, so that case hands it straight back to the xterm (`reclaim`). The
+ * press is recorded by a capture listener on the wrapper and forgotten at the end of the task,
+ * because the focus change it causes is that press's own default action.
+ *
+ * The guard follows the same fact in this mode: it is lowered whenever this xterm takes focus and
+ * re-armed when focus leaves the node, so the focused terminal owns the wheel and every other one
+ * stays a canvas surface (scroll = pan, drag = move) until it is clicked. In the pointer mode the
+ * guard is a dwell contract instead (see `enterNow`), which is why none of this runs there.
+ *
+ * Symmetrically, gaining focus anywhere inside the node marks it active: the xterm being focused
+ * by something other than `enterNow` (the ⌘M view handing focus back, Chromium restoring it on
+ * window activation) must not leave the node reading as idle.
+ */
+ useEffect(() => {
+ if (focusFollowsPointer) return
+ const root = rootRef.current
+ if (!root) return
+ // Our root sits inside React Flow's wrapper, which also holds the node's resize handles and is
+ // what a header press focuses. Fall back to the root if it is ever rendered outside one.
+ const wrapper: HTMLElement = root.closest<HTMLElement>('.react-flow__node') ?? root
+ let pressedInOwnNode = false
+ let pressTimer: ReturnType<typeof setTimeout> | null = null
+ let reclaimTimer: ReturnType<typeof setTimeout> | null = null
+ const onPointerDown = () => {
+ pressedInOwnNode = true
+ if (pressTimer) clearTimeout(pressTimer)
+ pressTimer = setTimeout(() => {
+ pressedInOwnNode = false
+ pressTimer = null
+ }, 0)
+ }
+ const release = () => {
+ setArmed(true)
+ useAgentStatus.getState().setActive(id, false)
+ presence.releaseFocus(id)
+ }
+ const onFocusIn = (e: FocusEvent) => {
+ if (e.target === termRef.current?.textarea) {
+ setArmed(false)
+ useTerminalFocus.getState().remember(id)
+ }
+ useAgentStatus.getState().setActive(id, true)
+ presence.reportFocus(id)
+ }
+ const onFocusOut = (e: FocusEvent) => {
+ const outcome = focusLossOutcome({
+ nodeRoot: root,
+ lost: e.target,
+ gained: e.relatedTarget,
+ activeElement: document.activeElement,
+ windowFocused: document.hasFocus(),
+ pressedInOwnNode
+ })
+ if (outcome === 'keep') return
+ if (outcome === 'release') {
+ release()
+ return
+ }
+ // 'reclaim': after the press's own focus change has settled. If the xterm cannot take it (the
+ // ⌘M view covers it, or it is gone) the keyboard really did leave, so say so.
+ if (reclaimTimer) clearTimeout(reclaimTimer)
+ reclaimTimer = setTimeout(() => {
+ reclaimTimer = null
+ focusXtermUnlessCovered(termRef.current, mdModeRef.current)
+ const ta = termRef.current?.textarea
+ if (!ta || document.activeElement !== ta) release()
+ }, 0)
+ }
+ wrapper.addEventListener('pointerdown', onPointerDown, true)
+ root.addEventListener('focusin', onFocusIn)
+ root.addEventListener('focusout', onFocusOut)
+ return () => {
+ if (pressTimer) clearTimeout(pressTimer)
+ if (reclaimTimer) clearTimeout(reclaimTimer)
+ wrapper.removeEventListener('pointerdown', onPointerDown, true)
+ root.removeEventListener('focusin', onFocusIn)
+ root.removeEventListener('focusout', onFocusOut)
+ }
+ }, [focusFollowsPointer, id, presence])
// While armed, a mousedown might start a node drag — pause the dwell timer so the
// terminal doesn't grab focus mid-drag; the release decides what happens next (`onGuardUp`).
const onGuardDown = (e: React.MouseEvent) => {
diff --git a/src/renderer/terminal/useMdModeFocus.test.tsx b/src/renderer/terminal/useMdModeFocus.test.tsx
index e5adadfbb..6fed3020e 100644
--- a/src/renderer/terminal/useMdModeFocus.test.tsx
+++ b/src/renderer/terminal/useMdModeFocus.test.tsx
@@ -167,7 +167,9 @@ describe('focusXtermUnlessCovered', () => {
// keystrokes into the hidden pane again with every unit test still green.
const src = readFileSync(resolve(__dirname, '../nodes/TerminalNode.tsx'), 'utf8').replace(/\r\n/g, '\n')
expect(src).not.toMatch(/termRef\.current\?\.focus\(\)/)
- expect(src.match(/focusXtermUnlessCovered\(termRef\.current, mdModeRef\.current\)/g)?.length).toBe(2)
+ // Three paths: the hover dwell, `enterNow`, and the click-to-focus reclaim after a press on the
+ // node's own chrome (#757) — each one asks about the cover.
+ expect(src.match(/focusXtermUnlessCovered\(termRef\.current, mdModeRef\.current\)/g)?.length).toBe(3)
})
it('the kanban card modal viewer uses the same hand-off (blur when covered, no attach-time focus)', () => {
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 92217b1f5..22349fed8 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1641,6 +1641,13 @@ export interface Settings {
worktreePathTemplate: string
/** ms to dwell over a terminal before it takes pointer focus (pan-across guard). */
panHoverDelay: number
+ /** Issue #757. Whether a terminal node's keyboard focus follows the POINTER (the long-standing
+ * behaviour and the default): a `panHoverDelay` dwell takes it and leaving the node gives it
+ * back. Off = click to focus (the Mac model): the pointer decides nothing, a click or a "go to
+ * node" takes the keyboard, and the terminal keeps it until focus really moves elsewhere
+ * (another node, the empty canvas, a field). Machine-local, Settings → Behavior. Decisions live
+ * in `renderer/lib/terminalFocusMode.ts`. */
+ terminalFocusFollowsPointer: boolean
doubleClickFocus: boolean
/** "Go to node" (sessions sidebar, notification click, ⌘K jump, breadcrumb steps, presence
* travel) fits the node in view. Off: the camera keeps the CURRENT zoom and only pans, which is
@@ -2038,6 +2045,7 @@ export const DEFAULT_SETTINGS: Settings = {
omniKanbanAsDefault: false,
worktreePathTemplate: DEFAULT_WORKTREE_PATH_TEMPLATE,
panHoverDelay: 600,
+ terminalFocusFollowsPointer: true,
doubleClickFocus: true,
focusZoomToNode: true,
rememberCanvasLock: false,