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(chat): never type into a TUI dialog from the ⌘M chat composer
review7f5e8391db16
diff --git a/CLAUDE.md b/CLAUDE.mdindex 5bb49e185..28415b6ed 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2333,6 +2333,12 @@ command-bearing opens; this does not add a human-confirm dialog or change mobileits `contextTail`, the hook-fed path authority). The browser's real reader is`buildTranscriptApi` in ws-bridge — deliberately NOT folded into `buildClaudeApi`, which therelay shares and must not adopt it.+ **The composer sends only in `done` or an unknown state** (`canSendFromChat`,+ `renderer/lib/chatSendGate.ts`) — never in `waiting`/`blocked`, not just never in `working`:+ PermissionRequest and AskUserQuestion both normalize to `waiting`, the pane then holds a TUI+ select dialog this view does not show, and `sendText`'s Enter would ANSWER it ("Yes" is the+ default highlight). The state is re-read from the store at send time, not only at render. Same+ trap as the in-place restart's `/exit`.- **Subagent visualization** (agents in `SUBAGENT_CAPABLE`) — `subagent-start`/`subagent-end`normalized events (from Claude's `PreToolUse`/`PostToolUse` on tool `Agent`/`Task`, correlatedby `tool_use_id`) drive a transient `state/agentNodes.ts` store. Claude launches subagentsdiff --git a/src/renderer/lib/chatSendGate.test.ts b/src/renderer/lib/chatSendGate.test.tsnew file mode 100644index 000000000..806db1096--- /dev/null+++ b/src/renderer/lib/chatSendGate.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest'+import { canSendFromChat, chatComposerPlaceholder } from './chatSendGate'++describe('canSendFromChat', () => {+ it('allows a finished turn and an unknown state (no hook knowledge keeps the historical behavior)', () => {+ expect(canSendFromChat('done')).toBe(true)+ expect(canSendFromChat(undefined)).toBe(true)+ })++ it('refuses while the agent is working', () => {+ expect(canSendFromChat('working')).toBe(false)+ })++ it('refuses while a TUI dialog is up: Enter would answer it', () => {+ // PermissionRequest / AskUserQuestion normalize to `waiting`, a permission Notification to+ // `blocked` — both are select dialogs where sendText's trailing Enter confirms the highlight.+ expect(canSendFromChat('waiting')).toBe(false)+ expect(canSendFromChat('blocked')).toBe(false)+ })+})++describe('chatComposerPlaceholder', () => {+ it('keeps the historical copy for a sendable state', () => {+ expect(chatComposerPlaceholder({ readonly: false, state: 'done', chip: '⌘M' })).toBe(+ 'Message Claude… (Enter to send)'+ )+ expect(chatComposerPlaceholder({ readonly: false, state: undefined, chip: '' })).toBe(+ 'Message Claude… (Enter to send)'+ )+ })++ it('keeps the working copy', () => {+ expect(chatComposerPlaceholder({ readonly: false, state: 'working', chip: '⌘M' })).toBe('Claude is working…')+ })++ it('points a dialog back at the terminal through the bound chord', () => {+ for (const state of ['waiting', 'blocked'] as const) {+ expect(chatComposerPlaceholder({ readonly: false, state, chip: '⌘M' })).toBe(+ 'Claude is waiting for an answer in the terminal — press ⌘M to answer there'+ )+ }+ })++ it('never promises a chord that is unbound', () => {+ const text = chatComposerPlaceholder({ readonly: false, state: 'waiting', chip: '' })+ expect(text).toBe('Claude is waiting for an answer in the terminal — switch back to the terminal to answer')+ expect(text).not.toMatch(/press/)+ })++ it('a write failure wins over every state', () => {+ expect(chatComposerPlaceholder({ readonly: true, state: 'waiting', chip: '⌘M' })).toBe(+ "Can't write to this session"+ )+ })+})diff --git a/src/renderer/lib/chatSendGate.ts b/src/renderer/lib/chatSendGate.tsnew file mode 100644index 000000000..5c0a5ffec--- /dev/null+++ b/src/renderer/lib/chatSendGate.ts@@ -0,0 +1,46 @@+import type { AgentState } from '@shared/agents/normalize'++/**+ * May the ⌘M chat composer type into the agent's pane right now?+ *+ * `pty.sendText` pastes the text and then presses Enter. That is a prompt only while the agent's+ * input box owns the pane. In `waiting` (Claude's PermissionRequest AND AskUserQuestion both+ * normalize to it, `shared/agents/normalize.ts`) and `blocked` (a permission Notification) the+ * pane holds a TUI select dialog the transcript view does not show — and Enter CONFIRMS the+ * highlighted option, which is "Yes" by default. A message typed into the chat would silently+ * grant a permission or pick an answer. Same trap CLAUDE.md documents for the in-place restart's+ * `/exit`, and the same refusal.+ *+ * `undefined` is ALLOWED: no hook knowledge (a custom agent, a session with no event yet in this+ * app run) is "unknown", not "unsafe", and refusing it would take the composer away from every+ * such node — the historical behavior is kept there. Only `done` is a positive "input box is up".+ */+export function canSendFromChat(state: AgentState | undefined): boolean {+ return state === undefined || state === 'done'+}++/**+ * The composer's placeholder — the one place the user learns WHY it is disabled. A dialog points+ * back at the terminal through the chord actually bound to the markdown/chat toggle (`chip`, from+ * `chipFor('node.toggleMarkdown')`); `''` = unbound, and then the text names the action instead+ * of promising a chord that never fires. A write failure (`readonly`) outranks every state: no+ * state change will make that session writable.+ */+export function chatComposerPlaceholder({+ readonly,+ state,+ chip+}: {+ readonly: boolean+ state: AgentState | undefined+ chip: string+}): string {+ if (readonly) return "Can't write to this session"+ if (state === 'working') return 'Claude is working…'+ if (!canSendFromChat(state)) {+ return chip+ ? `Claude is waiting for an answer in the terminal — press ${chip} to answer there`+ : 'Claude is waiting for an answer in the terminal — switch back to the terminal to answer'+ }+ return 'Message Claude… (Enter to send)'+}diff --git a/src/renderer/nodes/ChatPanel.sendGate.test.tsx b/src/renderer/nodes/ChatPanel.sendGate.test.tsxnew file mode 100644index 000000000..11888348e--- /dev/null+++ b/src/renderer/nodes/ChatPanel.sendGate.test.tsx@@ -0,0 +1,106 @@+// @vitest-environment jsdom+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { useAgentStatus } from '../state/agentStatus'++/**+ * The composer must never type into a TUI dialog: `sendText` pastes and presses Enter, and Enter+ * answers a permission / AskUserQuestion dialog the transcript view does not show. The pure rule+ * is `lib/chatSendGate.ts`; this file pins the GLUE — the textarea is disabled in a dialog state,+ * and `send` re-reads the store at send time, so a dialog that arrives between the last render and+ * the keypress still blocks.+ */++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++// ONE stable api object: `load` depends on `api`, so a fresh object per `useSession()` call would+// re-run the load effect on every render and never settle.+const { sendText, session } = vi.hoisted(() => {+ const sendText = vi.fn(async (_id: string, _text: string) => true as const)+ const session = {+ api: {+ chat: { readTranscript: async () => ({ messages: [], found: true }) },+ pty: { sendText }+ }+ }+ return { sendText, session }+})+vi.mock('../session/session', () => ({ useSession: () => session }))++import { ChatPanel } from './ChatPanel'++const NODE = 'n-chat-gate'+let host: HTMLDivElement+let root: Root++function setAgentState(state: 'working' | 'waiting' | 'blocked' | 'done' | undefined): void {+ useAgentStatus.setState((s) => ({+ byId: { ...s.byId, [NODE]: { ...(s.byId[NODE] ?? {}), state } as (typeof s.byId)[string] }+ }))+}++async function mount(): Promise<HTMLTextAreaElement> {+ await act(async () => {+ root.render(<ChatPanel nodeId={NODE} sessionId="s1" agentId="claude" />)+ })+ return host.querySelector('textarea') as HTMLTextAreaElement+}++function type(ta: HTMLTextAreaElement, text: string): void {+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!+ setter.call(ta, text)+ ta.dispatchEvent(new Event('input', { bubbles: true }))+}++const enter = (ta: HTMLTextAreaElement): void => {+ ta.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))+}++beforeEach(() => {+ sendText.mockClear()+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})++afterEach(() => {+ act(() => root.unmount())+ host.remove()+ useAgentStatus.setState((s) => {+ const byId = { ...s.byId }+ delete byId[NODE]+ return { byId }+ })+})++describe('ChatPanel send gate', () => {+ it('sends when the turn is done', async () => {+ setAgentState('done')+ const ta = await mount()+ expect(ta.disabled).toBe(false)+ await act(async () => type(ta, 'hello'))+ await act(async () => enter(ta))+ expect(sendText).toHaveBeenCalledWith(NODE, 'hello')+ })++ it.each(['waiting', 'blocked'] as const)('disables the composer and explains while %s', async (state) => {+ setAgentState(state)+ const ta = await mount()+ expect(ta.disabled).toBe(true)+ expect(ta.placeholder).toMatch(/waiting for an answer in the terminal/)+ })++ it('re-reads the state at send time: a dialog that arrived after the last render still blocks', async () => {+ setAgentState('done')+ const ta = await mount()+ await act(async () => type(ta, 'yes please'))+ // Store flips to a dialog state and the keypress lands in the SAME act, before React commits+ // the re-render — the handler's render-time `state` is still 'done'.+ await act(async () => {+ setAgentState('waiting')+ enter(ta)+ })+ expect(sendText).not.toHaveBeenCalled()+ })+})diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsxindex 07e970c3d..398eab3da 100644--- a/src/renderer/nodes/ChatPanel.tsx+++ b/src/renderer/nodes/ChatPanel.tsx@@ -5,6 +5,7 @@ import { useAgentStatus } from '../state/agentStatus'import { useSession } from '../session/session'import type { ChatMessage } from '@shared/types'import { chipFor } from '../lib/keybindingOverrides'+import { canSendFromChat, chatComposerPlaceholder } from '../lib/chatSendGate'import { E_UNSUPPORTED } from '@shared/rpc'// Memoized bubble: marked+DOMPurify re-ran for EVERY message on each ChatPanel render (each@@ -127,11 +128,15 @@ export function ChatPanel({if (el) el.scrollTop = el.scrollHeight}, [messages])- const working = state === 'working'+ // Not just `working`: in `waiting`/`blocked` the pane holds a TUI dialog this view does not show,+ // and sendText's Enter would ANSWER it (see lib/chatSendGate.ts).+ const sendRefused = !canSendFromChat(state)const send = useCallback(async () => {const text = input.trim()- if (!text || working) return+ // Read the store at SEND time, not the render-time `state`: a PermissionRequest that landed+ // between the last render and this keypress must still block, or the Enter answers the dialog.+ if (!text || !canSendFromChat(useAgentStatus.getState().byId[nodeId]?.state)) returnconst ok = await api.pty.sendText(nodeId, text)if (ok === 'pasted-not-submitted') {window.dispatchEvent(new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message: TEXT_NOT_SUBMITTED } }))@@ -145,7 +150,7 @@ export function ChatPanel({// Optimistic: show the prompt immediately; the next load() reconciles from the transcript.setMessages((m) => [...m, { role: 'user', parts: [{ kind: 'text', text }] }])setInput('')- }, [api, input, working, nodeId])+ }, [api, input, nodeId])const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {if (e.key === 'Enter') {@@ -203,14 +208,8 @@ export function ChatPanel({value={input}onChange={(e) => setInput(e.target.value)}onKeyDown={onKeyDown}- placeholder={- readonly- ? "Can't write to this session"- : working- ? 'Claude is working…'- : 'Message Claude… (Enter to send)'- }- disabled={readonly || working}+ placeholder={chatComposerPlaceholder({ readonly, state, chip: mdChip })}+ disabled={readonly || sendRefused}rows={2}/></div>