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(md-view): output view lifecycle — focus, freshness, size
review77a9d04fb808
diff --git a/CLAUDE.md b/CLAUDE.mdindex 681ee949c..5804dc55e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1254,7 +1254,13 @@ session.click-to-rename title, ✦ AI-name, ×. Body has a **hover guard** overlay: dwell`settings.panHoverDelay` (default 600 ms) before the terminal takes focus — before that,drag = move node, scroll = pan canvas. **Cmd/Ctrl+M** (while hovered) toggles a markdown- render of the captured output. Tag chips via `NodeTags`.+ render of the captured output — `nodes/TerminalMarkdownView.tsx`, which takes a node id + a+ `capture` function (no React Flow context, so the kanban card modal can reuse it) and owns the+ 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`.**Selection + copy is tmux's** (its mouse is on — see the tmux section): drag to select, wheel toscroll tmux's history. A drag copies via copy-mode, and tmux emits **OSC 52** to the client, whosehandler writes the **system clipboard** — the one copy path on every platform *and* over SSH (nodiff --git a/src/renderer/lib/terminalOutputMarkdown.test.ts b/src/renderer/lib/terminalOutputMarkdown.test.tsindex cdc18c8e0..0c6950521 100644--- a/src/renderer/lib/terminalOutputMarkdown.test.ts+++ b/src/renderer/lib/terminalOutputMarkdown.test.ts@@ -1,7 +1,7 @@// @vitest-environment jsdomimport { describe, expect, it } from 'vitest'import { marked } from 'marked'-import { renderTerminalOutput } from './terminalOutputMarkdown'+import { MD_OUTPUT_MAX_LINES, renderTerminalOutput, tailOutputLines } from './terminalOutputMarkdown'import { renderMarkdown } from './markdown'/** Visible text of the rendered HTML, the way a user reads it. */@@ -78,3 +78,32 @@ describe('renderTerminalOutput', () => {expect(renderMarkdown('<b>x</b>')).toBe('<p><b>x</b></p>\n')})})++describe('tailOutputLines', () => {+ const lines = (n: number) => Array.from({ length: n }, (_, i) => `line ${i + 1}`).join('\n')++ it('is 5000 lines', () => {+ expect(MD_OUTPUT_MAX_LINES).toBe(5000)+ })++ it('keeps output at or under the cap whole', () => {+ expect(tailOutputLines(lines(3), 3)).toEqual({ text: lines(3), dropped: 0 })+ })++ it('keeps only the LAST max lines and reports how many were dropped', () => {+ const r = tailOutputLines(lines(10), 4)+ expect(r.dropped).toBe(6)+ expect(r.text).toBe('line 7\nline 8\nline 9\nline 10')+ })++ it('does not let capture-pane trailing padding eat the budget', () => {+ const r = tailOutputLines(`${lines(4)}\n\n\n \n\n`, 4)+ expect(r).toEqual({ text: lines(4), dropped: 0 })+ })++ it('defaults to MD_OUTPUT_MAX_LINES and handles CRLF + empty input', () => {+ expect(tailOutputLines(lines(MD_OUTPUT_MAX_LINES + 2)).dropped).toBe(2)+ expect(tailOutputLines('a\r\nb\r\nc', 2)).toEqual({ text: 'b\nc', dropped: 1 })+ expect(tailOutputLines('')).toEqual({ text: '', dropped: 0 })+ })+})diff --git a/src/renderer/lib/terminalOutputMarkdown.ts b/src/renderer/lib/terminalOutputMarkdown.tsindex 8491bac25..da9df9445 100644--- a/src/renderer/lib/terminalOutputMarkdown.ts+++ b/src/renderer/lib/terminalOutputMarkdown.ts@@ -58,3 +58,26 @@ export function renderTerminalOutput(text: string): string {const html = terminalMarked.parse(src) as stringreturn DOMPurify.sanitize(html)}++/**+ * How many lines of captured output the ⌘M view renders. The capture is the FULL scrollback — up+ * to the tmux `history-limit` (50k lines), possibly over SSH — and marked + DOMPurify + layout of+ * all of it runs synchronously on the renderer thread. The newest output is what the view is for+ * (it opens scrolled to the bottom), so the oldest lines are the ones dropped.+ */+export const MD_OUTPUT_MAX_LINES = 5000++/** The last `max` lines of a capture (after dropping capture-pane's trailing blank padding, so the+ * padding cannot spend the budget), and how many older lines were cut. A cut can land inside a+ * fenced block, which then renders from that point as the other side of the fence — accepted:+ * the cut is announced, and the tail is what the reader came for. */+export function tailOutputLines(+ text: string,+ max: number = MD_OUTPUT_MAX_LINES+): { text: string; dropped: number } {+ const trimmed = trimCapture(text || '')+ if (!trimmed) return { text: '', dropped: 0 }+ const lines = trimmed.split('\n')+ if (lines.length <= max) return { text: trimmed, dropped: 0 }+ return { text: lines.slice(lines.length - max).join('\n'), dropped: lines.length - max }+}diff --git a/src/renderer/nodes/TerminalMarkdownView.test.tsx b/src/renderer/nodes/TerminalMarkdownView.test.tsxnew file mode 100644index 000000000..53f098ad2--- /dev/null+++ b/src/renderer/nodes/TerminalMarkdownView.test.tsx@@ -0,0 +1,153 @@+// @vitest-environment jsdom+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import { createRoot, type Root } from 'react-dom/client'+import { act } from 'react'+import { TerminalMarkdownView } from './TerminalMarkdownView'++// Standalone harness — react-dom only, no testing-library (same shape as useDiscardWhenHidden).+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++interface Deferred {+ resolve: (text: string) => void+ reject: (err: unknown) => void+}++let host: HTMLDivElement+let root: Root+let pending: Deferred[]+let capture: ReturnType<typeof vi.fn<(id: string) => Promise<string>>>++// Warm the lazily imported renderer once, so each test's `settle()` only has to wait for its own+// promises and not for vite to transform marked + DOMPurify on first use.+beforeAll(async () => {+ await import('../lib/terminalOutputMarkdown')+})++beforeEach(() => {+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+ pending = []+ capture = vi.fn(+ () =>+ new Promise<string>((resolve, reject) => {+ pending.push({ resolve, reject })+ })+ )+})++afterEach(() => {+ act(() => root.unmount())+ host.remove()+})++/** Let the capture promise + the lazy `import()` of the renderer settle. */+async function settle(): Promise<void> {+ for (let i = 0; i < 5; i++) await act(async () => { await new Promise((r) => setTimeout(r, 0)) })+}++function mount(): void {+ act(() => root.render(<TerminalMarkdownView nodeId="n1" capture={capture} hint="⌘M to exit" />))+}++const content = () => host.querySelector('.term-md__content') as HTMLElement+const refresh = () => host.querySelector('.term-md__refresh') as HTMLButtonElement++describe('TerminalMarkdownView', () => {+ it('captures the node on mount, shows Capturing…, then the rendered output', async () => {+ mount()+ expect(capture).toHaveBeenCalledWith('n1')+ expect(content().textContent).toBe('Capturing…')+ expect(refresh().disabled).toBe(true)+ pending[0].resolve('$ echo <stdin>\nline two\n\n\n')+ await settle()+ expect(content().innerHTML).toContain('<stdin>')+ expect(content().innerHTML).toContain('<br>')+ expect(refresh().disabled).toBe(false)+ expect(host.querySelector('.term-md__hint')?.textContent).toBe('⌘M to exit')+ })++ it("says so when the capture is empty — '' is an answer, not a blank page", async () => {+ mount()+ pending[0].resolve('\n\n \n')+ await settle()+ expect(content().textContent).toBe('Nothing captured from this terminal.')+ })++ it('reports a failed capture as a failure, never as empty output', async () => {+ mount()+ pending[0].reject(new Error('ssh down'))+ await settle()+ expect(content().textContent).toBe('Could not capture this terminal’s output.')+ })++ it('↻ re-captures, keeping the old output visible meanwhile', async () => {+ mount()+ pending[0].resolve('first')+ await settle()+ act(() => refresh().click())+ expect(capture).toHaveBeenCalledTimes(2)+ expect(content().textContent).toContain('first')+ expect(host.querySelector('.term-md__bar')?.textContent).toContain('Capturing…')+ pending[1].resolve('second')+ await settle()+ expect(content().textContent).toContain('second')+ })++ it('drops an older answer that lands after a newer one', async () => {+ mount()+ pending[0].resolve('first')+ await settle()+ act(() => refresh().click()) // request 2+ // Re-enable by hand is not possible while capturing, so drive a third request by remounting+ // the view on a new node id — the same token path.+ act(() => root.render(<TerminalMarkdownView nodeId="n2" capture={capture} hint="" />))+ expect(capture).toHaveBeenLastCalledWith('n2')+ pending[2].resolve('newest')+ await settle()+ pending[1].resolve('stale')+ await settle()+ expect(content().textContent).toContain('newest')+ expect(content().textContent).not.toContain('stale')+ })++ it('ignores an answer that arrives after unmount', async () => {+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {})+ mount()+ act(() => root.unmount())+ pending[0].resolve('late')+ await settle()+ expect(errors).not.toHaveBeenCalled()+ errors.mockRestore()+ root = createRoot(host) // afterEach unmounts again+ })++ 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'))+ await settle()+ const text = content().textContent ?? ''+ expect(text).not.toContain('row3\n')+ expect(text.startsWith('row4')).toBe(true)+ expect(text).toContain('row5003')+ expect(host.querySelector('.term-md__bar')?.textContent).toContain('Last 5,000 lines (3 older not shown)')+ })++ it('opens scrolled to the bottom (latest output), and again after a refresh', async () => {+ const desc = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollHeight')+ Object.defineProperty(HTMLElement.prototype, 'scrollHeight', { configurable: true, get: () => 900 })+ try {+ mount()+ pending[0].resolve('a\nb')+ await settle()+ expect(content().scrollTop).toBe(900)+ content().scrollTop = 0+ act(() => refresh().click())+ pending[1].resolve('a\nb')+ await settle()+ expect(content().scrollTop).toBe(900)+ } finally {+ if (desc) Object.defineProperty(HTMLElement.prototype, 'scrollHeight', desc)+ }+ })+})diff --git a/src/renderer/nodes/TerminalMarkdownView.tsx b/src/renderer/nodes/TerminalMarkdownView.tsxnew file mode 100644index 000000000..faddd6365--- /dev/null+++ b/src/renderer/nodes/TerminalMarkdownView.tsx@@ -0,0 +1,138 @@+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'+import { IconReload } from '../components/icons'+import { Tooltip } from '../components/Tooltip'++/**+ * The ⌘M "output" face of a terminal: its captured scrollback rendered as readable markdown.+ *+ * Deliberately free of React Flow and of any node state — it is handed a node id and a `capture`+ * function, so the kanban card modal can mount the same view over the same session (the canvas+ * node passes its session-bound `api.pty.capture`). The `.term-md__content` class is load-bearing+ * beyond styling: the document-level link-click handler keys on it.+ *+ * Lifecycle rules this component owns (each was a bug in the inline one-shot version):+ * - It captures on MOUNT, so re-entering ⌘M never shows the previous entry's stale HTML, and it+ * shows "Capturing…" until the answer lands; ↻ re-captures in place.+ * - Every capture carries a request token: an older answer that resolves after a newer one (a+ * refresh during a slow SSH capture) is dropped, and nothing is set after unmount.+ * - '' is its own answer ("Nothing captured…"), and a REJECTED capture is not '' — a failure+ * rendered as an empty page would read as "this terminal printed nothing".+ * - Only the last `MD_OUTPUT_MAX_LINES` lines are rendered (announced when cut), and each fresh+ * render scrolls to the bottom — the newest output is what the view is opened for.+ * `marked` + DOMPurify stay a lazy import: the canvas node is on the startup path, this renderer+ * runs only after someone presses ⌘M.+ */+export interface TerminalMarkdownViewProps {+ /** The terminal's persist key (node id) — what `capture` is asked for. */+ nodeId: string+ /** Full-scrollback capture of that session (`(id) => api.pty.capture(id, true)` on the canvas). */+ capture: (nodeId: string) => Promise<string>+ /** Right-hand bar text, e.g. "⌘M to exit" (the caller knows its own exit chord). */+ hint: string+}++type ViewState =+ | { kind: 'loading' }+ | { kind: 'empty' }+ | { kind: 'error' }+ | { kind: 'ready'; html: string; kept: number; dropped: number }++export function TerminalMarkdownView({ nodeId, capture, hint }: TerminalMarkdownViewProps) {+ const [view, setView] = useState<ViewState>({ kind: 'loading' })+ const [capturing, setCapturing] = useState(true)+ const contentRef = useRef<HTMLDivElement | null>(null)+ // Monotonic request token; bumped on unmount too, so a late answer matches nothing.+ const reqRef = useRef(0)+ // The latest `capture` without making it an effect dependency: a caller passing an inline+ // arrow must not re-capture on every render.+ const captureRef = useRef(capture)+ captureRef.current = capture++ const run = useCallback(() => {+ const token = ++reqRef.current+ setCapturing(true)+ void Promise.all([captureRef.current(nodeId), import('../lib/terminalOutputMarkdown')]).then(+ ([text, md]) => {+ if (token !== reqRef.current) return+ const tail = md.tailOutputLines(text)+ setView(+ tail.text+ ? {+ kind: 'ready',+ html: md.renderTerminalOutput(tail.text),+ // Read off the lazy module, not imported statically — a static import of the+ // constant would drag marked into the startup chunk with it.+ kept: md.MD_OUTPUT_MAX_LINES,+ dropped: tail.dropped+ }+ : { kind: 'empty' }+ )+ setCapturing(false)+ },+ () => {+ if (token !== reqRef.current) return+ setView({ kind: 'error' })+ setCapturing(false)+ }+ )+ }, [nodeId])++ useEffect(() => {+ run()+ return () => {+ reqRef.current+++ }+ }, [run])++ // After each fresh render, jump to the latest output. Keyed on the view object itself, so a+ // refresh that produced identical HTML still re-anchors to the bottom.+ useLayoutEffect(() => {+ const el = contentRef.current+ if (el && view.kind === 'ready') el.scrollTop = el.scrollHeight+ }, [view])++ return (+ <div className="term-md nodrag nowheel">+ <div className="term-md__bar">+ <span className="term-md__title">+ Markdown+ {capturing && view.kind !== 'loading' && (+ <span className="term-md__status"> · Capturing…</span>+ )}+ {view.kind === 'ready' && view.dropped > 0 && (+ <span className="term-md__status">+ {' '}+ · Last {view.kept.toLocaleString('en-US')} lines ({view.dropped.toLocaleString('en-US')} older not+ shown)+ </span>+ )}+ </span>+ <span className="term-md__actions">+ <Tooltip label="Refresh — capture the terminal again">+ <button+ type="button"+ className="term-md__refresh"+ aria-label="Refresh"+ disabled={capturing}+ onClick={run}+ >+ <IconReload />+ </button>+ </Tooltip>+ <span className="term-md__hint">{hint}</span>+ </span>+ </div>+ {view.kind === 'ready' ? (+ <div ref={contentRef} className="term-md__content" dangerouslySetInnerHTML={{ __html: view.html }} />+ ) : (+ <div className="term-md__content term-md__content--placeholder">+ {view.kind === 'loading'+ ? 'Capturing…'+ : view.kind === 'empty'+ ? 'Nothing captured from this terminal.'+ : 'Could not capture this terminal’s output.'}+ </div>+ )}+ </div>+ )+}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 16a6611ba..35eafa2b7 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -173,6 +173,8 @@ import { shouldAutoWake, shouldColdResume } from '../terminal/hibernation-policyimport { 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 { 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'@@ -1428,7 +1430,6 @@ export function TerminalNode({}}}, [focused])- const [mdHtml, setMdHtml] = useState('')const [editingTitle, setEditingTitle] = useState(false)const hoveredRef = useRef(false)// Render-fresh respawnNonce for the lifecycle cleanup: React updates this ref (render) before@@ -5304,23 +5305,13 @@ export function TerminalNode({return () => window.removeEventListener('keydown', onKey, true)}, [])- // When markdown mode turns on, capture the terminal output and render it. Skipped when the- // chat panel is active (it loads its own structured transcript), but still runs as the- // fallback when a chat-capable node has no sessionId yet.- useEffect(() => {- if (data.mdMode && !useChat) {- // Full scrollback (not just the visible viewport) so the whole session renders.- // `marked` + DOMPurify are imported HERE rather than at module scope: this node is on the- // startup path (it is what the canvas is made of), the markdown renderer is not — it runs- // only after someone presses ⌘M. The capture is already a round trip to main, so the extra- // chunk fetch is not even on a path the user can perceive.- // `renderTerminalOutput`, not `renderMarkdown`: output keeps its line breaks, and tag-like- // text (`echo <stdin>`) shows as text instead of being parsed as HTML and stripped.- void Promise.all([api.pty.capture(id, true), import('../lib/terminalOutputMarkdown')]).then(- ([text, md]) => setMdHtml(md.renderTerminalOutput(text))- )- }- }, [data.mdMode, id, useChat])+ // 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)+ // 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.+ const captureFull = useCallback((nodeId: string) => api.pty.capture(nodeId, true), [api])// Unread = the agent finished (not still working/waiting/blocked) while you weren't looking.// Drives both the header badge and a node-wide glow so it's obvious at a glance.@@ -6032,13 +6023,11 @@ export function TerminalNode({/></Suspense>) : (- <div className="term-md nodrag nowheel">- <div className="term-md__bar">- <span>Markdown</span>- <span className="term-md__hint">{mdChip ? `${mdChip} to exit` : 'Exit'}</span>- </div>- <div className="term-md__content" dangerouslySetInnerHTML={{ __html: mdHtml }} />- </div>+ <TerminalMarkdownView+ nodeId={id}+ capture={captureFull}+ hint={mdChip ? `${mdChip} to exit` : 'Exit'}+ />))}</div></div>diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex e30fe13a7..6109f10e7 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -2934,6 +2934,7 @@ body,display: flex;align-items: center;justify-content: space-between;+ gap: 8px;padding: 5px 10px;font-size: 11px;color: var(--muted);@@ -2945,6 +2946,55 @@ body,opacity: 0.8;}+.term-md__title {+ min-width: 0;+ overflow: hidden;+ white-space: nowrap;+ text-overflow: ellipsis;+}++.term-md__actions {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ flex-shrink: 0;+}++/* ↻ re-capture — same shape as the node header's small icon buttons. */+.term-md__refresh {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 20px;+ height: 20px;+ padding: 0;+ background: transparent;+ border: none;+ border-radius: 5px;+ color: var(--muted);+ cursor: pointer;+}++.term-md__refresh svg {+ width: 13px;+ height: 13px;+}++.term-md__refresh:hover:not(:disabled) {+ background: rgba(var(--tint-rgb), 0.1);+ color: var(--text);+}++.term-md__refresh:disabled {+ opacity: 0.45;+ cursor: default;+}++/* "Capturing…" / "Nothing captured…" / a failed capture — a sentence, not rendered output. */+.term-md__content--placeholder {+ color: var(--muted);+}+.term-md__content {flex: 1;min-height: 0;diff --git a/src/renderer/terminal/useMdModeFocus.test.tsx b/src/renderer/terminal/useMdModeFocus.test.tsxnew file mode 100644index 000000000..0febc1bc9--- /dev/null+++ b/src/renderer/terminal/useMdModeFocus.test.tsx@@ -0,0 +1,92 @@+// @vitest-environment jsdom+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'++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++/** A stand-in for xterm: its helper textarea is what holds DOM focus while the terminal types. */+function fakeTerm(): FocusableTerm & { calls: string[] } {+ const textarea = document.createElement('textarea')+ document.body.appendChild(textarea)+ const calls: string[] = []+ return {+ textarea,+ calls,+ blur: () => {+ calls.push('blur')+ textarea.blur()+ },+ focus: () => {+ calls.push('focus')+ textarea.focus()+ }+ }+}++let host: HTMLDivElement+let root: Root+let term: ReturnType<typeof fakeTerm> | null++function Harness({ mdMode }: { mdMode: boolean }) {+ useMdModeFocus(mdMode, () => term)+ return null+}++const render = (mdMode: boolean) => act(() => root.render(<Harness mdMode={mdMode} />))++beforeEach(() => {+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+ term = fakeTerm()+})++afterEach(() => {+ act(() => root.unmount())+ document.body.innerHTML = ''+})++describe('useMdModeFocus', () => {+ it('blurs the terminal when the view opens, so keystrokes stop reaching the hidden pane', () => {+ render(false)+ term!.focus()+ render(true)+ expect(document.activeElement).not.toBe(term!.textarea)+ expect(term!.calls).toContain('blur')+ })++ it('gives focus back on exit when the terminal had it on entry', () => {+ render(false)+ term!.focus()+ render(true)+ term!.calls.length = 0+ render(false)+ expect(term!.calls).toEqual(['focus'])+ expect(document.activeElement).toBe(term!.textarea)+ })++ it('does NOT steal focus on exit when the terminal did not have it on entry', () => {+ const other = document.createElement('input')+ document.body.appendChild(other)+ render(false)+ other.focus()+ render(true)+ render(false)+ expect(term!.calls).not.toContain('focus')+ expect(document.activeElement).toBe(other)+ })++ it('never focuses on first mount, whatever the mode', () => {+ render(false)+ expect(term!.calls).toEqual([])+ })++ it('tolerates a terminal that does not exist (released / not yet spawned)', () => {+ term = null+ render(false)+ render(true)+ render(false)+ })+})diff --git a/src/renderer/terminal/useMdModeFocus.ts b/src/renderer/terminal/useMdModeFocus.tsnew file mode 100644index 000000000..4ecab569d--- /dev/null+++ b/src/renderer/terminal/useMdModeFocus.ts@@ -0,0 +1,41 @@+import { useEffect, useRef } from 'react'++/** The slice of an xterm `Terminal` this hook touches (its helper textarea holds DOM focus). */+export interface FocusableTerm {+ readonly textarea?: HTMLTextAreaElement+ blur(): void+ focus(): void+}++/**+ * Focus hand-off for a terminal node's ⌘M face (the output view AND the ChatPanel).+ *+ * Opening the view covers the xterm but used to leave it focused, so every keystroke kept flowing+ * into a pane the user could no longer see — into an agent's composer or a shell prompt. On entry+ * the terminal is blurred; on exit focus goes back ONLY if the terminal had it when the view+ * 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.+ *+ * `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 {+ const restoreRef = useRef(false)+ const prevRef = useRef(mdMode)+ const getTermRef = useRef(getTerm)+ getTermRef.current = getTerm++ useEffect(() => {+ if (prevRef.current === mdMode) return+ prevRef.current = mdMode+ const term = getTermRef.current()+ if (mdMode) {+ const ta = term?.textarea+ restoreRef.current = !!ta && document.activeElement === ta+ term?.blur()+ } else if (restoreRef.current) {+ restoreRef.current = false+ term?.focus()+ }+ }, [mdMode])+}