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.

refactor(canvas): one click-to-focus ownership hook on the stable node root (#757)

Erik Zwep09733ceb5dd1
diff --git a/CLAUDE.md b/CLAUDE.md
index 89924b930..ff1edd211 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1264,19 +1264,25 @@ session.
- **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 (`HoverGuard` pointer events → `onGuardClick` → `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, MEASURED in Electron 42) hands it back to
- the element that lost it (the ⌘M composer) or the xterm (`reclaimTarget`), anything else —
- another node, a field, the empty canvas (`onPaneClick` blurs the xterm textarea,
- `shouldReleasePaneFocus`) — releases it and re-arms the guard. Activity claimed WITHOUT focus
- (go-to-node under the ⌘M view, Canvas's own `setActive` on a jump) has no focusout, so a
- document capture `pointerdown` outside the node releases it (`outsidePressReleases`) — else the
- stale `activeId` suppresses that node's unread dot. The ⌘M view has no guard (`armed && !mdMode`)
- and no dwell here, so a primary press in the node body while it is open runs `enterNow`
- (`mdViewPressAcknowledges` — the dwell's ack, xterm left unfocused), and the xterm blur that
- OPENING the view causes is `keep`, not a release (`lostIsCoveredXterm`). The guard listens to POINTER events
+ keyboard, and the node's active flag, presence focus AND guard then follow DOM focus. ONE hook
+ owns all of it, `nodes/useClickToFocus.ts`, and it binds to the stable `.term-node` ROOT, never
+ the React Flow wrapper: focus mode MOVES that root into the fullscreen surface
+ (`surface.appendChild(root)`), so a listener or containment check captured on the wrapper went
+ deaf there and read every body press as an outside press. The wrapper is re-resolved at event
+ time only to recognise the node's own React Flow chrome (resize handles). Root `focusin`/
+ `focusout` run `focusLossOutcome` (`lib/terminalFocusMode.ts`): 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, MEASURED in Electron 42) hands it back to the element that lost it (the ⌘M
+ composer) or the xterm (`reclaimTarget`), anything else — another node, a field, the empty canvas
+ (`onPaneClick` blurs the xterm textarea, `shouldReleasePaneFocus`) — releases it and re-arms the
+ guard. One document capture `pointerdown` does the rest: outside the node it releases activity
+ claimed WITHOUT focus (go-to-node under the ⌘M view, Canvas's own `setActive` on a jump — no
+ focusout ever comes, `outsidePressReleases`), else the stale `activeId` suppresses that node's
+ unread dot; inside the BODY, any deliberate primary press that is not on the guard runs `enterNow`
+ (`bodyPressAcknowledges`) — guard down, xterm focused, ⌘M view open, all the same — so an unread
+ finish is cleared by clicking the terminal, not only by clicking the guard. A focus RESTORE that
+ no press caused (window activation) never acknowledges. The xterm blur that OPENING the ⌘M view
+ causes is `keep`, not a release (`lostIsCoveredXterm`). The guard listens to POINTER events
(`nodes/HoverGuard.tsx`): React Flow's d3-drag swallows a left `mousedown`/`mouseup` on a
draggable node before React sees them, so the old mouse-event guard never received a left click
(#87's click-to-focus only ever worked through the dwell). Only a literal `false` in
diff --git a/src/renderer/lib/terminalFocusMode.test.ts b/src/renderer/lib/terminalFocusMode.test.ts
index 9cf8bfb94..062bd1b32 100644
--- a/src/renderer/lib/terminalFocusMode.test.ts
+++ b/src/renderer/lib/terminalFocusMode.test.ts
@@ -4,7 +4,7 @@ import { join } from 'path'
import { DEFAULT_SETTINGS } from '@shared/types'
import {
focusLossOutcome,
- mdViewPressAcknowledges,
+ bodyPressAcknowledges,
outsidePressReleases,
reclaimTarget,
hoverTakesKeyboard,
@@ -152,22 +152,22 @@ describe('terminal focus mode (#757)', () => {
})
})
- describe('mdViewPressAcknowledges', () => {
- // With focus-follows-pointer, a dwell over the ⌘M view acknowledges the node (setActive,
- // clearUnread, presence) without focusing the covered xterm. Click to focus has no dwell and no
- // guard over that view (the guard renders only when !mdMode), so a click is the replacement.
- it('acknowledges a primary press on the covered view in click-to-focus mode', () => {
- expect(mdViewPressAcknowledges({ focusFollowsPointer: false, mdMode: true, primary: true, inBody: true })).toBe(true)
+ describe('bodyPressAcknowledges', () => {
+ // Click to focus has no dwell, so a deliberate press is the acknowledgement (active,
+ // clearUnread, presence) — on the xterm with the guard already down (a finish that turned unread
+ // while the window was inactive), on the ⌘M view, on its composer. Only a press can: a focus
+ // restore on window activation is not the user aiming at the node.
+ it('acknowledges any primary press inside the node body', () => {
+ expect(bodyPressAcknowledges({ primary: true, inBody: true, onGuard: false })).toBe(true)
})
- it('does nothing where something else already owns it', () => {
- // the dwell owns it
- expect(mdViewPressAcknowledges({ focusFollowsPointer: true, mdMode: true, primary: true, inBody: true })).toBe(false)
- // the guard / xterm own it
- expect(mdViewPressAcknowledges({ focusFollowsPointer: false, mdMode: false, primary: true, inBody: true })).toBe(false)
- // a right click opens the menu; the header is chrome, not the view
- expect(mdViewPressAcknowledges({ focusFollowsPointer: false, mdMode: true, primary: false, inBody: true })).toBe(false)
- expect(mdViewPressAcknowledges({ focusFollowsPointer: false, mdMode: true, primary: true, inBody: false })).toBe(false)
+ it('leaves the guard to HoverGuard, since a press there may be the start of a node drag', () => {
+ expect(bodyPressAcknowledges({ primary: true, inBody: true, onGuard: true })).toBe(false)
+ })
+
+ it('ignores the header chrome and non-primary buttons', () => {
+ expect(bodyPressAcknowledges({ primary: true, inBody: false, onGuard: false })).toBe(false)
+ expect(bodyPressAcknowledges({ primary: false, inBody: true, onGuard: false })).toBe(false)
})
})
@@ -181,10 +181,12 @@ describe('terminal focus mode (#757)', () => {
expect(src).toContain('useSettings((s) => s.settings.terminalFocusFollowsPointer)')
expect(src).toContain('hoverTakesKeyboard(focusFollowsPointer)')
expect(src).toContain('pointerLeaveReleases(focusFollowsPointer)')
- expect(src).toContain('focusLossOutcome(')
- expect(src).toContain('outsidePressReleases(')
- expect(src).toContain('mdViewPressAcknowledges(')
- expect(src).toContain('lostIsCoveredXterm:')
+ expect(src).toContain('useClickToFocus(!focusFollowsPointer,')
+ const hook = read('src/renderer/nodes/useClickToFocus.ts')
+ for (const call of ['focusLossOutcome(', 'outsidePressReleases(', 'bodyPressAcknowledges(', 'reclaimTarget(']) {
+ expect(hook).toContain(call)
+ }
+ expect(hook).toContain('lostIsCoveredXterm:')
})
it('Settings → Behavior offers the toggle, findable by search', () => {
diff --git a/src/renderer/lib/terminalFocusMode.ts b/src/renderer/lib/terminalFocusMode.ts
index bd7e15975..bc732c9e4 100644
--- a/src/renderer/lib/terminalFocusMode.ts
+++ b/src/renderer/lib/terminalFocusMode.ts
@@ -151,21 +151,17 @@ export function reclaimTarget(p: { lostIsXterm: boolean; lostStillInNode: boolea
}
/**
- * Click to focus: does this press acknowledge the node while its ⌘M (Markdown / chat) view is open?
+ * Click to focus: does this press ACKNOWLEDGE the node (the `enterNow` routine — active flag,
+ * `clearUnread`, presence, remember, and the xterm focused unless the ⌘M view covers it)?
*
- * With focus-follows-pointer, the hover dwell over that view runs the whole "I am here" routine —
- * active flag, `clearUnread` (the cross-surface finish ACK), presence, remember — while
- * `focusXtermUnlessCovered` leaves the hidden xterm unfocused. Click to focus has no dwell, and the
- * hover guard is not rendered over the view (`armed && !mdMode`), so without this a user could click
- * into an unread conversation, read it, type in its composer, and it stayed unread. A primary press
- * inside the node BODY (the view) is the click equivalent; the header is chrome and a right click
- * opens the menu.
+ * Focus-follows-pointer acknowledges on every dwell. Click to focus has no dwell, so a deliberate
+ * primary press anywhere in the node BODY is the acknowledgement: on the xterm even when the guard is
+ * already down (Codex round 3 — a finish that turned unread while the window was inactive could not
+ * be cleared by clicking the terminal it belongs to), on the open ⌘M view, on its composer. Three
+ * exclusions: the guard itself, because a press there may start a node drag and `HoverGuard` owns
+ * that decision on release; the header chrome; and non-primary buttons (the context menu). A focus
+ * restore with no press (window activation) is never an acknowledgement — only presses reach this.
*/
-export function mdViewPressAcknowledges(p: {
- focusFollowsPointer: boolean
- mdMode: boolean
- primary: boolean
- inBody: boolean
-}): boolean {
- return !p.focusFollowsPointer && p.mdMode && p.primary && p.inBody
+export function bodyPressAcknowledges(p: { primary: boolean; inBody: boolean; onGuard: boolean }): boolean {
+ return p.primary && p.inBody && !p.onGuard
}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 31bc3ae48..396985b52 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -210,14 +210,11 @@ import { ContextMeter } from '../components/ContextMeter'
import { isZoomModifierHeld } from '../lib/zoomModifier'
import { HoverGuard } from './HoverGuard'
import {
- focusLossOutcome,
hoverTakesKeyboard,
- mdViewPressAcknowledges,
- outsidePressReleases,
pointerLeaveReleases,
- reclaimTarget,
resolveFocusFollowsPointer
} from '../lib/terminalFocusMode'
+import { useClickToFocus } from './useClickToFocus'
import { isHidden } from '../lib/ui-visibility'
import { useTerminalGlass } from '../lib/useTerminalGlass'
import { isLiquidGlass } from '../lib/appTheme'
@@ -5272,135 +5269,24 @@ export function TerminalNode({
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 = (e: PointerEvent) => {
- // A click on the open ⌘M view is click-to-focus's stand-in for the dwell over it: it runs
- // `enterNow`, which acknowledges the node and leaves the covered xterm unfocused
- // (`focusXtermUnlessCovered`) — exactly what the dwell does there in the default mode.
- if (
- mdViewPressAcknowledges({
- focusFollowsPointer: false,
- mdMode: mdModeRef.current,
- primary: e.button === 0,
- inBody: e.target instanceof Element && !!e.target.closest('.term-node__body') && root.contains(e.target)
- })
- ) {
- enterNow()
- }
- 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,
- lostIsCoveredXterm: mdModeRef.current && e.target === termRef.current?.textarea
- })
- if (outcome === 'keep') return
- if (outcome === 'release') {
- release()
- return
- }
- // 'reclaim': after the press's own focus change has settled, give the keyboard back to what
- // lost it (the ⌘M composer) or to the xterm (`reclaimTarget`). If nothing inside the node
- // could take it (the xterm is covered or gone) the keyboard really did leave, so say so.
- const lost = e.target
- if (reclaimTimer) clearTimeout(reclaimTimer)
- reclaimTimer = setTimeout(() => {
- reclaimTimer = null
- const target = reclaimTarget({
- lostIsXterm: lost === termRef.current?.textarea,
- lostStillInNode: lost instanceof HTMLElement && lost.isConnected && root.contains(lost)
- })
- if (target === 'lost') (lost as HTMLElement).focus()
- else focusXtermUnlessCovered(termRef.current, mdModeRef.current)
- if (!root.contains(document.activeElement)) release()
- }, 0)
- }
- // Activity claimed WITHOUT focus (a go-to-node under the ⌘M view, Canvas's own setActive on a
- // jump) has no focusout to end it; a press anywhere else does (`outsidePressReleases`). Capture
- // phase, so React Flow's d3 handlers cannot hide the press, and a cheap `activeId` check first:
- // every mounted terminal carries one of these.
- const onDocPointerDown = (e: PointerEvent) => {
- const releases = outsidePressReleases({
- isActive: useAgentStatus.getState().activeId === id,
- pressInsideNode: e.target instanceof Node && wrapper.contains(e.target),
- focusInsideNode: root.contains(document.activeElement)
- })
- if (releases) release()
- }
- document.addEventListener('pointerdown', onDocPointerDown, true)
- wrapper.addEventListener('pointerdown', onPointerDown, true)
- root.addEventListener('focusin', onFocusIn)
- root.addEventListener('focusout', onFocusOut)
- return () => {
- if (pressTimer) clearTimeout(pressTimer)
- if (reclaimTimer) clearTimeout(reclaimTimer)
- document.removeEventListener('pointerdown', onDocPointerDown, true)
- wrapper.removeEventListener('pointerdown', onPointerDown, true)
- root.removeEventListener('focusin', onFocusIn)
- root.removeEventListener('focusout', onFocusOut)
- }
- }, [focusFollowsPointer, id, presence])
+ // Click to focus (#757): who holds the keyboard follows DOM focus and deliberate presses, not the
+ // pointer — the whole mechanism, its measurements and its refusals live in `useClickToFocus`.
+ // Every callback is read live from this render; the listeners are bound once per mode switch, to
+ // the node root, which is the one element that survives focus mode's reparent.
+ useClickToFocus(!focusFollowsPointer, {
+ id,
+ root: () => rootRef.current,
+ xtermTextarea: () => termRef.current?.textarea,
+ mdMode: () => mdModeRef.current,
+ acknowledge: () => enterNow(),
+ focusXterm: () => focusXtermUnlessCovered(termRef.current, mdModeRef.current),
+ setArmed,
+ remember: () => useTerminalFocus.getState().remember(id),
+ isActive: () => useAgentStatus.getState().activeId === id,
+ setActive: (active) => useAgentStatus.getState().setActive(id, active),
+ reportFocus: () => presence.reportFocus(id),
+ releaseFocus: () => presence.releaseFocus(id)
+ })
// While armed, a press might start a node drag — pause the dwell timer so the terminal doesn't
// grab focus mid-drag; the release decides what happens next (`onGuardClick` / `onBodyEnter`).
const onGuardPress = () => {
diff --git a/src/renderer/nodes/useClickToFocus.test.tsx b/src/renderer/nodes/useClickToFocus.test.tsx
new file mode 100644
index 000000000..392f2fba4
--- /dev/null
+++ b/src/renderer/nodes/useClickToFocus.test.tsx
@@ -0,0 +1,202 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { useClickToFocus, type ClickToFocusHost } from './useClickToFocus'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+/**
+ * Click-to-focus ownership (#757) against a real DOM shaped like a terminal node:
+ *
+ * .react-flow__node (tabindex 0)
+ * .term-node ← the stable root; focus mode MOVES this element
+ * .term-node__header
+ * .term-node__body
+ * textarea.xterm ← the xterm's input
+ * .term-hover-guard ← present only while armed
+ * .resize-handle ← React Flow chrome outside our root
+ *
+ * The listeners must survive the root being reparented into the fullscreen focus surface (Codex
+ * round 3), and every deliberate primary press in the body must acknowledge — with the guard down
+ * too — while a focus restore that no press caused must not.
+ */
+describe('useClickToFocus', () => {
+ let container: HTMLDivElement
+ let reactRoot: Root
+ let wrapper: HTMLDivElement
+ let node: HTMLDivElement
+ let header: HTMLDivElement
+ let body: HTMLDivElement
+ let xterm: HTMLTextAreaElement
+ let guard: HTMLDivElement
+ let handle: HTMLDivElement
+ let outside: HTMLDivElement
+ let surface: HTMLDivElement
+ let host: ClickToFocusHost & { active: boolean; md: boolean }
+ const calls: string[] = []
+
+ beforeEach(() => {
+ calls.length = 0
+ // jsdom clears its focused element between blur and focus, so its hasFocus() reads false inside
+ // an in-window focusout. Blink reads TRUE there (MEASURED in Electron 42 for every click move;
+ // false only when the window itself deactivates), and that is the state the logic is for.
+ vi.spyOn(document, 'hasFocus').mockReturnValue(true)
+ container = document.createElement('div')
+ document.body.appendChild(container)
+ wrapper = document.createElement('div')
+ wrapper.className = 'react-flow__node'
+ wrapper.tabIndex = 0
+ node = document.createElement('div')
+ node.className = 'term-node'
+ header = document.createElement('div')
+ header.className = 'term-node__header'
+ body = document.createElement('div')
+ body.className = 'term-node__body'
+ xterm = document.createElement('textarea')
+ guard = document.createElement('div')
+ guard.className = 'term-hover-guard'
+ handle = document.createElement('div')
+ handle.className = 'resize-handle'
+ body.append(xterm, guard)
+ node.append(header, body)
+ wrapper.append(node, handle)
+ outside = document.createElement('div')
+ surface = document.createElement('div')
+ document.body.append(wrapper, outside, surface)
+
+ host = {
+ active: false,
+ md: false,
+ id: 'n1',
+ root: () => node,
+ xtermTextarea: () => xterm,
+ mdMode: () => host.md,
+ acknowledge: vi.fn(() => {
+ calls.push('acknowledge')
+ host.active = true
+ }),
+ focusXterm: vi.fn(() => {
+ if (!host.md) xterm.focus()
+ }),
+ setArmed: vi.fn((armed: boolean) => calls.push(`armed:${armed}`)),
+ remember: vi.fn(() => calls.push('remember')),
+ isActive: () => host.active,
+ setActive: vi.fn((a: boolean) => {
+ calls.push(`active:${a}`)
+ host.active = a
+ }),
+ reportFocus: vi.fn(() => calls.push('report')),
+ releaseFocus: vi.fn(() => calls.push('release'))
+ }
+ function Probe({ enabled }: { enabled: boolean }) {
+ useClickToFocus(enabled, host)
+ return null
+ }
+ reactRoot = createRoot(container)
+ act(() => reactRoot.render(<Probe enabled />))
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ act(() => reactRoot.unmount())
+ container.remove()
+ wrapper.remove()
+ outside.remove()
+ surface.remove()
+ })
+
+ const press = (target: Element, button = 0) =>
+ act(() => {
+ target.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true, cancelable: true, button }))
+ })
+
+ it('acknowledges a press on the xterm with the guard already down (focused terminal, unread finish)', () => {
+ guard.remove()
+ press(xterm)
+ expect(host.acknowledge).toHaveBeenCalledTimes(1)
+ })
+
+ it('acknowledges a press on the open ⌘M view', () => {
+ guard.remove()
+ host.md = true
+ const view = document.createElement('div')
+ body.append(view)
+ press(view)
+ expect(host.acknowledge).toHaveBeenCalledTimes(1)
+ })
+
+ it('leaves a press on the guard to HoverGuard (it may be a drag), and ignores the header and right clicks', () => {
+ press(guard)
+ press(header)
+ press(xterm, 2)
+ expect(host.acknowledge).not.toHaveBeenCalled()
+ })
+
+ it('does not acknowledge a focus restore that no press caused (window activation)', () => {
+ act(() => xterm.focus())
+ expect(host.acknowledge).not.toHaveBeenCalled()
+ // …but the node does report that it holds the keyboard.
+ expect(calls).toContain('active:true')
+ expect(calls).toContain('armed:false')
+ })
+
+ it('keeps working after focus mode moves the root into another surface', () => {
+ guard.remove()
+ act(() => surface.appendChild(node))
+ host.active = true
+ press(xterm)
+ expect(host.acknowledge).toHaveBeenCalledTimes(1)
+ expect(calls).not.toContain('release')
+ })
+
+ it('releases an active node that holds no focus on a press elsewhere, and only elsewhere', () => {
+ host.active = true
+ press(handle) // React Flow chrome of the SAME node
+ expect(calls).not.toContain('release')
+ press(outside)
+ expect(calls).toContain('release')
+ expect(calls).toContain('active:false')
+ })
+
+ it('releases when focus leaves for something outside the node', () => {
+ act(() => xterm.focus())
+ calls.length = 0
+ const field = document.createElement('input')
+ outside.append(field)
+ act(() => field.focus())
+ expect(calls).toContain('release')
+ expect(calls).toContain('armed:true')
+ })
+
+ it('hands the keyboard back to the xterm after a press on the node’s own chrome moved it to the wrapper', async () => {
+ act(() => xterm.focus())
+ press(header)
+ act(() => wrapper.focus()) // what Blink does with a header press (measured in Electron 42)
+ await act(async () => {
+ await new Promise((r) => setTimeout(r, 5))
+ })
+ expect(document.activeElement).toBe(xterm)
+ expect(calls).not.toContain('release')
+ })
+
+ it('does nothing while focus follows the pointer', () => {
+ act(() =>
+ reactRoot.render(
+ (() => {
+ function Off() {
+ useClickToFocus(false, host)
+ return null
+ }
+ return <Off />
+ })()
+ )
+ )
+ guard.remove()
+ press(xterm)
+ host.active = true
+ press(outside)
+ expect(host.acknowledge).not.toHaveBeenCalled()
+ expect(calls).not.toContain('release')
+ })
+})
diff --git a/src/renderer/nodes/useClickToFocus.ts b/src/renderer/nodes/useClickToFocus.ts
new file mode 100644
index 000000000..eece5a5ca
--- /dev/null
+++ b/src/renderer/nodes/useClickToFocus.ts
@@ -0,0 +1,156 @@
+import { useEffect, useRef } from 'react'
+import {
+ bodyPressAcknowledges,
+ focusLossOutcome,
+ outsidePressReleases,
+ reclaimTarget
+} from '../lib/terminalFocusMode'
+
+/** What the click-to-focus machinery needs from its terminal node. Read LIVE on every event. */
+export interface ClickToFocusHost {
+ id: string
+ /** The node's own root (`.term-node`). Focus mode MOVES this element; it is never replaced. */
+ root: () => HTMLElement | null
+ /** The xterm's input element, if a terminal is mounted. */
+ xtermTextarea: () => HTMLTextAreaElement | undefined
+ /** The ⌘M (Markdown / chat) view covers the xterm. */
+ mdMode: () => boolean
+ /** The node's `enterNow` — the acknowledgement a dwell or a guard click runs. */
+ acknowledge: () => void
+ /** `focusXtermUnlessCovered` for this node. */
+ focusXterm: () => void
+ setArmed: (armed: boolean) => void
+ remember: () => void
+ isActive: () => boolean
+ setActive: (active: boolean) => void
+ reportFocus: () => void
+ releaseFocus: () => void
+}
+
+/**
+ * Click to focus (#757): the node's "I hold the keyboard" state follows DOM focus and deliberate
+ * presses, never the pointer's position.
+ *
+ * ONE document capture `pointerdown` listener plus `focusin`/`focusout` on the node root. Earlier
+ * versions also listened on the React Flow wrapper, captured once when the effect ran — and focus
+ * mode moves the root out of that wrapper into the fullscreen surface, after which body presses
+ * never reached the wrapper listener and the document listener called them "outside" (Codex round
+ * 3). Now every containment question is asked at EVENT time: the root is the one stable element,
+ * and "this node's own chrome" is `root.closest('.react-flow__node') ?? root`, resolved when the
+ * press happens (in focus mode that is just the root, which is all of the node there is).
+ *
+ * The press listener does three things, in this order:
+ * - remembers that a press landed on this node, for the `focusout` that the press's own default
+ * action causes in the same task (MEASURED in Electron 42: pointerdown → mousedown → focusout);
+ * - releases an active node that holds no focus when the press is elsewhere (`outsidePressReleases`);
+ * - acknowledges a deliberate primary press in the body (`bodyPressAcknowledges`), guard excluded.
+ *
+ * Capture phase on the document, so React Flow's d3-drag (which stops mousedown at the wrapper) can
+ * never hide a press. The focus decisions are the pure functions in `lib/terminalFocusMode.ts`.
+ */
+export function useClickToFocus(enabled: boolean, host: ClickToFocusHost): void {
+ const hostRef = useRef(host)
+ hostRef.current = host
+ useEffect(() => {
+ if (!enabled) return
+ const h = () => hostRef.current
+ const root = h().root()
+ if (!root) return
+ let pressedInOwnNode = false
+ let pressTimer: ReturnType<typeof setTimeout> | null = null
+ let reclaimTimer: ReturnType<typeof setTimeout> | null = null
+
+ const release = () => {
+ h().setArmed(true)
+ h().setActive(false)
+ h().releaseFocus()
+ }
+
+ const onPointerDown = (e: PointerEvent) => {
+ const target = e.target instanceof Element ? e.target : null
+ const ownNode = root.closest<HTMLElement>('.react-flow__node') ?? root
+ const inNode = !!target && ownNode.contains(target)
+ if (inNode) {
+ pressedInOwnNode = true
+ if (pressTimer) clearTimeout(pressTimer)
+ pressTimer = setTimeout(() => {
+ pressedInOwnNode = false
+ pressTimer = null
+ }, 0)
+ }
+ if (
+ outsidePressReleases({
+ isActive: h().isActive(),
+ pressInsideNode: inNode,
+ focusInsideNode: root.contains(document.activeElement)
+ })
+ ) {
+ release()
+ return
+ }
+ if (
+ target &&
+ root.contains(target) &&
+ bodyPressAcknowledges({
+ primary: e.button === 0,
+ inBody: !!target.closest('.term-node__body'),
+ onGuard: !!target.closest('.term-hover-guard')
+ })
+ ) {
+ h().acknowledge()
+ }
+ }
+
+ const onFocusIn = (e: FocusEvent) => {
+ if (e.target === h().xtermTextarea()) {
+ h().setArmed(false)
+ h().remember()
+ }
+ h().setActive(true)
+ h().reportFocus()
+ }
+
+ const onFocusOut = (e: FocusEvent) => {
+ const outcome = focusLossOutcome({
+ nodeRoot: root,
+ lost: e.target,
+ gained: e.relatedTarget,
+ activeElement: document.activeElement,
+ windowFocused: document.hasFocus(),
+ pressedInOwnNode,
+ lostIsCoveredXterm: h().mdMode() && e.target === h().xtermTextarea()
+ })
+ if (outcome === 'keep') return
+ if (outcome === 'release') {
+ release()
+ return
+ }
+ // 'reclaim': once the press's own focus change has settled, give the keyboard back to what
+ // lost it (the ⌘M composer) or to the xterm. If nothing inside the node could take it (the
+ // xterm is covered or gone), the keyboard really did leave, so say so.
+ const lost = e.target
+ if (reclaimTimer) clearTimeout(reclaimTimer)
+ reclaimTimer = setTimeout(() => {
+ reclaimTimer = null
+ const target = reclaimTarget({
+ lostIsXterm: lost === h().xtermTextarea(),
+ lostStillInNode: lost instanceof HTMLElement && lost.isConnected && root.contains(lost)
+ })
+ if (target === 'lost') (lost as HTMLElement).focus()
+ else h().focusXterm()
+ if (!root.contains(document.activeElement)) release()
+ }, 0)
+ }
+
+ document.addEventListener('pointerdown', onPointerDown, true)
+ root.addEventListener('focusin', onFocusIn)
+ root.addEventListener('focusout', onFocusOut)
+ return () => {
+ if (pressTimer) clearTimeout(pressTimer)
+ if (reclaimTimer) clearTimeout(reclaimTimer)
+ document.removeEventListener('pointerdown', onPointerDown, true)
+ root.removeEventListener('focusin', onFocusIn)
+ root.removeEventListener('focusout', onFocusOut)
+ }
+ }, [enabled])
+}