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(chat): composer review round 1 — focus on flip, picker in-flight guard, shortcut dictation

reviewf466d56a790c
diff --git a/CLAUDE.md b/CLAUDE.md
index 88ece919a..6f623375e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2572,6 +2572,20 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
terminal equivalent. Surfaces: Desktop + Server Edition identical (dictation and uploads already
bridge — `files.saveUpload`, `speech.*`); SSH nodes upload to the host; kanban card modal shares
ChatPanel and wires both props; relay tabs keep the panel's existing refusal; mobile N/A.
+ Fix-round rules (same day): the composer is its OWN component (`nodes/ChatComposer.tsx`) so the
+ thread and the composer restyle independently. A label click is an explicit "go to the
+ terminal", so the flip FOCUSES the xterm whatever its entry state was
+ (`requestTerminalFocusOnExit(nodeId)` before the state change, consumed once by the node's
+ `useMdModeFocus` — TerminalNode and ModalTerminal both key it by node id). `/model` and `/effort`
+ open LOCAL pickers that fire NO hook, so the gate still reads `done` while one is on screen: the
+ composer holds a picker command in flight (ref + disabled/`aria-disabled` labels, and Enter is
+ swallowed) from click until the flip or failure — a second click would otherwise paste
+ `/model` + Enter INTO the picker, confirming its highlighted row. **Inherent limitation:**
+ returning to ⌘M while a picker is still open reads `done` too, so a chat send or a label click
+ there would type into it — the pane is not observable from here. Shortcut dictation (keyed chord
+ and hold-to-talk) targets the composer holding the caret before the selected terminal (the pane
+ under the view is hidden) via `composerFromElement`; the dispatcher offers keyed dictation in
+ that one text field (`isChatComposerTarget`).
- **Subagent visualization** (agents in `SUBAGENT_CAPABLE`) — `subagent-start`/`subagent-end`
normalized events (from Claude's `PreToolUse`/`PostToolUse` on tool `Agent`/`Task`, correlated
by `tool_use_id`) drive a transient `state/agentNodes.ts` store. Claude launches subagents
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 3493b7de9..d0b4c8a01 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -157,7 +157,7 @@ import { WelcomeScreen } from '../components/WelcomeScreen'
import { CloneRepoDialog } from '../components/CloneRepoDialog'
import { markMobileLaunchSeen, shouldShowMobileLaunch } from '../lib/mobileLaunch'
import type { DictationTarget } from '../components/DictationOverlay'
-import { dictationTargetFromRequest } from '../lib/chatComposerDictation'
+import { composerFromElement, dictationTargetFromRequest } from '../lib/chatComposerDictation'
import { describeOs, REPO_URL } from '../lib/bugReport'
import { shouldReleasePaneFocus } from '../lib/paneFocus'
import {
@@ -2383,12 +2383,27 @@ export function Canvas() {
// The node whose kanban card modal is open (null = none). The dictation shortcut targets THIS
// when set, since no canvas node is selected while the board covers the canvas.
const kanbanModalNodeRef = useRef<string | null>(null)
+ // The ⌘M chat composer holding the caret, as a dictation target (lib/chatComposerDictation.ts).
+ // Both shortcut paths ask it FIRST: with the caret in a composer, the selected terminal is the
+ // hidden pane under the view, and the take belongs in the draft being typed.
+ const focusedComposerDictationTarget = (): DictationTarget | null => {
+ const c = composerFromElement(document.activeElement)
+ if (!c) return null
+ const n = nodesRef.current.find((x) => x.id === c.nodeId)
+ return dictationTargetFromRequest(c, (n?.data.title as string) || 'Untitled')
+ }
const toggleDictation = useCallback(() => {
setDictationOpen((open) => {
if (open) {
setDictationStopSignal((n) => n + 1)
return true
}
+ const composer = focusedComposerDictationTarget()
+ if (composer) {
+ setDictationTarget(composer)
+ setDictationNonce((n) => n + 1)
+ return true
+ }
// A kanban card modal open over the board wins (nothing on the canvas is selected then);
// otherwise fall back to the selected canvas terminal.
const modalId = kanbanModalNodeRef.current
@@ -5054,8 +5069,11 @@ export function Canvas() {
armed = true
heldSince = Date.now()
const sel = nodesRef.current.find((n) => n.selected && n.type === 'terminal')
+ const composer = focusedComposerDictationTarget()
setDictationTarget(
- sel
+ composer
+ ? composer
+ : sel
? {
kind: 'terminal',
nodeId: sel.id,
diff --git a/src/renderer/components/kanban/CardModal.tsx b/src/renderer/components/kanban/CardModal.tsx
index 796f96ea5..d70fcfa09 100644
--- a/src/renderer/components/kanban/CardModal.tsx
+++ b/src/renderer/components/kanban/CardModal.tsx
@@ -36,6 +36,7 @@ import { useSession } from '../../session/session'
// imports from `components/kanban/*`, and none of those re-import CardModal.
import { sshConnectionScope, wakeHibernatedNode } from '../../nodes/TerminalNode'
import { droppedPaths } from '../../terminal/file-drop'
+import { requestTerminalFocusOnExit } from '../../terminal/useMdModeFocus'
import { useProjects } from '../../state/projects'
import type { ProjectKanban } from '@shared/types'
import type { KanbanSession } from './KanbanView'
@@ -559,7 +560,11 @@ export function CardModal({ session, columnTitle, board, onChangeBoard, onClose,
: ''
})
}
- onShowTerminal={() => setMdFor(null)}
+ onShowTerminal={() => {
+ // The picker just opened in the live viewer needs the keyboard.
+ requestTerminalFocusOnExit(session.id)
+ setMdFor(null)
+ }}
/>
</Suspense>
) : (
diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsx
index e67e7df74..a58b8b463 100644
--- a/src/renderer/components/kanban/ModalTerminal.tsx
+++ b/src/renderer/components/kanban/ModalTerminal.tsx
@@ -113,7 +113,7 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch, covere
const termRef = useRef<Terminal | null>(null)
const coveredRef = useRef(covered)
coveredRef.current = covered
- useMdModeFocus(covered, () => termRef.current, () => hostRef.current?.closest('.kanban-modal'))
+ useMdModeFocus(covered, () => termRef.current, () => hostRef.current?.closest('.kanban-modal'), nodeId)
const searchAddonRef = useRef<SearchAddon | null>(null)
// The live pty session + its fit addon, reachable from OUTSIDE the lifecycle effect's closure —
// the appearance effect below has to re-fit and re-REPORT this viewer's grid, and under co-attach
diff --git a/src/renderer/lib/chatComposerDictation.test.ts b/src/renderer/lib/chatComposerDictation.test.ts
index 2e7cf7666..d8546699c 100644
--- a/src/renderer/lib/chatComposerDictation.test.ts
+++ b/src/renderer/lib/chatComposerDictation.test.ts
@@ -1,6 +1,9 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
import {
+ composerFromElement,
deliverToComposer,
dictationTargetFromRequest,
requestComposerDictation,
@@ -63,3 +66,36 @@ describe('composer dictation delivery', () => {
expect(seen).toHaveBeenCalledWith({ nodeId: 'n1', composerId: 'c1' })
})
})
+
+describe('composerFromElement (shortcut dictation with the caret in a composer)', () => {
+ it('finds the composer box around the focused textarea', () => {
+ const box = document.createElement('div')
+ box.setAttribute('data-chat-composer-id', 'c9')
+ box.setAttribute('data-chat-node-id', 'n9')
+ const ta = document.createElement('textarea')
+ box.append(ta)
+ document.body.append(box)
+ expect(composerFromElement(ta)).toEqual({ nodeId: 'n9', composerId: 'c9' })
+ box.remove()
+ })
+
+ it('is null anywhere else, and for no element at all', () => {
+ const ta = document.createElement('textarea')
+ document.body.append(ta)
+ expect(composerFromElement(ta)).toBeNull()
+ expect(composerFromElement(null)).toBeNull()
+ ta.remove()
+ })
+
+ it('both shortcut paths in Canvas ask the focused composer before the selected terminal', () => {
+ // Source pin: Canvas cannot be mounted here. Without the composer check the keyed chord and
+ // hold-to-talk typed the take into the HIDDEN pane under the ⌘M view.
+ const src = readFileSync(resolve(__dirname, '../canvas/Canvas.tsx'), 'utf8').replace(/\r\n/g, '\n')
+ const toggle = src.slice(src.indexOf('const toggleDictation = useCallback'))
+ expect(toggle.indexOf('focusedComposerDictationTarget()')).toBeGreaterThan(-1)
+ expect(toggle.indexOf('focusedComposerDictationTarget()')).toBeLessThan(toggle.indexOf('kanbanModalNodeRef.current'))
+ const hold = src.slice(src.indexOf('armed = true\n heldSince = Date.now()'))
+ expect(hold.indexOf('focusedComposerDictationTarget()')).toBeGreaterThan(-1)
+ expect(hold.indexOf('focusedComposerDictationTarget()')).toBeLessThan(hold.indexOf('setDictationNonce'))
+ })
+})
diff --git a/src/renderer/lib/chatComposerDictation.ts b/src/renderer/lib/chatComposerDictation.ts
index 08ef8d228..deb487faa 100644
--- a/src/renderer/lib/chatComposerDictation.ts
+++ b/src/renderer/lib/chatComposerDictation.ts
@@ -57,3 +57,19 @@ export function subscribeComposerDictation(composerId: string, onText: (text: st
window.addEventListener('nodeterm:chat-dictation', handler)
return () => window.removeEventListener('nodeterm:chat-dictation', handler)
}
+
+/**
+ * The composer that holds keyboard focus, if any — for the SHORTCUT dictation paths (the keyed
+ * chord and hold-to-talk), which otherwise target the selected canvas terminal. With the caret in
+ * a ⌘M composer that terminal is the HIDDEN pane under the view, so a take would be typed into a
+ * pane nobody can see; the composer the user is typing in is what they mean. Read from the
+ * composer box's data attributes (ChatComposer), never from React state: the shortcut handlers
+ * live in Canvas and know nothing of which panel is mounted.
+ */
+export function composerFromElement(el: Element | null | undefined): { nodeId: string; composerId: string } | null {
+ const box = el?.closest?.('[data-chat-composer-id]')
+ if (!box) return null
+ const composerId = box.getAttribute('data-chat-composer-id')
+ const nodeId = box.getAttribute('data-chat-node-id')
+ return composerId && nodeId ? { nodeId, composerId } : null
+}
diff --git a/src/renderer/lib/globalKeybindings.test.ts b/src/renderer/lib/globalKeybindings.test.ts
index 3079e50d3..90acebf44 100644
--- a/src/renderer/lib/globalKeybindings.test.ts
+++ b/src/renderer/lib/globalKeybindings.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, vi } from 'vitest'
import type { CommandId } from '@shared/keybindings'
import { dispatchGlobalKeydown, type GlobalKeydownDeps, type GlobalKeyEvent } from './globalKeybindings'
-import { XTERM_INPUT_CLASS, type ContextElement } from './keyContext'
+import { CHAT_COMPOSER_INPUT_CLASS, XTERM_INPUT_CLASS, type ContextElement } from './keyContext'
const ev = (over: Partial<GlobalKeyEvent>): GlobalKeyEvent => ({
metaKey: false, ctrlKey: false, shiftKey: false, altKey: false, key: '',
@@ -65,6 +65,24 @@ describe('dispatchGlobalKeydown', () => {
dispatchGlobalKeydown(ev({ metaKey: true, key: 't' }), terminal)
expect(dictation).toHaveBeenCalledTimes(1)
})
+ it('keyed dictation IS offered in the ⌘M chat composer (the one text field it fills), and nowhere else that types', () => {
+ const dictation = vi.fn((e: GlobalKeyEvent) => { e.preventDefault(); return true })
+ const g = { keyedDictation: dictation, zoom: noGesture, projectJump: noGesture, copy: noGesture }
+ const composer = deps({
+ gestures: g,
+ activeElement: () => ({ tagName: 'TEXTAREA', classList: { contains: (n: string) => n === CHAT_COMPOSER_INPUT_CLASS } })
+ })
+ expect(dispatchGlobalKeydown(ev({ metaKey: true, key: 'd', shiftKey: true }), composer)).toBe(true)
+ const otherTextarea = deps({ gestures: g, activeElement: () => ({ tagName: 'TEXTAREA', classList: { contains: () => false } }) })
+ expect(dispatchGlobalKeydown(ev({ metaKey: true, key: 'd', shiftKey: true }), otherTextarea)).toBe(false)
+ const onBoard = deps({
+ gestures: g,
+ kanbanOpen: () => true,
+ activeElement: () => ({ tagName: 'TEXTAREA', classList: { contains: (n: string) => n === CHAT_COMPOSER_INPUT_CLASS } })
+ })
+ expect(dispatchGlobalKeydown(ev({ metaKey: true, key: 'd', shiftKey: true }), onBoard)).toBe(false)
+ expect(dictation).toHaveBeenCalledTimes(1)
+ })
it('typing blocks canvas AND app commands (the announced D-typing guard fix)', () => {
const palette = vi.fn(() => true)
const undo = vi.fn(() => true)
diff --git a/src/renderer/lib/globalKeybindings.ts b/src/renderer/lib/globalKeybindings.ts
index cfa87bf41..1825edd73 100644
--- a/src/renderer/lib/globalKeybindings.ts
+++ b/src/renderer/lib/globalKeybindings.ts
@@ -37,7 +37,7 @@ import {
resolveCommandForKeyEvent, COMMANDS_BY_ID,
type CommandId, type KeybindingOverrides
} from '@shared/keybindings'
-import { keyDispatchContextFor, type ContextElement } from './keyContext'
+import { isChatComposerTarget, keyDispatchContextFor, type ContextElement } from './keyContext'
/** Structural key event so node-env tests need no DOM (a real KeyboardEvent satisfies it). */
export interface GlobalKeyEvent {
@@ -82,10 +82,13 @@ export interface GlobalKeydownDeps {
export function dispatchGlobalKeydown(e: GlobalKeyEvent, deps: GlobalKeydownDeps): boolean {
// A child handler (find bar, dialogs, terminal) that already claimed the key wins outright.
if (e.defaultPrevented) return false
- const ctx = keyDispatchContextFor(deps.activeElement(), deps.kanbanOpen(), deps.terminalFirst())
+ const active = deps.activeElement()
+ const ctx = keyDispatchContextFor(active, deps.kanbanOpen(), deps.terminalFirst())
// Keyed dictation predates the registry and may deliberately collide with a default; it
- // keeps first claim, but only in plain app focus (its old guard blocked inputs AND xterm).
- if (!ctx.typing && !ctx.terminal && !ctx.kanbanOpen && deps.gestures.keyedDictation(e)) return true
+ // keeps first claim, but only in plain app focus (its old guard blocked inputs AND xterm) —
+ // or in the ⌘M chat composer, the one text field dictation fills (the take goes into it).
+ const dictationFocus = !ctx.typing || isChatComposerTarget(active)
+ if (dictationFocus && !ctx.terminal && !ctx.kanbanOpen && deps.gestures.keyedDictation(e)) return true
const id = resolveCommandForKeyEvent(e, ctx, deps.overrides(), deps.isMac)
if (id) {
const handler = deps.handlers[id]
diff --git a/src/renderer/lib/keyContext.ts b/src/renderer/lib/keyContext.ts
index 2cfadb6d5..1e014f50e 100644
--- a/src/renderer/lib/keyContext.ts
+++ b/src/renderer/lib/keyContext.ts
@@ -26,6 +26,15 @@ export interface ContextElement {
classList?: { contains(name: string): boolean }
}
+/** The ⌘M chat composer's textarea (nodes/ChatComposer.tsx). A TYPING target like any other, with
+ * one exception the dispatcher makes: keyed dictation is allowed there, because the composer is
+ * the one text field dictation can fill (lib/chatComposerDictation.ts). */
+export const CHAT_COMPOSER_INPUT_CLASS = 'term-chat__input'
+
+export function isChatComposerTarget(el: ContextElement | null): boolean {
+ return el?.classList?.contains(CHAT_COMPOSER_INPUT_CLASS) === true
+}
+
export function isTerminalTarget(el: ContextElement | null): boolean {
return el?.classList?.contains(XTERM_INPUT_CLASS) === true
}
diff --git a/src/renderer/nodes/ChatComposer.tsx b/src/renderer/nodes/ChatComposer.tsx
new file mode 100644
index 000000000..d7c4fd8c2
--- /dev/null
+++ b/src/renderer/nodes/ChatComposer.tsx
@@ -0,0 +1,348 @@
+import { TEXT_NOT_SUBMITTED } from '@shared/text-delivery'
+import {
+ useCallback,
+ useEffect,
+ useId,
+ useRef,
+ useState,
+ type ClipboardEvent as ReactClipboardEvent,
+ type Dispatch,
+ type DragEvent as ReactDragEvent,
+ type KeyboardEvent,
+ type SetStateAction
+} from 'react'
+import { useAgentStatus } from '../state/agentStatus'
+import { useSession } from '../session/session'
+import { useContextUsage } from '../state/contextWindow'
+import { chatSendRefusal } from '../lib/chatSendGate'
+import { chatKeyAction } from '../lib/chatPanel'
+import { appendToComposer, composerLabels, composerPickerCommand, type ComposerPicker } from '../lib/chatComposer'
+import { requestComposerDictation, subscribeComposerDictation } from '../lib/chatComposerDictation'
+import { clipboardImages, pasteHasText, pastedFiles } from '../terminal/file-drop'
+import { IconMic, IconPlus } from '../components/icons'
+import { Spinner } from '../components/Spinner'
+
+export interface ChatComposerProps {
+ nodeId: string
+ sessionId?: string
+ agentId: string
+ /** The node's agent, as the placeholder and tooltips name it. */
+ agentLabel: string
+ /** The draft. Owned by ChatPanel, whose `send` reads it and whose optimistic bubble clears it. */
+ value: string
+ onChange: Dispatch<SetStateAction<string>>
+ /** Enter (not Shift+Enter, not an IME commit). ChatPanel's send re-checks the gate itself. */
+ onSend: () => void
+ placeholder: string
+ /** Read-only session or a send-gate refusal: the whole composer stands down with the textarea. */
+ disabled: boolean
+ /** A picker command the pane refused outright (`sendText` → false): the session is not writable. */
+ onWriteRefused: () => void
+ /** See ChatPanelProps. */
+ pathsForFiles?: (files: File[]) => Promise<string[]>
+ /** See ChatPanelProps. */
+ onShowTerminal?: () => void
+}
+
+/**
+ * The ⌘M chat composer, claude.ai-style: one rounded box, the textarea on top and a toolbar under
+ * it — "+" attach on the left; model label, muted effort label and the mic on the right. The pure
+ * decisions are lib/chatComposer.ts; this is the glue. Split out of ChatPanel so the thread and the
+ * composer can be restyled independently.
+ */
+export function ChatComposer({
+ nodeId,
+ sessionId,
+ agentId,
+ agentLabel,
+ value,
+ onChange,
+ onSend,
+ placeholder,
+ disabled,
+ onWriteRefused,
+ pathsForFiles,
+ onShowTerminal
+}: ChatComposerProps) {
+ const { api } = useSession()
+ const inputRef = useRef<HTMLTextAreaElement>(null)
+ const composerRef = useRef<HTMLDivElement>(null)
+ const fileInputRef = useRef<HTMLInputElement>(null)
+ // Per-MOUNT id, not the node id: the canvas node and the kanban card modal can both have this
+ // session's composer mounted, and a dictated take must land in the one whose mic was clicked.
+ const composerId = useId()
+ // The model / effort the header ContextMeter shows, from the SAME reader (no second transcript
+ // read). Never node-scoped: that is for remote Codex, which never mounts this panel.
+ const usage = useContextUsage({ sessionId, nodeId, scoped: false })
+ const [composerWidth, setComposerWidth] = useState<number | null>(null)
+ const [attachNote, setAttachNote] = useState<{ text: string; failed?: boolean } | null>(null)
+ const [dropping, setDropping] = useState(false)
+ // A picker command on its way into the pane. `/model` and `/effort` are local pickers that fire
+ // NO hook, so the agent state stays `done` and the send gate stays open: a second click (or an
+ // Enter) while the first `sendText` is still in flight — easy over SSH — would paste the command
+ // plus Enter INTO the picker the first one just opened, and Enter confirms its highlighted
+ // option. The ref is the guard (read synchronously); the state only renders it.
+ const pickerBusyRef = useRef(false)
+ const [pickerBusy, setPickerBusy] = useState(false)
+ const labels = composerLabels({ agentId, model: usage?.model, effort: usage?.effort, width: composerWidth })
+
+ // The labels drop by the composer's OWN width (a narrow node, a split card modal), not the
+ // window's. Guarded like the thread's observer: jsdom and old engines have none, and then every
+ // label shows (`composerToolbarLayout(null)`).
+ useEffect(() => {
+ const el = composerRef.current
+ if (!el || typeof ResizeObserver === 'undefined') return
+ const ro = new ResizeObserver((entries?: ResizeObserverEntry[]) => {
+ // No box (collapsed node, display:none) reports 0: keep the last real width rather than
+ // collapsing the toolbar to its narrowest form while nobody can see it.
+ const w = entries?.[entries.length - 1]?.contentRect?.width ?? el.clientWidth
+ if (typeof w === 'number' && w > 0) setComposerWidth(Math.round(w))
+ })
+ ro.observe(el)
+ return () => ro.disconnect()
+ }, [])
+
+ const insertIntoComposer = useCallback(
+ (text: string) => {
+ onChange((cur) => appendToComposer(cur, text))
+ inputRef.current?.focus()
+ },
+ [onChange]
+ )
+
+ // A dictated take for THIS composer lands in the draft, never in the pane.
+ useEffect(() => subscribeComposerDictation(composerId, insertIntoComposer), [composerId, insertIntoComposer])
+
+ const attachFiles = useCallback(
+ async (files: File[]) => {
+ if (!files.length || !pathsForFiles) return
+ setAttachNote({ text: `Attaching ${files.length === 1 ? files[0].name || 'file' : `${files.length} files`}…` })
+ let paths: string[] = []
+ try {
+ paths = await pathsForFiles(files)
+ } catch {
+ paths = []
+ }
+ if (!paths.length) {
+ setAttachNote({ text: 'Could not attach', failed: true })
+ return
+ }
+ setAttachNote(null)
+ // Same shape a drop into the terminal pastes: escaped paths, space-separated, trailing space.
+ insertIntoComposer(paths.join(' ') + ' ')
+ },
+ [pathsForFiles, insertIntoComposer]
+ )
+ useEffect(() => {
+ if (!attachNote?.failed) return
+ const t = setTimeout(() => setAttachNote(null), 2500)
+ return () => clearTimeout(t)
+ }, [attachNote])
+
+ // A drag cancelled with Esc, dropped outside the window or ended by an app switch never sends
+ // the composer a dragleave, which would leave the drop highlight stuck on.
+ useEffect(() => {
+ if (!dropping) return
+ const clear = () => setDropping(false)
+ window.addEventListener('dragend', clear)
+ window.addEventListener('drop', clear)
+ window.addEventListener('blur', clear)
+ return () => {
+ window.removeEventListener('dragend', clear)
+ window.removeEventListener('drop', clear)
+ window.removeEventListener('blur', clear)
+ }
+ }, [dropping])
+
+ // Files arriving by drop or paste become paths in the DRAFT (the terminal's own drop handlers
+ // stand aside while the ⌘M view covers it — `terminalOwnsFileInput`). Stopped here so the
+ // canvas's window-level drop (image nodes) never sees a drop aimed at the composer.
+ const onDragOver = (e: ReactDragEvent) => {
+ if (!pathsForFiles || disabled || !Array.from(e.dataTransfer.types).includes('Files')) return
+ e.preventDefault()
+ e.stopPropagation()
+ e.dataTransfer.dropEffect = 'copy'
+ if (!dropping) setDropping(true)
+ }
+ const onDragLeave = (e: ReactDragEvent) => {
+ const rt = e.relatedTarget as Node | null
+ if (!rt || !(e.currentTarget as HTMLElement).contains(rt)) setDropping(false)
+ }
+ const onDrop = (e: ReactDragEvent) => {
+ setDropping(false)
+ if (!pathsForFiles || disabled) return
+ const files = Array.from(e.dataTransfer.files)
+ if (!files.length) return
+ e.preventDefault()
+ e.stopPropagation()
+ void attachFiles(files)
+ }
+ const onPaste = (e: ReactClipboardEvent<HTMLTextAreaElement>) => {
+ if (!pathsForFiles) return
+ const files = pastedFiles(e.clipboardData)
+ if (files.length) {
+ e.preventDefault()
+ e.stopPropagation()
+ void attachFiles(files)
+ return
+ }
+ // Ordinary text is the textarea's; only an image-only clipboard Chromium filtered to nothing
+ // on its way to a text target asks the async Clipboard API (see `clipboardImages`).
+ if (pasteHasText(e.clipboardData)) return
+ void clipboardImages().then((images) => {
+ if (images.length) void attachFiles(images)
+ })
+ }
+
+ // The model / effort label: type the agent's own picker command into the pane — through the
+ // SAME send gate as a message, re-read at click time (a picker command typed into a dialog would
+ // answer it; into a shell it would run) — then flip to the terminal so the picker is in view.
+ const openPicker = useCallback(
+ async (picker: ComposerPicker) => {
+ if (pickerBusyRef.current) return
+ const command = composerPickerCommand(agentId, picker)
+ if (!command || !onShowTerminal) return
+ if (chatSendRefusal(agentId, useAgentStatus.getState().byId[nodeId] ?? {}) !== null) return
+ pickerBusyRef.current = true
+ setPickerBusy(true)
+ try {
+ const ok = await api.pty.sendText(nodeId, command)
+ if (ok === 'pasted-not-submitted') {
+ window.dispatchEvent(
+ new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message: TEXT_NOT_SUBMITTED } })
+ )
+ return
+ }
+ if (ok !== true) {
+ onWriteRefused()
+ return
+ }
+ onShowTerminal()
+ } finally {
+ pickerBusyRef.current = false
+ setPickerBusy(false)
+ }
+ },
+ [api, agentId, nodeId, onShowTerminal, onWriteRefused]
+ )
+
+ const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
+ // Shift+Enter falls through to the textarea's own newline; an IME commit is not a send.
+ const action = chatKeyAction({
+ key: e.key,
+ shiftKey: e.shiftKey,
+ isComposing: e.nativeEvent.isComposing || e.keyCode === 229
+ })
+ if (action !== 'send') return
+ e.preventDefault()
+ // A picker command still in flight: this Enter would land in the picker it is opening.
+ if (pickerBusyRef.current) return
+ onSend()
+ }
+
+ const labelDisabled = disabled || pickerBusy
+
+ return (
+ <div className="term-chat__compose">
+ <div
+ ref={composerRef}
+ className={`term-chat__composer${dropping ? ' term-chat__composer--drop' : ''}${
+ disabled ? ' term-chat__composer--disabled' : ''
+ }`}
+ // Read by the shortcut dictation paths (lib/chatComposerDictation.ts
+ // `composerFromElement`) so ⌘⇧D / hold-to-talk with the caret here fills THIS draft.
+ data-chat-composer-id={composerId}
+ data-chat-node-id={nodeId}
+ onDragOver={onDragOver}
+ onDragLeave={onDragLeave}
+ onDrop={onDrop}
+ >
+ <textarea
+ ref={inputRef}
+ className="term-chat__input"
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ onKeyDown={onKeyDown}
+ onPaste={onPaste}
+ placeholder={placeholder}
+ disabled={disabled}
+ rows={2}
+ />
+ <div className="term-chat__toolbar">
+ {pathsForFiles && (
+ <>
+ <button
+ type="button"
+ className="term-chat__tool-btn"
+ title="Attach files — their paths go into the message"
+ aria-label="Attach files"
+ disabled={disabled}
+ onClick={() => fileInputRef.current?.click()}
+ >
+ <IconPlus />
+ </button>
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ hidden
+ tabIndex={-1}
+ aria-hidden="true"
+ onChange={(e) => {
+ const files = Array.from(e.target.files ?? [])
+ // Reset so picking the same file again still fires `change`.
+ e.target.value = ''
+ void attachFiles(files)
+ }}
+ />
+ </>
+ )}
+ {attachNote && (
+ <span
+ className={`term-chat__attach-note${attachNote.failed ? ' term-chat__attach-note--failed' : ''}`}
+ role="status"
+ >
+ {!attachNote.failed && <Spinner />}
+ {attachNote.text}
+ </span>
+ )}
+ <span className="term-chat__toolbar-spacer" />
+ {onShowTerminal && labels.model && (
+ <button
+ type="button"
+ className="term-chat__model"
+ title={`Change model — opens ${agentLabel}'s /model picker in the terminal`}
+ disabled={labelDisabled}
+ aria-disabled={labelDisabled}
+ onClick={() => void openPicker('model')}
+ >
+ {labels.model}
+ </button>
+ )}
+ {onShowTerminal && labels.effort && (
+ <button
+ type="button"
+ className="term-chat__effort"
+ title={`Change effort — opens ${agentLabel}'s /effort picker in the terminal`}
+ disabled={labelDisabled}
+ aria-disabled={labelDisabled}
+ onClick={() => void openPicker('effort')}
+ >
+ {labels.effort}
+ </button>
+ )}
+ <button
+ type="button"
+ className="term-chat__tool-btn"
+ title="Dictate into the message"
+ aria-label="Dictate into the message"
+ disabled={disabled}
+ onClick={() => requestComposerDictation(nodeId, composerId)}
+ >
+ <IconMic />
+ </button>
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/src/renderer/nodes/ChatPanel.composer.test.tsx b/src/renderer/nodes/ChatPanel.composer.test.tsx
index 7bbd36db9..52d503952 100644
--- a/src/renderer/nodes/ChatPanel.composer.test.tsx
+++ b/src/renderer/nodes/ChatPanel.composer.test.tsx
@@ -17,7 +17,7 @@ import { COMPOSER_EFFORT_MIN_WIDTH, COMPOSER_MODEL_MIN_WIDTH } from '../lib/chat
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
const { sendText, session } = vi.hoisted(() => {
- const sendText = vi.fn(async (_id: string, _text: string): Promise<boolean | 'pasted-not-submitted'> => true)
+ const sendText = vi.fn((_id: string, _text: string): Promise<boolean | 'pasted-not-submitted'> => Promise.resolve(true))
const session = {
api: {
chat: { readTranscript: async () => ({ messages: [], found: true }) },
@@ -183,6 +183,36 @@ describe('composer attach ("+", paste, drop)', () => {
expect(textarea().value).toBe('/tmp/notes.md ')
})
+ it('the drop highlight never sticks: a drag cancelled without a dragleave (Esc, app switch) clears it', async () => {
+ setAgentState('done')
+ await mount()
+ const box = host.querySelector('.term-chat__composer')!
+ const over = async () => {
+ const ev = new Event('dragover', { bubbles: true, cancelable: true })
+ Object.defineProperty(ev, 'dataTransfer', { value: { types: ['Files'], dropEffect: 'none' } })
+ await act(async () => {
+ box.dispatchEvent(ev)
+ })
+ }
+ await over()
+ expect(box.classList.contains('term-chat__composer--drop')).toBe(true)
+ await act(async () => {
+ window.dispatchEvent(new Event('dragend'))
+ })
+ expect(box.classList.contains('term-chat__composer--drop')).toBe(false)
+ await over()
+ expect(box.classList.contains('term-chat__composer--drop')).toBe(true)
+ await act(async () => {
+ window.dispatchEvent(new Event('blur'))
+ })
+ expect(box.classList.contains('term-chat__composer--drop')).toBe(false)
+ await over()
+ await act(async () => {
+ window.dispatchEvent(new Event('drop'))
+ })
+ expect(box.classList.contains('term-chat__composer--drop')).toBe(false)
+ })
+
it('says so when no path could be resolved (an upload that failed)', async () => {
setAgentState('done')
pathsForFiles.mockResolvedValue([])
@@ -321,13 +351,58 @@ describe('model / effort labels', () => {
expect(textarea().placeholder).toMatch(/Can't write to this session/)
})
+ it('one picker command at a time: a second click or an Enter while /model is in flight types nothing', async () => {
+ // /model opens a local picker that fires NO hook, so the gate still reads `done`; without the
+ // in-flight guard the second click would paste "/model" + Enter INTO that picker.
+ setUsage('claude-opus-5', 'high')
+ setAgentState('done')
+ let release: (v: boolean) => void = () => {}
+ sendText.mockImplementation(() => new Promise<boolean>((r) => (release = r)))
+ await mount()
+ await act(async () => type(textarea(), 'hello'))
+ // A double click lands before React re-renders the disabled state: only the ref can stop it.
+ await act(async () => {
+ modelBtn()!.click()
+ modelBtn()!.click()
+ effortBtn()!.click()
+ })
+ expect(modelBtn()!.disabled).toBe(true)
+ expect(modelBtn()!.getAttribute('aria-disabled')).toBe('true')
+ expect(effortBtn()!.disabled).toBe(true)
+ // The textarea stays live, but its Enter must not reach the pane while the picker opens.
+ await act(async () => {
+ textarea().dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))
+ })
+ expect(sendText).toHaveBeenCalledTimes(1)
+ expect(sendText).toHaveBeenCalledWith(NODE, '/model')
+ await act(async () => release(true))
+ await flush()
+ expect(onShowTerminal).toHaveBeenCalledTimes(1)
+ })
+
+ it('the in-flight guard lifts after a failure, so the label works again', async () => {
+ setUsage('claude-opus-5', 'high')
+ setAgentState('done')
+ sendText.mockResolvedValueOnce('pasted-not-submitted').mockResolvedValueOnce(true)
+ await mount()
+ await act(async () => modelBtn()!.click())
+ await flush()
+ expect(modelBtn()!.disabled).toBe(false)
+ await act(async () => modelBtn()!.click())
+ await flush()
+ expect(sendText).toHaveBeenCalledTimes(2)
+ expect(onShowTerminal).toHaveBeenCalledTimes(1)
+ })
+
it('drops the effort label first, then the model label, as the composer narrows', async () => {
- let fire: (width: number) => void = () => {}
+ // Every observer (the thread's and the composer's) hears the resize, like the real thing.
+ const cbs: Array<(entries: Array<{ contentRect: { width: number } }>) => void> = []
+ const fire = (width: number) => cbs.forEach((cb) => cb([{ contentRect: { width } }]))
vi.stubGlobal(
'ResizeObserver',
class {
constructor(cb: (entries: Array<{ contentRect: { width: number } }>) => void) {
- fire = (width) => cb([{ contentRect: { width } }])
+ cbs.push(cb)
}
observe(): void {}
disconnect(): void {}
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 0d3df8f9d..60efe97ac 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -1,23 +1,11 @@
import { TEXT_NOT_SUBMITTED } from '@shared/text-delivery'
-import {
- memo,
- useCallback,
- useEffect,
- useId,
- useLayoutEffect,
- useMemo,
- useRef,
- useState,
- type ClipboardEvent as ReactClipboardEvent,
- type DragEvent as ReactDragEvent,
- type KeyboardEvent
-} from 'react'
+import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { renderMarkdown } from '../lib/markdown'
import { useAgentStatus } from '../state/agentStatus'
import { useSession } from '../session/session'
import { chipFor } from '../lib/keybindingOverrides'
import { chatComposerPlaceholder, chatSendRefusal } from '../lib/chatSendGate'
-import { chatAgentLabel, chatKeyAction, isNearBottom, shouldFollowOnLoad, toolCardTitle } from '../lib/chatPanel'
+import { chatAgentLabel, isNearBottom, shouldFollowOnLoad, toolCardTitle } from '../lib/chatPanel'
import { useSettings } from '../state/settings'
import {
CHAT_OLDER_PAGE_BYTES,
@@ -36,11 +24,7 @@ import { ChatLoadingStatus } from './ChatPanelFallback'
import { activeAnswerCard } from '../lib/chatAnswer'
import { PlanAnswerControls, QuestionAnswerControls } from './ChatAnswerControls'
import type { PermissionAnswer } from '@shared/agents/permission-answer'
-import { IconMic, IconPlus } from '../components/icons'
-import { useContextUsage } from '../state/contextWindow'
-import { appendToComposer, composerLabels, composerPickerCommand, type ComposerPicker } from '../lib/chatComposer'
-import { requestComposerDictation, subscribeComposerDictation } from '../lib/chatComposerDictation'
-import { clipboardImages, pasteHasText, pastedFiles } from '../terminal/file-drop'
+import { ChatComposer } from './ChatComposer'
// Memoized bubble: marked+DOMPurify re-ran for EVERY message on each ChatPanel render (each
// turn-finish reload, each keystroke re-render). Text is stable per message, so cache per text.
@@ -534,133 +518,7 @@ export function ChatPanel({
setInput('')
}, [api, input, nodeId, agentId])
- // ── Composer toolbar (lib/chatComposer.ts) ────────────────────────────────────────────────
- const inputRef = useRef<HTMLTextAreaElement>(null)
- const composerRef = useRef<HTMLDivElement>(null)
- const fileInputRef = useRef<HTMLInputElement>(null)
- // Per-MOUNT id, not the node id: the canvas node and the kanban card modal can both have this
- // session's composer mounted, and a dictated take must land in the one whose mic was clicked.
- const composerId = useId()
- // The model / effort the header ContextMeter shows, from the SAME reader (no second transcript
- // read). Never node-scoped: that is for remote Codex, which never mounts this panel.
- const usage = useContextUsage({ sessionId, nodeId, scoped: false })
- const [composerWidth, setComposerWidth] = useState<number | null>(null)
- const [attachNote, setAttachNote] = useState<{ text: string; failed?: boolean } | null>(null)
- const [dropping, setDropping] = useState(false)
- const labels = composerLabels({ agentId, model: usage?.model, effort: usage?.effort, width: composerWidth })
- const composerDisabled = readonly || refusal !== null
-
- // The labels drop by the composer's OWN width (a narrow node, a split card modal), not the
- // window's. Guarded like the thread's observer: jsdom and old engines have none, and then every
- // label shows (`composerToolbarLayout(null)`).
- useEffect(() => {
- const el = composerRef.current
- if (!el || typeof ResizeObserver === 'undefined') return
- const ro = new ResizeObserver((entries?: ResizeObserverEntry[]) => {
- // No box (collapsed node, display:none) reports 0: keep the last real width rather than
- // collapsing the toolbar to its narrowest form while nobody can see it.
- const w = entries?.[entries.length - 1]?.contentRect?.width ?? el.clientWidth
- if (typeof w === 'number' && w > 0) setComposerWidth(Math.round(w))
- })
- ro.observe(el)
- return () => ro.disconnect()
- }, [readOnly])
-
- const insertIntoComposer = useCallback((text: string) => {
- setInput((cur) => appendToComposer(cur, text))
- inputRef.current?.focus()
- }, [])
-
- // A dictated take for THIS composer lands in the draft, never in the pane.
- useEffect(() => subscribeComposerDictation(composerId, insertIntoComposer), [composerId, insertIntoComposer])
-
- const attachFiles = useCallback(
- async (files: File[]) => {
- if (!files.length || !pathsForFiles) return
- setAttachNote({ text: `Attaching ${files.length === 1 ? files[0].name || 'file' : `${files.length} files`}…` })
- let paths: string[] = []
- try {
- paths = await pathsForFiles(files)
- } catch {
- paths = []
- }
- if (!paths.length) {
- setAttachNote({ text: 'Could not attach', failed: true })
- return
- }
- setAttachNote(null)
- // Same shape a drop into the terminal pastes: escaped paths, space-separated, trailing space.
- insertIntoComposer(paths.join(' ') + ' ')
- },
- [pathsForFiles, insertIntoComposer]
- )
- useEffect(() => {
- if (!attachNote?.failed) return
- const t = setTimeout(() => setAttachNote(null), 2500)
- return () => clearTimeout(t)
- }, [attachNote])
-
- // Files arriving by drop or paste become paths in the DRAFT (the terminal's own drop handlers
- // stand aside while the ⌘M view covers it — `terminalOwnsFileInput`). Stopped here so the
- // canvas's window-level drop (image nodes) never sees a drop aimed at the composer.
- const onComposerDragOver = (e: ReactDragEvent) => {
- if (!pathsForFiles || composerDisabled || !Array.from(e.dataTransfer.types).includes('Files')) return
- e.preventDefault()
- e.stopPropagation()
- e.dataTransfer.dropEffect = 'copy'
- if (!dropping) setDropping(true)
- }
- const onComposerDragLeave = (e: ReactDragEvent) => {
- const rt = e.relatedTarget as Node | null
- if (!rt || !(e.currentTarget as HTMLElement).contains(rt)) setDropping(false)
- }
- const onComposerDrop = (e: ReactDragEvent) => {
- setDropping(false)
- if (!pathsForFiles || composerDisabled) return
- const files = Array.from(e.dataTransfer.files)
- if (!files.length) return
- e.preventDefault()
- e.stopPropagation()
- void attachFiles(files)
- }
- const onComposerPaste = (e: ReactClipboardEvent<HTMLTextAreaElement>) => {
- if (!pathsForFiles) return
- const files = pastedFiles(e.clipboardData)
- if (files.length) {
- e.preventDefault()
- e.stopPropagation()
- void attachFiles(files)
- return
- }
- // Ordinary text is the textarea's; only an image-only clipboard Chromium filtered to nothing
- // on its way to a text target asks the async Clipboard API (see `clipboardImages`).
- if (pasteHasText(e.clipboardData)) return
- void clipboardImages().then((images) => {
- if (images.length) void attachFiles(images)
- })
- }
-
- // The model / effort label: type the agent's own picker command into the pane — through the
- // SAME send gate as a message, re-read at click time (a picker command typed into a dialog would
- // answer it; into a shell it would run) — then flip to the terminal so the picker is in view.
- const openPicker = useCallback(
- async (picker: ComposerPicker) => {
- const command = composerPickerCommand(agentId, picker)
- if (!command || !onShowTerminal) return
- if (chatSendRefusal(agentId, useAgentStatus.getState().byId[nodeId] ?? {}) !== null) return
- const ok = await api.pty.sendText(nodeId, command)
- if (ok === 'pasted-not-submitted') {
- window.dispatchEvent(new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message: TEXT_NOT_SUBMITTED } }))
- return
- }
- if (ok !== true) {
- setReadonly(true)
- return
- }
- onShowTerminal()
- },
- [api, agentId, nodeId, onShowTerminal]
- )
+ const onWriteRefused = useCallback(() => setReadonly(true), [])
// Answer the held request through core, which validates the answer against the pending request
// file and builds what the hook prints. The ticket is re-checked against the store at SEND time:
@@ -675,18 +533,6 @@ export function ChatPanel({
[api, nodeId]
)
- const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
- // Shift+Enter falls through to the textarea's own newline; an IME commit is not a send.
- const action = chatKeyAction({
- key: e.key,
- shiftKey: e.shiftKey,
- isComposing: e.nativeEvent.isComposing || e.keyCode === 229
- })
- if (action !== 'send') return
- e.preventDefault()
- void send()
- }
-
// Whatever the markdown/chat toggle is bound to; '' when unbound, in which case the bar names
// the action instead of promising a chord that never fires.
const mdChip = chipFor('node.toggleMarkdown')
@@ -823,107 +669,26 @@ export function ChatPanel({
)}
</div>
{!readOnly && (
- <div className="term-chat__compose">
- <div
- ref={composerRef}
- className={`term-chat__composer${dropping ? ' term-chat__composer--drop' : ''}${
- composerDisabled ? ' term-chat__composer--disabled' : ''
- }`}
- onDragOver={onComposerDragOver}
- onDragLeave={onComposerDragLeave}
- onDrop={onComposerDrop}
- >
- <textarea
- ref={inputRef}
- className="term-chat__input"
- value={input}
- onChange={(e) => setInput(e.target.value)}
- onKeyDown={onKeyDown}
- onPaste={onComposerPaste}
- placeholder={chatComposerPlaceholder({
- readonly,
- refusal,
- agentLabel,
- chip: mdChip,
- answerOnCard: answerCard !== null
- })}
- disabled={composerDisabled}
- rows={2}
- />
- <div className="term-chat__toolbar">
- {pathsForFiles && (
- <>
- <button
- type="button"
- className="term-chat__tool-btn"
- title="Attach files — their paths go into the message"
- aria-label="Attach files"
- disabled={composerDisabled}
- onClick={() => fileInputRef.current?.click()}
- >
- <IconPlus />
- </button>
- <input
- ref={fileInputRef}
- type="file"
- multiple
- hidden
- tabIndex={-1}
- aria-hidden="true"
- onChange={(e) => {
- const files = Array.from(e.target.files ?? [])
- // Reset so picking the same file again still fires `change`.
- e.target.value = ''
- void attachFiles(files)
- }}
- />
- </>
- )}
- {attachNote && (
- <span
- className={`term-chat__attach-note${attachNote.failed ? ' term-chat__attach-note--failed' : ''}`}
- role="status"
- >
- {!attachNote.failed && <Spinner />}
- {attachNote.text}
- </span>
- )}
- <span className="term-chat__toolbar-spacer" />
- {onShowTerminal && labels.model && (
- <button
- type="button"
- className="term-chat__model"
- title={`Change model — opens ${agentLabel}'s /model picker in the terminal`}
- disabled={composerDisabled}
- onClick={() => void openPicker('model')}
- >
- {labels.model}
- </button>
- )}
- {onShowTerminal && labels.effort && (
- <button
- type="button"
- className="term-chat__effort"
- title={`Change effort — opens ${agentLabel}'s /effort picker in the terminal`}
- disabled={composerDisabled}
- onClick={() => void openPicker('effort')}
- >
- {labels.effort}
- </button>
- )}
- <button
- type="button"
- className="term-chat__tool-btn"
- title="Dictate into the message"
- aria-label="Dictate into the message"
- disabled={composerDisabled}
- onClick={() => requestComposerDictation(nodeId, composerId)}
- >
- <IconMic />
- </button>
- </div>
- </div>
- </div>
+ <ChatComposer
+ nodeId={nodeId}
+ sessionId={sessionId}
+ agentId={agentId}
+ agentLabel={agentLabel}
+ value={input}
+ onChange={setInput}
+ onSend={() => void send()}
+ placeholder={chatComposerPlaceholder({
+ readonly,
+ refusal,
+ agentLabel,
+ chip: mdChip,
+ answerOnCard: answerCard !== null
+ })}
+ disabled={readonly || refusal !== null}
+ onWriteRefused={onWriteRefused}
+ pathsForFiles={pathsForFiles}
+ onShowTerminal={onShowTerminal}
+ />
)}
</div>
)
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index c79c208b6..5547dd74f 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -179,7 +179,12 @@ import { coldSelfHealVerdict } from '../terminal/cold-self-heal'
import { WakeInputBuffer } from '../terminal/wake-input-buffer'
import { FindBar } from '../components/FindBar'
import { TerminalMarkdownView } from './TerminalMarkdownView'
-import { focusXtermUnlessCovered, terminalOwnsFileInput, useMdModeFocus } from '../terminal/useMdModeFocus'
+import {
+ focusXtermUnlessCovered,
+ requestTerminalFocusOnExit,
+ terminalOwnsFileInput,
+ useMdModeFocus
+} from '../terminal/useMdModeFocus'
import { canvasOwnsMarkdownChord } from '../lib/markdownChord'
import { IconChat, IconChevronDown, IconChevronRight, IconClose, IconEye, IconEyeOff, IconGrid, IconMic, IconMoveTo, IconPlay, IconReload, IconSearch, IconSparkle } from '../components/icons'
import { NodeLabels } from '../components/kanban/NodeLabels'
@@ -5339,7 +5344,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, () => rootRef.current)
+ useMdModeFocus(mdMode, () => termRef.current, () => rootRef.current, id)
// 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.
@@ -6079,7 +6084,11 @@ export function TerminalNode({
projectId: data.sshRemoteTmux ? dropProjectId() : ''
})
}
- onShowTerminal={() => updateNodeData(id, () => ({ mdMode: false }))}
+ onShowTerminal={() => {
+ // An explicit "go to the terminal": the picker just opened there needs the keyboard.
+ requestTerminalFocusOnExit(id)
+ updateNodeData(id, () => ({ mdMode: false }))
+ }}
/>
</Suspense>
) : (
diff --git a/src/renderer/terminal/useMdModeFocus.test.tsx b/src/renderer/terminal/useMdModeFocus.test.tsx
index 37b23a7b7..e5adadfbb 100644
--- a/src/renderer/terminal/useMdModeFocus.test.tsx
+++ b/src/renderer/terminal/useMdModeFocus.test.tsx
@@ -7,6 +7,7 @@ import { resolve } from 'node:path'
import {
focusXtermUnlessCovered,
mayRestoreFocus,
+ requestTerminalFocusOnExit,
terminalOwnsFileInput,
useMdModeFocus,
type FocusableTerm
@@ -39,12 +40,13 @@ 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, () => nodeRoot)
+function Harness({ mdMode, nodeId }: { mdMode: boolean; nodeId?: string }) {
+ useMdModeFocus(mdMode, () => term, () => nodeRoot, nodeId)
return null
}
-const render = (mdMode: boolean) => act(() => root.render(<Harness mdMode={mdMode} />))
+const render = (mdMode: boolean, nodeId?: string) =>
+ act(() => root.render(<Harness mdMode={mdMode} nodeId={nodeId} />))
beforeEach(() => {
host = document.createElement('div')
@@ -177,6 +179,63 @@ describe('focusXtermUnlessCovered', () => {
})
})
+describe('requestTerminalFocusOnExit (the ⌘M composer model / effort label)', () => {
+ it('focuses the terminal on exit even when it did NOT have focus on entry (⌘K / menu / board)', () => {
+ render(false, 'n1')
+ render(true, 'n1')
+ term!.calls.length = 0
+ requestTerminalFocusOnExit('n1')
+ render(false, 'n1')
+ expect(term!.calls).toEqual(['focus'])
+ expect(document.activeElement).toBe(term!.textarea)
+ })
+
+ it('wins over focus sitting elsewhere: the click that asked for it was the user choosing', () => {
+ render(false, 'n2')
+ render(true, 'n2')
+ const other = document.createElement('input')
+ document.body.appendChild(other)
+ other.focus()
+ requestTerminalFocusOnExit('n2')
+ render(false, 'n2')
+ expect(document.activeElement).toBe(term!.textarea)
+ })
+
+ it('is consumed once: the next ordinary exit is back on the restore rule', () => {
+ render(false, 'n3')
+ render(true, 'n3')
+ requestTerminalFocusOnExit('n3')
+ render(false, 'n3')
+ term!.textarea!.blur()
+ render(true, 'n3')
+ term!.calls.length = 0
+ render(false, 'n3')
+ expect(term!.calls).toEqual([])
+ })
+
+ it("answers only its own node's request", () => {
+ render(false, 'mine')
+ render(true, 'mine')
+ term!.calls.length = 0
+ requestTerminalFocusOnExit('someone-else')
+ render(false, 'mine')
+ expect(term!.calls).toEqual([])
+ })
+
+ it('both mount sites request focus before flipping, and both hooks are keyed by node id', () => {
+ // Source pins: TerminalNode and CardModal cannot be mounted here. The request must come
+ // BEFORE the state change, or the hook's exit transition runs first and misses it.
+ const read = (rel: string) => readFileSync(resolve(__dirname, rel), 'utf8').replace(/\r\n/g, '\n')
+ const node = read('../nodes/TerminalNode.tsx')
+ expect(node).toMatch(/useMdModeFocus\(mdMode, \(\) => termRef\.current, \(\) => rootRef\.current, id\)/)
+ expect(node).toMatch(/requestTerminalFocusOnExit\(id\)\s*\n\s*updateNodeData\(id, \(\) => \(\{ mdMode: false \}\)\)/)
+ const modal = read('../components/kanban/CardModal.tsx')
+ expect(modal).toMatch(/requestTerminalFocusOnExit\(session\.id\)\s*\n\s*setMdFor\(null\)/)
+ const viewer = read('../components/kanban/ModalTerminal.tsx')
+ expect(viewer).toMatch(/useMdModeFocus\(covered, [^\n]*, nodeId\)/)
+ })
+})
+
describe('terminalOwnsFileInput', () => {
it('hands dropped / pasted files to the terminal only while the ⌘M view is not covering it', () => {
expect(terminalOwnsFileInput(false)).toBe(true)
diff --git a/src/renderer/terminal/useMdModeFocus.ts b/src/renderer/terminal/useMdModeFocus.ts
index a7860323f..4d5269071 100644
--- a/src/renderer/terminal/useMdModeFocus.ts
+++ b/src/renderer/terminal/useMdModeFocus.ts
@@ -23,10 +23,31 @@ export interface FocusableTerm {
* `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.
*/
+/**
+ * Node ids whose NEXT ⌘M exit must focus the terminal whatever the entry state was. Set by an
+ * action that is itself an explicit "go to the terminal": the ⌘M composer's model / effort label,
+ * which types `/model` / `/effort` into the pane and flips the view so the user can drive the
+ * picker it opened — with the keyboard, which is useless if the xterm does not have it. Entry was
+ * very often NOT from a focused terminal (context menu, ⌘K, the kanban card), which is exactly
+ * when the restore rule above would leave the picker unreachable.
+ *
+ * Module-level and keyed by node id because the request is made by the panel, which unmounts in
+ * the same flip, and consumed by the terminal's hook, which lives on. Consumed once: the hook that
+ * takes it deletes it, so a later unrelated exit is back on the ordinary rule.
+ */
+const focusOnExit = new Set<string>()
+
+/** Ask the next ⌘M exit of `nodeId` to focus its terminal. Call BEFORE the state change. */
+export function requestTerminalFocusOnExit(nodeId: string): void {
+ focusOnExit.add(nodeId)
+}
+
export function useMdModeFocus(
mdMode: boolean,
getTerm: () => FocusableTerm | null | undefined,
- getRoot: () => Element | null | undefined
+ getRoot: () => Element | null | undefined,
+ /** Whose `requestTerminalFocusOnExit` this hook answers. Absent = never forced. */
+ nodeId?: string
): void {
const restoreRef = useRef(false)
const prevRef = useRef(mdMode)
@@ -34,6 +55,8 @@ export function useMdModeFocus(
getTermRef.current = getTerm
const getRootRef = useRef(getRoot)
getRootRef.current = getRoot
+ const nodeIdRef = useRef(nodeId)
+ nodeIdRef.current = nodeId
useEffect(() => {
if (prevRef.current === mdMode) return
@@ -43,6 +66,11 @@ export function useMdModeFocus(
const ta = term?.textarea
restoreRef.current = !!ta && document.activeElement === ta
term?.blur()
+ } else if (nodeIdRef.current !== undefined && focusOnExit.delete(nodeIdRef.current)) {
+ // An explicit "go to the terminal" (see `requestTerminalFocusOnExit`): the user just clicked
+ // inside this node to get here, so nothing they chose elsewhere is being overridden.
+ restoreRef.current = false
+ term?.focus()
} else if (restoreRef.current) {
restoreRef.current = false
if (mayRestoreFocus(document.activeElement, getRootRef.current(), document.body)) term?.focus()