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(canvas): keep the keyboard across focus mode's reparent; cancel a stale dwell (#757)
Erik Zwep161cf6bcb98c
diff --git a/CLAUDE.md b/CLAUDE.mdindex 5e24d7139..4d93d6055 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1283,7 +1283,11 @@ session.(`bodyPressAcknowledges`) — guard down, xterm focused, ⌘M view open, all the same — so an unreadfinish is cleared by clicking the terminal, not only by clicking the guard. A focus RESTORE thatno 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+ causes is `keep`, not a release (`lostIsCoveredXterm`). Focus mode's reparent blurs a focused xterm SYNCHRONOUSLY inside+ `appendChild` (MEASURED, Electron 42: `relatedTarget` null, root still connected — so an+ `isConnected` test cannot see it); `nodes/reparentKeepingFocus.ts` brackets the move with a flag the+ hook honours (`reparenting`) and re-focuses the element that held the keyboard, in BOTH modes —+ before it, entering/leaving focus mode dropped the keyboard in the default mode too. The guard listens to POINTER events(`nodes/HoverGuard.tsx`): React Flow's d3-drag swallows a left `mousedown`/`mouseup` on adraggable 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` indiff --git a/src/renderer/lib/terminalFocusMode.test.ts b/src/renderer/lib/terminalFocusMode.test.tsindex 062bd1b32..848abc6f5 100644--- a/src/renderer/lib/terminalFocusMode.test.ts+++ b/src/renderer/lib/terminalFocusMode.test.ts@@ -182,6 +182,13 @@ describe('terminal focus mode (#757)', () => {expect(src).toContain('hoverTakesKeyboard(focusFollowsPointer)')expect(src).toContain('pointerLeaveReleases(focusFollowsPointer)')expect(src).toContain('useClickToFocus(!focusFollowsPointer,')+ // A dwell already running when the setting is switched off must not still take the keyboard:+ // the timer re-reads the LIVE setting, and switching off cancels a pending dwell.+ expect(src).toContain('if (!hoverTakesKeyboard(focusFollowsPointerRef.current)) return')+ expect(src).toMatch(/if \(focusFollowsPointer\) return\s*\n\s*if \(dwellRef\.current\) clearTimeout\(dwellRef\.current\)/)+ // Focus mode keeps the keyboard across its reparent in BOTH modes, and tells the hook.+ expect(src.match(/reparentKeepingFocus\(/g)?.length).toBe(2)+ expect(src).toContain('reparenting: () => reparentingRef.current')const hook = read('src/renderer/nodes/useClickToFocus.ts')for (const call of ['focusLossOutcome(', 'outsidePressReleases(', 'bodyPressAcknowledges(', 'reclaimTarget(']) {expect(hook).toContain(call)diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 396985b52..97e1c094e 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -215,6 +215,7 @@ import {resolveFocusFollowsPointer} from '../lib/terminalFocusMode'import { useClickToFocus } from './useClickToFocus'+import { reparentKeepingFocus } from './reparentKeepingFocus'import { isHidden } from '../lib/ui-visibility'import { useTerminalGlass } from '../lib/useTerminalGlass'import { isLiquidGlass } from '../lib/appTheme'@@ -1515,6 +1516,8 @@ export function TerminalNode({const [, bumpFocused] = useState(0)const focused = focusedNodeId() === idconst focusedRef = useRef(focused)+ /** True only while focus mode's reparent is moving the root (see reparentKeepingFocus). */+ const reparentingRef = useRef(false)focusedRef.current = focuseduseEffect(() => {const read = (): void => {@@ -1546,10 +1549,15 @@ export function TerminalNode({// effect then re-runs with the same answer and no-ops. (Review finding on #267.)glyphSyncRef.current?.(false)const home = root.parentElement- surface.appendChild(root)+ // The move blurs a focused xterm (MEASURED) — give it back, and tell click-to-focus the blur+ // is ours, not the user leaving (reparentKeepingFocus).+ const setMoving = (moving: boolean): void => {+ reparentingRef.current = moving+ }+ reparentKeepingFocus(root, surface, setMoving)return () => {try {- home?.appendChild(root)+ if (home) reparentKeepingFocus(root, home, setMoving)} catch {/* home unmounted with the project — React already gave up on this subtree */}@@ -5232,6 +5240,14 @@ export function TerminalNode({// enterNow closes over live refs/setters; re-running on its identity would fire spuriously.// eslint-disable-next-line react-hooks/exhaustive-deps}, [focusReq])+ const focusFollowsPointerRef = useRef(focusFollowsPointer)+ focusFollowsPointerRef.current = focusFollowsPointer+ // Switching to click to focus cancels a dwell that was already counting down.+ useEffect(() => {+ if (focusFollowsPointer) return+ if (dwellRef.current) clearTimeout(dwellRef.current)+ dwellRef.current = null+ }, [focusFollowsPointer])const onBodyEnter = () => {if (dwellRef.current) clearTimeout(dwellRef.current)// Click to focus (#757): hovering never takes the keyboard. A click still does, at once, through@@ -5239,6 +5255,8 @@ export function TerminalNode({// correctly, arms nothing.if (!hoverTakesKeyboard(focusFollowsPointer)) returnconst enter = () => {+ // The setting can flip while this dwell is pending; the closure's value would be stale.+ if (!hoverTakesKeyboard(focusFollowsPointerRef.current)) return// 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.if (isZoomModifierHeld()) {@@ -5278,6 +5296,7 @@ export function TerminalNode({root: () => rootRef.current,xtermTextarea: () => termRef.current?.textarea,mdMode: () => mdModeRef.current,+ reparenting: () => reparentingRef.current,acknowledge: () => enterNow(),focusXterm: () => focusXtermUnlessCovered(termRef.current, mdModeRef.current),setArmed,diff --git a/src/renderer/nodes/reparentKeepingFocus.test.ts b/src/renderer/nodes/reparentKeepingFocus.test.tsnew file mode 100644index 000000000..c902ebe29--- /dev/null+++ b/src/renderer/nodes/reparentKeepingFocus.test.ts@@ -0,0 +1,69 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it } from 'vitest'+import { reparentKeepingFocus } from './reparentKeepingFocus'++/**+ * Focus mode moves the whole node root into the fullscreen surface. MEASURED in Electron 42 (built-in+ * display): Blink blurs a focused descendant SYNCHRONOUSLY inside appendChild (focusout with+ * relatedTarget null, root still connected, activeElement already <body>), and an immediate focus()+ * after the move takes. So the move is bracketed by a flag the focus listeners can read, and the+ * element that held the keyboard gets it back.+ */+describe('reparentKeepingFocus', () => {+ afterEach(() => {+ document.body.innerHTML = ''+ })++ function setup() {+ const home = document.createElement('div')+ const surface = document.createElement('div')+ const root = document.createElement('div')+ const ta = document.createElement('textarea')+ root.append(ta)+ home.append(root)+ document.body.append(home, surface)+ return { home, surface, root, ta }+ }++ it('moves the root and gives the keyboard back to the element that held it', () => {+ const { surface, root, ta } = setup()+ ta.focus()+ reparentKeepingFocus(root, surface, () => {})+ expect(root.parentElement).toBe(surface)+ expect(document.activeElement).toBe(ta)+ })++ it('raises the flag for exactly the duration of the move', () => {+ const { surface, root, ta } = setup()+ ta.focus()+ const seen: boolean[] = []+ let flag = false+ reparentKeepingFocus(root, surface, (on) => {+ flag = on+ seen.push(on)+ })+ expect(seen).toEqual([true, false])+ expect(flag).toBe(false)+ })++ it('focuses nothing when the node did not hold the keyboard', () => {+ const { surface, root } = setup()+ const other = document.createElement('input')+ document.body.append(other)+ other.focus()+ reparentKeepingFocus(root, surface, () => {})+ expect(document.activeElement).toBe(other)+ })++ it('lowers the flag even when the move throws', () => {+ const { root, ta } = setup()+ ta.focus()+ let flag = false+ expect(() =>+ reparentKeepingFocus(root, root, (on) => {+ flag = on+ })+ ).toThrow()+ expect(flag).toBe(false)+ })+})diff --git a/src/renderer/nodes/reparentKeepingFocus.ts b/src/renderer/nodes/reparentKeepingFocus.tsnew file mode 100644index 000000000..202eb2c79--- /dev/null+++ b/src/renderer/nodes/reparentKeepingFocus.ts@@ -0,0 +1,27 @@+/**+ * Move a node root to a new parent without losing the keyboard (focus mode, #78 / #757).+ *+ * MEASURED in Electron 42 (built-in display): Blink blurs a focused descendant SYNCHRONOUSLY inside+ * `appendChild` — `focusout` with `relatedTarget` null, the root still connected, `activeElement`+ * already `<body>` — and nothing re-focuses it, so entering or leaving focus mode dropped the+ * keyboard on the floor in BOTH focus modes. An immediate `focus()` after the move takes.+ *+ * `setMoving(true/false)` brackets exactly the move, so a focus listener can tell this blur from the+ * user going elsewhere (click to focus would otherwise read it as `release`). It is lowered even when+ * the move throws.+ */+export function reparentKeepingFocus(+ root: HTMLElement,+ parent: HTMLElement,+ setMoving: (moving: boolean) => void+): void {+ const active = document.activeElement+ const held = active instanceof HTMLElement && root.contains(active) ? active : null+ setMoving(true)+ try {+ parent.appendChild(root)+ } finally {+ setMoving(false)+ }+ if (held && held.isConnected && root.contains(held)) held.focus({ preventScroll: true })+}diff --git a/src/renderer/nodes/useClickToFocus.test.tsx b/src/renderer/nodes/useClickToFocus.test.tsxindex ec8f6b374..cd30e1ebe 100644--- a/src/renderer/nodes/useClickToFocus.test.tsx+++ b/src/renderer/nodes/useClickToFocus.test.tsx@@ -33,7 +33,7 @@ describe('useClickToFocus', () => {let handle: HTMLDivElementlet outside: HTMLDivElementlet surface: HTMLDivElement- let host: ClickToFocusHost & { active: boolean; md: boolean }+ let host: ClickToFocusHost & { active: boolean; md: boolean; moving: boolean }const calls: string[] = []beforeEach(() => {@@ -68,6 +68,8 @@ describe('useClickToFocus', () => {host = {active: false,md: false,+ moving: false,+ reparenting: () => host.moving,id: 'n1',root: () => node,xtermTextarea: () => xterm,@@ -159,6 +161,16 @@ describe('useClickToFocus', () => {expect(calls).toContain('active:false')})+ it('keeps the node across focus mode\'s reparent blur (the move re-focuses it afterwards)', () => {+ act(() => xterm.focus())+ calls.length = 0+ host.moving = true+ act(() => xterm.blur()) // Blink blurs the focused textarea synchronously inside appendChild+ host.moving = false+ expect(calls).not.toContain('release')+ expect(calls).not.toContain('armed:true')+ })+it('releases when focus leaves for something outside the node', () => {act(() => xterm.focus())calls.length = 0diff --git a/src/renderer/nodes/useClickToFocus.ts b/src/renderer/nodes/useClickToFocus.tsindex af4c05aa4..8a20e5cf3 100644--- a/src/renderer/nodes/useClickToFocus.ts+++ b/src/renderer/nodes/useClickToFocus.ts@@ -15,6 +15,8 @@ export interface ClickToFocusHost {xtermTextarea: () => HTMLTextAreaElement | undefined/** The ⌘M (Markdown / chat) view covers the xterm. */mdMode: () => boolean+ /** True while focus mode is moving the root; the blur that move causes is not the user leaving. */+ reparenting: () => boolean/** The node's `enterNow` — the acknowledgement a dwell or a guard click runs. */acknowledge: () => void/** `focusXtermUnlessCovered` for this node. */@@ -111,6 +113,8 @@ export function useClickToFocus(enabled: boolean, host: ClickToFocusHost): void}const onFocusOut = (e: FocusEvent) => {+ // Focus mode's own reparent (reparentKeepingFocus re-focuses the element right after).+ if (h().reparenting()) returnconst outcome = focusLossOutcome({nodeRoot: root,lost: e.target,