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(md-view): keep the hidden xterm unfocused; honest late-answer tests

review61f1adc76456
diff --git a/CLAUDE.md b/CLAUDE.md
index 5804dc55e..cbf5963ff 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1259,8 +1259,12 @@ session.
lifecycle: capture on mount + a ↻ refresh, a request token that drops stale/late answers, an
explicit empty state ('' is an answer; a rejected capture is a failure, not empty), only the
LAST `MD_OUTPUT_MAX_LINES` (5000) lines rendered and announced when cut, scrolled to the latest
- output. Entering the view (output or ChatPanel) blurs the xterm, and leaving it restores focus
- only if the terminal had it on entry (`terminal/useMdModeFocus.ts`). Tag chips via `NodeTags`.
+ output. Entering the view (output or ChatPanel) blurs the xterm; leaving it restores focus
+ only if the terminal had it on entry AND focus is now nowhere or still inside this node
+ (`terminal/useMdModeFocus.ts`). While the view is open, every "take the keyboard" path (hover
+ dwell, click, sidebar/notification jump) goes through `focusXtermUnlessCovered` and leaves the
+ hidden xterm unfocused — the overlay sits inside the node body, so a dwell over it used to route
+ keystrokes into a pane nobody could see (source-pinned in `useMdModeFocus.test.tsx`). Tag chips via `NodeTags`.
**Selection + copy is tmux's** (its mouse is on — see the tmux section): drag to select, wheel to
scroll tmux's history. A drag copies via copy-mode, and tmux emits **OSC 52** to the client, whose
handler writes the **system clipboard** — the one copy path on every platform *and* over SSH (no
diff --git a/src/renderer/nodes/TerminalMarkdownView.test.tsx b/src/renderer/nodes/TerminalMarkdownView.test.tsx
index 53f098ad2..2021dc0b3 100644
--- a/src/renderer/nodes/TerminalMarkdownView.test.tsx
+++ b/src/renderer/nodes/TerminalMarkdownView.test.tsx
@@ -4,6 +4,26 @@ import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react'
import { TerminalMarkdownView } from './TerminalMarkdownView'
+// Spy on the lazily imported renderer (vitest mocks dynamic imports too), so a dropped answer is
+// OBSERVABLE: React 18 no longer warns on a set-state-after-unmount, so "no console error" proves
+// nothing — "the renderer never ran for it" does.
+const md = vi.hoisted(() => ({ tail: vi.fn(), render: vi.fn(), throwRender: false }))
+vi.mock('../lib/terminalOutputMarkdown', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../lib/terminalOutputMarkdown')>()
+ return {
+ ...actual,
+ tailOutputLines: (...args: Parameters<typeof actual.tailOutputLines>) => {
+ md.tail(...args)
+ return actual.tailOutputLines(...args)
+ },
+ renderTerminalOutput: (text: string) => {
+ md.render(text)
+ if (md.throwRender) throw new Error('renderer blew up')
+ return actual.renderTerminalOutput(text)
+ }
+ }
+})
+
// Standalone harness — react-dom only, no testing-library (same shape as useDiscardWhenHidden).
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
@@ -24,6 +44,9 @@ beforeAll(async () => {
})
beforeEach(() => {
+ md.tail.mockClear()
+ md.render.mockClear()
+ md.throwRender = false
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
@@ -111,17 +134,43 @@ describe('TerminalMarkdownView', () => {
expect(content().textContent).not.toContain('stale')
})
- it('ignores an answer that arrives after unmount', async () => {
- const errors = vi.spyOn(console, 'error').mockImplementation(() => {})
+ it('ignores an answer that arrives after unmount — the renderer never runs for it', async () => {
mount()
act(() => root.unmount())
pending[0].resolve('late')
await settle()
- expect(errors).not.toHaveBeenCalled()
- errors.mockRestore()
+ expect(md.tail).not.toHaveBeenCalled()
+ expect(md.render).not.toHaveBeenCalled()
root = createRoot(host) // afterEach unmounts again
})
+ it('a stale answer after a newer one never reaches the renderer', async () => {
+ mount()
+ act(() => root.render(<TerminalMarkdownView nodeId="n2" capture={capture} hint="" />))
+ pending[1].resolve('newest')
+ await settle()
+ md.tail.mockClear()
+ md.render.mockClear()
+ pending[0].resolve('stale')
+ await settle()
+ expect(md.tail).not.toHaveBeenCalled()
+ expect(md.render).not.toHaveBeenCalled()
+ })
+
+ it('a renderer that throws lands in the error state, and ↻ works again', async () => {
+ md.throwRender = true
+ mount()
+ pending[0].resolve('boom')
+ await settle()
+ expect(content().textContent).toBe('Could not capture this terminal’s output.')
+ expect(refresh().disabled).toBe(false)
+ md.throwRender = false
+ act(() => refresh().click())
+ pending[1].resolve('fine now')
+ await settle()
+ expect(content().textContent).toContain('fine now')
+ })
+
it('renders only the last 5000 lines and says how many were cut', async () => {
mount()
pending[0].resolve(Array.from({ length: 5003 }, (_, i) => `row${i + 1}`).join('\n'))
diff --git a/src/renderer/nodes/TerminalMarkdownView.tsx b/src/renderer/nodes/TerminalMarkdownView.tsx
index faddd6365..1e4d40b5e 100644
--- a/src/renderer/nodes/TerminalMarkdownView.tsx
+++ b/src/renderer/nodes/TerminalMarkdownView.tsx
@@ -51,8 +51,11 @@ export function TerminalMarkdownView({ nodeId, capture, hint }: TerminalMarkdown
const run = useCallback(() => {
const token = ++reqRef.current
setCapturing(true)
- void Promise.all([captureRef.current(nodeId), import('../lib/terminalOutputMarkdown')]).then(
- ([text, md]) => {
+ // `.then(ok).catch(fail)`, not `.then(ok, fail)`: a throw INSIDE the fulfilment handler (the
+ // renderer on some pathological capture) must land in the error state too — with the two-arg
+ // form it escaped as an unhandled rejection and left `capturing` true, ↻ disabled for good.
+ void Promise.all([captureRef.current(nodeId), import('../lib/terminalOutputMarkdown')])
+ .then(([text, md]) => {
if (token !== reqRef.current) return
const tail = md.tailOutputLines(text)
setView(
@@ -68,13 +71,12 @@ export function TerminalMarkdownView({ nodeId, capture, hint }: TerminalMarkdown
: { kind: 'empty' }
)
setCapturing(false)
- },
- () => {
+ })
+ .catch(() => {
if (token !== reqRef.current) return
setView({ kind: 'error' })
setCapturing(false)
- }
- )
+ })
}, [nodeId])
useEffect(() => {
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 35eafa2b7..2207e31e6 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -174,7 +174,7 @@ import { coldSelfHealVerdict } from '../terminal/cold-self-heal'
import { WakeInputBuffer } from '../terminal/wake-input-buffer'
import { FindBar } from '../components/FindBar'
import { TerminalMarkdownView } from './TerminalMarkdownView'
-import { useMdModeFocus } from '../terminal/useMdModeFocus'
+import { focusXtermUnlessCovered, useMdModeFocus } from '../terminal/useMdModeFocus'
import { IconChat, IconChevronDown, IconChevronRight, IconClose, IconEye, IconEyeOff, IconGrid, IconMic, IconMoveTo, IconPlay, IconReload, IconSearch, IconSparkle } from '../components/icons'
import { NodeLabels } from '../components/kanban/NodeLabels'
import { Tooltip } from '../components/Tooltip'
@@ -1508,6 +1508,10 @@ export function TerminalNode({
const titleEditStartRef = useRef('')
const skipBlurRef = useRef(false)
const mdMode = !!data.mdMode
+ // Read by the "take the keyboard" paths (dwell, click, sidebar jump), which are closures that
+ // outlive a render: while the ⌘M view covers the terminal they must not focus the hidden xterm.
+ const mdModeRef = useRef(mdMode)
+ mdModeRef.current = mdMode
const collapsed = !!data.collapsed
// "This node must NOT hold a grid on the shared canvas right now." Four states, two reasons:
//
@@ -4986,7 +4990,7 @@ export function TerminalNode({
const aimed = opts?.ack !== false
if (dwellRef.current) clearTimeout(dwellRef.current)
if (aimed) setArmed(false)
- termRef.current?.focus()
+ focusXtermUnlessCovered(termRef.current, mdModeRef.current)
useTerminalFocus.getState().remember(id)
useAgentStatus.getState().setActive(id, true)
if (aimed) {
@@ -5022,7 +5026,7 @@ export function TerminalNode({
return
}
setArmed(false)
- termRef.current?.focus()
+ focusXtermUnlessCovered(termRef.current, mdModeRef.current)
useTerminalFocus.getState().remember(id)
useAgentStatus.getState().setActive(id, true)
useAgentStatus.getState().clearUnread(id)
@@ -5307,7 +5311,7 @@ export function TerminalNode({
// The ⌘M face (output view or ChatPanel) covers the xterm: blur it on entry so keystrokes stop
// reaching a pane nobody can see, and hand focus back on exit only if it had it on entry.
- useMdModeFocus(mdMode, () => termRef.current)
+ useMdModeFocus(mdMode, () => termRef.current, () => rootRef.current)
// Full-scrollback capture for the output view (TerminalMarkdownView owns the lifecycle: capture on
// mount, ↻, stale-answer guard, line cap, scroll-to-latest). Session-bound, so a relay tab
// captures the PEER's pane.
diff --git a/src/renderer/terminal/useMdModeFocus.test.tsx b/src/renderer/terminal/useMdModeFocus.test.tsx
index 0febc1bc9..0aca42b46 100644
--- a/src/renderer/terminal/useMdModeFocus.test.tsx
+++ b/src/renderer/terminal/useMdModeFocus.test.tsx
@@ -2,7 +2,9 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react'
-import { useMdModeFocus, type FocusableTerm } from './useMdModeFocus'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { focusXtermUnlessCovered, mayRestoreFocus, useMdModeFocus, type FocusableTerm } from './useMdModeFocus'
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
@@ -28,9 +30,11 @@ function fakeTerm(): FocusableTerm & { calls: string[] } {
let host: HTMLDivElement
let root: Root
let term: ReturnType<typeof fakeTerm> | null
+/** The node root: the terminal's textarea lives inside it, like a real `.term-node`. */
+let nodeRoot: HTMLDivElement
function Harness({ mdMode }: { mdMode: boolean }) {
- useMdModeFocus(mdMode, () => term)
+ useMdModeFocus(mdMode, () => term, () => nodeRoot)
return null
}
@@ -40,7 +44,10 @@ beforeEach(() => {
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
+ nodeRoot = document.createElement('div')
+ document.body.appendChild(nodeRoot)
term = fakeTerm()
+ nodeRoot.appendChild(term.textarea!)
})
afterEach(() => {
@@ -78,6 +85,31 @@ describe('useMdModeFocus', () => {
expect(document.activeElement).toBe(other)
})
+ it('had focus on entry, but the user focused an input elsewhere meanwhile → no focus()', () => {
+ render(false)
+ term!.focus()
+ render(true)
+ const elsewhere = document.createElement('input')
+ document.body.appendChild(elsewhere)
+ elsewhere.focus()
+ term!.calls.length = 0
+ render(false)
+ expect(term!.calls).not.toContain('focus')
+ expect(document.activeElement).toBe(elsewhere)
+ })
+
+ it('restores when focus meanwhile stayed inside this node (e.g. the view\'s own controls)', () => {
+ render(false)
+ term!.focus()
+ render(true)
+ const insideNode = document.createElement('button')
+ nodeRoot.appendChild(insideNode)
+ insideNode.focus()
+ term!.calls.length = 0
+ render(false)
+ expect(term!.calls).toEqual(['focus'])
+ })
+
it('never focuses on first mount, whatever the mode', () => {
render(false)
expect(term!.calls).toEqual([])
@@ -90,3 +122,43 @@ describe('useMdModeFocus', () => {
render(false)
})
})
+
+describe('mayRestoreFocus', () => {
+ const body = document.createElement('body')
+ const nodeRoot = document.createElement('div')
+ const inside = document.createElement('span')
+ nodeRoot.appendChild(inside)
+ const outside = document.createElement('input')
+
+ it('allows it when focus is nowhere or inside the node', () => {
+ expect(mayRestoreFocus(null, nodeRoot, body)).toBe(true)
+ expect(mayRestoreFocus(body, nodeRoot, body)).toBe(true)
+ expect(mayRestoreFocus(inside, nodeRoot, body)).toBe(true)
+ })
+
+ it('refuses when focus is somewhere else, or the node root is unknown', () => {
+ expect(mayRestoreFocus(outside, nodeRoot, body)).toBe(false)
+ expect(mayRestoreFocus(inside, null, body)).toBe(false)
+ })
+})
+
+describe('focusXtermUnlessCovered', () => {
+ it('focuses only while the ⌘M view is not covering the terminal', () => {
+ let n = 0
+ const t: FocusableTerm = { blur: () => {}, focus: () => void n++ }
+ focusXtermUnlessCovered(t, true)
+ expect(n).toBe(0)
+ focusXtermUnlessCovered(t, false)
+ expect(n).toBe(1)
+ focusXtermUnlessCovered(null, false)
+ })
+
+ it('is what every TerminalNode "take the keyboard" path calls (no bare xterm focus left)', () => {
+ // Source pin: the dwell and enterNow are closures deep in a 6000-line component that cannot
+ // be mounted here; a bare `termRef.current?.focus()` reintroduced there would route
+ // 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)
+ })
+})
diff --git a/src/renderer/terminal/useMdModeFocus.ts b/src/renderer/terminal/useMdModeFocus.ts
index 4ecab569d..65787ff82 100644
--- a/src/renderer/terminal/useMdModeFocus.ts
+++ b/src/renderer/terminal/useMdModeFocus.ts
@@ -16,14 +16,24 @@ export interface FocusableTerm {
* opened. Restoring unconditionally would pull focus out of whatever the user moved to meanwhile
* (another node, a text field) the moment they toggle the view off from the menu.
*
+ * Entry state alone is not enough to restore: the view can stay open for minutes, and the user may
+ * have moved on to a text field elsewhere (the view is toggled from the context menu or ⌘K, not
+ * only by ⌘M over the node). So exit also asks where focus IS (`mayRestoreFocus`).
+ *
* `getTerm` is read at transition time, not captured: the node's xterm can be released, parked or
* respawned while the view is open, and a stale instance must never be focused.
*/
-export function useMdModeFocus(mdMode: boolean, getTerm: () => FocusableTerm | null | undefined): void {
+export function useMdModeFocus(
+ mdMode: boolean,
+ getTerm: () => FocusableTerm | null | undefined,
+ getRoot: () => Element | null | undefined
+): void {
const restoreRef = useRef(false)
const prevRef = useRef(mdMode)
const getTermRef = useRef(getTerm)
getTermRef.current = getTerm
+ const getRootRef = useRef(getRoot)
+ getRootRef.current = getRoot
useEffect(() => {
if (prevRef.current === mdMode) return
@@ -35,7 +45,31 @@ export function useMdModeFocus(mdMode: boolean, getTerm: () => FocusableTerm | n
term?.blur()
} else if (restoreRef.current) {
restoreRef.current = false
- term?.focus()
+ if (mayRestoreFocus(document.activeElement, getRootRef.current(), document.body)) term?.focus()
}
}, [mdMode])
}
+
+/**
+ * Whether exiting the ⌘M view may hand focus back to the xterm: only when focus is nowhere
+ * (null / `<body>` — typically because the view's own ↻ button just unmounted with it) or still
+ * inside this node. Focus anywhere else belongs to something the user chose meanwhile.
+ */
+export function mayRestoreFocus(
+ active: Element | null,
+ nodeRoot: Element | null | undefined,
+ body: Element | null
+): boolean {
+ if (!active || active === body) return true
+ return !!nodeRoot && nodeRoot.contains(active)
+}
+
+/**
+ * The xterm focus call for every "take the keyboard" path in TerminalNode (hover dwell, click,
+ * sidebar / notification jump, window-activation restore). While the ⌘M view covers the terminal
+ * it must NOT focus: the overlay sits inside the node body, so a dwell over it — or a sidebar jump
+ * to the node — used to route keystrokes into a pane nobody could see.
+ */
+export function focusXtermUnlessCovered(term: FocusableTerm | null | undefined, covered: boolean): void {
+ if (!covered) term?.focus()
+}