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 send into Claude Code's own dialogs from the ⌘M view
Paul Robertsoncc71894ebeb9
diff --git a/CLAUDE.md b/CLAUDE.mdindex ef1965189..43164a1d9 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -3353,6 +3353,17 @@ command-bearing opens; this does not add a human-confirm dialog or change mobilestore at send time, not only at render. Same trap as the in-place restart's `/exit`. The bar's ↻reloads on demand (beside the empty state's Retry), since a session whose hooks never report`working` never takes the turn-finish reload.+ **The agent's OWN dialogs are read off the screen** (`shared/agents/claude-screen.ts`, claude+ only — `SCREEN_DIALOG_READABLE`). The folder-trust prompt, `/model` and one-time setup questions+ fire NO hook, so the state gate above reads `done` while one owns the keyboard, and a paste into+ it was swallowed while its Enter answered the dialog (the trust prompt's default is "No, exit").+ A send therefore goes through `pty.sendChatPrompt`, where core captures the pane first and+ refuses (`ChatPromptBlocked`, nothing written, the draft kept) when the bottom of the screen is a+ dialog footer or has no input box; an empty or unreadable capture is NOT evidence and sends as+ before. A LOCAL pane is also polled every 2 s while the view is visible, to disable the composer+ and show the dialog's lines; SSH and relay panes are not polled (a round trip per read) and rely+ on the send-time check. Another CLI's layout would read as a permanent dialog, so an agent joins+ the list only with its own measured reader.**Live progress (2026-09).** While the agent works, a `role=status` row closes the thread (the ONEspinner + the placeholder's own "<agent> is working…"/"waiting for an answer" sentence; optimisticright after a send, bounded by `CHAT_OPTIMISTIC_WORKING_MS`), and every hook event re-reads thediff --git a/src/core/pty-manager.chat-prompt.test.ts b/src/core/pty-manager.chat-prompt.test.tsnew file mode 100644index 000000000..2ad70ff5e--- /dev/null+++ b/src/core/pty-manager.chat-prompt.test.ts@@ -0,0 +1,78 @@+// `PtyManager.sendChatPrompt` — the ⌘M chat view's send. For an agent whose screen we can read+// (claude), the pane's screen is checked BEFORE anything is written: Claude Code's own dialogs fire+// no hook, and a paste into one swallowed the text while its Enter answered the dialog. The screen+// reader itself is tested in shared/agents/claude-screen.test.ts; this file pins the dispatch.+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'++vi.mock('node-pty', () => ({ spawn: () => ({}) }))++const NODE = 'node-1'+const RULE = '─'.repeat(80)+const IDLE = [RULE, '❯ ', RULE, ' ? for shortcuts'].join('\n')+const TRUST = [RULE, ' Accessing workspace:', ' ❯ No, exit', ' Yes, I trust this folder', ' Enter to confirm · Esc to cancel'].join('\n')++async function manager(screen: string) {+ const { PtyManager } = await import('./pty-manager')+ const mgr = new PtyManager()+ const captureSession = vi.spyOn(mgr, 'captureSession').mockResolvedValue(screen)+ const sendText = vi.spyOn(mgr, 'sendText').mockResolvedValue(true)+ return { mgr, captureSession, sendText }+}++describe('PtyManager.sendChatPrompt', () => {+ beforeEach(() => {+ vi.resetModules()+ initPlatform(fakePlatform())+ })+ afterEach(() => {+ resetPlatformForTests()+ })++ it('sends a claude prompt when its input box is on screen', async () => {+ const { mgr, sendText } = await manager(IDLE)++ const result = await mgr.sendChatPrompt(NODE, 'hello', 'claude')++ expect(result).toBe(true)+ expect(sendText).toHaveBeenCalledWith(NODE, 'hello')+ })++ it('refuses before writing anything when a claude dialog owns the screen, and returns its text', async () => {+ const { mgr, sendText } = await manager(TRUST)++ const result = await mgr.sendChatPrompt(NODE, 'hello', 'claude')++ expect(sendText).not.toHaveBeenCalled()+ expect(result).toEqual({ blocked: 'screen', dialog: expect.stringContaining('No, exit') })+ })++ it('refuses with no dialog text when the input box is gone (a shell owns the pane)', async () => {+ const { mgr, sendText } = await manager('user@host ~ % ')++ const result = await mgr.sendChatPrompt(NODE, 'hello', 'claude')++ expect(sendText).not.toHaveBeenCalled()+ expect(result).toEqual({ blocked: 'screen', dialog: null })+ })++ it('an empty capture is not evidence of a dialog: the prompt is sent as before', async () => {+ const { mgr, sendText } = await manager('')++ const result = await mgr.sendChatPrompt(NODE, 'hello', 'claude')++ expect(result).toBe(true)+ expect(sendText).toHaveBeenCalledWith(NODE, 'hello')+ })++ it('never reads the screen of an agent without a measured reader', async () => {+ const { mgr, captureSession, sendText } = await manager(TRUST)++ const result = await mgr.sendChatPrompt(NODE, 'hello', 'codex')++ expect(captureSession).not.toHaveBeenCalled()+ expect(result).toBe(true)+ expect(sendText).toHaveBeenCalledWith(NODE, 'hello')+ })+})diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 7138ac7f5..1a7ef90a1 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -1,4 +1,5 @@-import type { TextDeliveryResult } from '../shared/text-delivery'+import type { ChatPromptBlocked, ChatPromptResult, TextDeliveryResult } from '../shared/text-delivery'+import { claudeScreenBlocksInput, readClaudeScreen } from '../shared/agents/claude-screen'import os from 'os'import fs from 'fs'import path from 'path'@@ -135,6 +136,7 @@ import { clearNode as clearNodeAgentStatus } from './agent-status-mirror'import {capabilityAgentId,hasSharedIdentity,+ readsScreenDialogs,setCustomAgentBaseResolver,vanillaEnvStripPattern,type AgentId@@ -892,6 +894,13 @@ export const SHADOW_CMD_TIMEOUT_MS = 5_000*/export const BACKGROUND_WRITE_LINGER_MS = 10_000+/** The chat view's screen check for Claude (shared/agents/claude-screen.ts): a refusal, or null. */+function screenGate(screen: string): ChatPromptBlocked | null {+ const read = readClaudeScreen(screen)+ if (!claudeScreenBlocksInput(read)) return null+ return { blocked: 'screen', dialog: read.kind === 'dialog' ? read.text : null }+}+/*** Manages all live PTY processes and bridges them to the renderer over IPC.*@@ -1923,6 +1932,11 @@ export class PtyManager {platform().handle(IPC.ptySendText, (persistKey: string, text: string, enter?: boolean) =>this.sendText(persistKey, text, enter === undefined ? undefined : { enter }))+ platform().handle(IPC.ptySendChatPrompt, (persistKey: string, text: string, agentId: unknown) =>+ // `agentId` crosses a process boundary: it only picks the screen reader, and a non-string+ // picks none (plain `sendText`), never a wrong one.+ this.sendChatPrompt(persistKey, text, typeof agentId === 'string' ? agentId : '')+ )platform().handle(IPC.ptyTmuxStatus, () => this.tmuxStatus())platform().handle(IPC.ptyPaneCommand, (persistKey: string) => this.paneCommand(persistKey))platform().handle(IPC.ptyPaneCwd, (persistKey: string) => this.paneCwd(persistKey))@@ -4958,6 +4972,24 @@ export class PtyManager {}}+ /**+ * A prompt from the ⌘M chat view. For an agent whose screen we can read (`readsScreenDialogs`),+ * refused before anything is written when the agent's own UI owns the keyboard: such dialogs+ * (the folder-trust prompt, `/model`, one-time setup questions) fire no hook, so the chat view's+ * state gate cannot see them, and a paste into one swallowed the text while its Enter answered+ * the dialog. An empty capture (no session, a failed read) is not evidence of a dialog: the+ * prompt is sent exactly as before. There is no second look before the Enter — `sendText`+ * submits in the same step. Everything else is `sendText`, unchanged.+ */+ async sendChatPrompt(persistKey: string, text: string, agentId: string): Promise<ChatPromptResult> {+ if (readsScreenDialogs(agentId)) {+ const screen = await this.captureSession(persistKey)+ const refused = screen === '' ? null : screenGate(screen)+ if (refused !== null) return refused+ }+ return this.sendText(persistKey, text)+ }+/*** The command currently in the foreground of a node's tmux pane (e.g. 'claude', 'zsh') — how* the in-place agent restart observes that the CLI has exited and a shell owns the pane again.diff --git a/src/core/relay/access-policy.ts b/src/core/relay/access-policy.tsindex e09f2527b..5e6a0772e 100644--- a/src/core/relay/access-policy.ts+++ b/src/core/relay/access-policy.ts@@ -292,6 +292,7 @@ export const EDITOR_ONLY: ReadonlySet<string> = new Set<string>([IPC.ptyRecycle,IPC.ptySessionAge,IPC.ptySendText,+ IPC.ptySendChatPrompt,IPC.ptyPaneOwner,// A host filesystem path, not a view of the terminal — a viewer's file links keep the node cwd.IPC.ptyPaneCwd,diff --git a/src/core/relay/scoped-guest-policy.ts b/src/core/relay/scoped-guest-policy.tsindex 42a770261..50cc9e625 100644--- a/src/core/relay/scoped-guest-policy.ts+++ b/src/core/relay/scoped-guest-policy.ts@@ -310,6 +310,7 @@ export const SCOPED: Readonly<Record<string, Check>> = Object.freeze({[IPC.ptySessionAge]: nodeArg0,[IPC.ptyReadScrollback]: nodeArg0,[IPC.ptySendText]: nodeArg0,+ [IPC.ptySendChatPrompt]: nodeArg0,[IPC.ptyTmuxStatus]: pass,[IPC.ptyPaneCommand]: nodeArg0,[IPC.ptyPaneCwd]: nodeArg0,diff --git a/src/preload/index.ts b/src/preload/index.tsindex b0eddc084..69b5644de 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -102,6 +102,8 @@ const api: NodeTerminalApi = {readScrollback: (persistKey) => ipcRenderer.invoke(IPC.ptyReadScrollback, persistKey),sendText: (persistKey, text, opts) =>ipcRenderer.invoke(IPC.ptySendText, persistKey, text, opts?.enter),+ sendChatPrompt: (persistKey, text, agentId) =>+ ipcRenderer.invoke(IPC.ptySendChatPrompt, persistKey, text, agentId),tmuxStatus: () => ipcRenderer.invoke(IPC.ptyTmuxStatus),paneCommand: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneCommand, persistKey),paneCwd: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneCwd, persistKey),diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex b3b46b081..8f0fb7aa6 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -19,6 +19,7 @@ import {type RpcMessage} from '../../shared/rpc'import { IPC } from '../../shared/ipc'+import type { ChatPromptResult } from '../../shared/text-delivery'import type { GitHubControlApi, GitHubIssuesApi } from '../../shared/github-issues'import {UNKNOWN_CLAUDE_CLI_CAPS,@@ -272,6 +273,8 @@ export function buildRealApi(client.request(IPC.ptyReadScrollback, persistKey) as Promise<string>,sendText: (persistKey, text, opts) =>client.request(IPC.ptySendText, persistKey, text, opts?.enter) as Promise<boolean>,+ sendChatPrompt: (persistKey, text, agentId) =>+ client.request(IPC.ptySendChatPrompt, persistKey, text, agentId) as Promise<ChatPromptResult>,// A failed read is unknown, never evidence that persistence is available.tmuxStatus: () =>clientdiff --git a/src/renderer/lib/chatLive.test.ts b/src/renderer/lib/chatLive.test.tsindex d0e8bc880..8fea7a8c2 100644--- a/src/renderer/lib/chatLive.test.ts+++ b/src/renderer/lib/chatLive.test.ts@@ -1,5 +1,11 @@import { describe, expect, it } from 'vitest'-import { CHAT_LIVE_RELOAD_MIN_MS, CHAT_OPTIMISTIC_WORKING_MS, chatActivity, planLiveReload } from './chatLive'+import {+ CHAT_LIVE_RELOAD_MIN_MS,+ CHAT_OPTIMISTIC_WORKING_MS,+ chatActivity,+ planLiveReload,+ shouldPollScreen+} from './chatLive'describe('chatActivity — the status row at the end of the ⌘M thread', () => {it('a working agent shows the working row', () => {@@ -52,3 +58,27 @@ describe('planLiveReload — throttled, single-flight, visible-only tail refreshexpect(CHAT_OPTIMISTIC_WORKING_MS).toBeLessThanOrEqual(30_000)})})++describe('shouldPollScreen — reading the pane for the agent\'s own dialogs', () => {+ const base = { readable: true, readOnly: false, remote: false, refusal: null } as const++ it('polls a local pane of a readable agent, idle or working', () => {+ expect(shouldPollScreen(base)).toBe(true)+ expect(shouldPollScreen({ ...base, refusal: 'working' })).toBe(true)+ })++ it('never polls a remote pane: every read would be a network round trip', () => {+ expect(shouldPollScreen({ ...base, remote: true })).toBe(false)+ })++ it('not for an agent whose screen we cannot read, nor a read-only transcript', () => {+ expect(shouldPollScreen({ ...base, readable: false })).toBe(false)+ expect(shouldPollScreen({ ...base, readOnly: true })).toBe(false)+ })++ it('not while a hook-reported dialog or a shell-owned pane already stands the composer down', () => {+ for (const refusal of ['dialog', 'asleep', 'paused', 'dropped', 'exited'] as const) {+ expect(shouldPollScreen({ ...base, refusal })).toBe(false)+ }+ })+})diff --git a/src/renderer/lib/chatLive.ts b/src/renderer/lib/chatLive.tsindex 39c9aec06..87c6ab75f 100644--- a/src/renderer/lib/chatLive.ts+++ b/src/renderer/lib/chatLive.ts@@ -22,6 +22,29 @@ export const CHAT_LIVE_RELOAD_MIN_MS = 1500*/export const CHAT_OPTIMISTIC_WORKING_MS = 15_000+/**+ * How often an open chat view re-reads the pane's screen for the agent's own dialogs+ * (shared/agents/claude-screen.ts) — they fire no hook, so this is the only way to disable the+ * composer while one is up. One local `tmux capture-pane` per tick.+ */+export const CHAT_SCREEN_POLL_MS = 2000++/**+ * Should the panel poll the pane's screen? Only for an agent whose screen we can read, only for a+ * LOCAL pane (each read of an SSH or relay pane is a network round trip, every two seconds, for as+ * long as the view is open — those rely on the check at send time alone), and only while no other+ * refusal already explains the pane: a hook-reported dialog or a shell-owned pane stands the+ * composer down on its own. `working` still polls — a harness dialog can open mid-turn.+ */+export function shouldPollScreen(s: {+ readable: boolean+ readOnly: boolean+ remote: boolean+ refusal: ChatSendRefusal+}): boolean {+ return s.readable && !s.readOnly && !s.remote && (s.refusal === null || s.refusal === 'working')+}+/** What the row at the end of the thread says; `null` = no row. */export type ChatActivity = 'working' | 'dialog' | nulldiff --git a/src/renderer/lib/chatSendGate.test.ts b/src/renderer/lib/chatSendGate.test.tsindex 1a0c61cd7..babc6567b 100644--- a/src/renderer/lib/chatSendGate.test.ts+++ b/src/renderer/lib/chatSendGate.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'import { agentProcessInPane } from '../terminal/live-work'-import { canSendFromChat, chatComposerPlaceholder, chatSendRefusal } from './chatSendGate'+import { canSendFromChat, chatComposerPlaceholder, chatSendRefusal, screenBlockedSentence } from './chatSendGate'describe('chatSendRefusal / canSendFromChat', () => {it('allows a finished turn and an unknown state (no hook knowledge keeps the historical behavior)', () => {@@ -115,3 +115,24 @@ describe('chatComposerPlaceholder', () => {)})})++describe('screenBlockedSentence — the agent\'s own dialog is on screen', () => {+ it('points at the terminal through the bound chord, or names the action when unbound', () => {+ expect(screenBlockedSentence('dialog', 'Claude Code', '⌘M')).toBe(+ 'Claude Code is showing a dialog — press ⌘M to answer it in the terminal'+ )+ expect(screenBlockedSentence('dialog', 'Claude Code', '')).toBe(+ 'Claude Code is showing a dialog — switch back to the terminal to answer it'+ )+ expect(screenBlockedSentence('no-prompt', 'Claude Code', '⌘M')).toBe(+ "Claude Code's input box isn't on screen — press ⌘M to check the terminal"+ )+ })++ it('is what the composer placeholder says, over every state sentence but read-only', () => {+ const base = { readonly: false, agentLabel: 'Claude Code', chip: '⌘M', refusal: null, screen: 'dialog' as const }++ expect(chatComposerPlaceholder(base)).toBe(screenBlockedSentence('dialog', 'Claude Code', '⌘M'))+ expect(chatComposerPlaceholder({ ...base, readonly: true })).toBe("Can't write to this session")+ })+})diff --git a/src/renderer/lib/chatSendGate.ts b/src/renderer/lib/chatSendGate.tsindex 7dac3ef09..1c8e604e7 100644--- a/src/renderer/lib/chatSendGate.ts+++ b/src/renderer/lib/chatSendGate.ts@@ -76,15 +76,19 @@ export function chatComposerPlaceholder({refusal,agentLabel,chip,- answerOnCard = false+ answerOnCard = false,+ screen = null}: {readonly: booleanrefusal: ChatSendRefusalagentLabel: stringchip: stringanswerOnCard?: boolean+ /** The pane's SCREEN says the agent's own UI owns the keyboard (`screenBlockedSentence`). */+ screen?: ScreenBlock | null}): string {if (readonly) return "Can't write to this session"+ if (screen !== null) return screenBlockedSentence(screen, agentLabel, chip)switch (refusal) {case 'working':return `${agentLabel} is working…`@@ -109,3 +113,22 @@ export function chatComposerPlaceholder({return `Message ${agentLabel}… (Enter to send, Shift+Enter for a new line)`}}++/** Why the pane's screen refuses input: one of the agent's own dialogs, or no input box. */+export type ScreenBlock = 'dialog' | 'no-prompt'++/**+ * The one sentence for a screen refusal — the composer's placeholder and the notice in the thread+ * both use it. Harness dialogs (folder trust, `/model`, setup questions) are answered in the+ * terminal: their options are not ours to guess, and the trust prompt's default is "No, exit".+ */+export function screenBlockedSentence(block: ScreenBlock, agentLabel: string, chip: string): string {+ if (block === 'dialog') {+ return chip+ ? `${agentLabel} is showing a dialog — press ${chip} to answer it in the terminal`+ : `${agentLabel} is showing a dialog — switch back to the terminal to answer it`+ }+ return chip+ ? `${agentLabel}'s input box isn't on screen — press ${chip} to check the terminal`+ : `${agentLabel}'s input box isn't on screen — switch back to the terminal to check it`+}diff --git a/src/renderer/nodes/ChatPanel.codexSend.test.tsx b/src/renderer/nodes/ChatPanel.codexSend.test.tsxindex 5129cac0a..477be18b7 100644--- a/src/renderer/nodes/ChatPanel.codexSend.test.tsx+++ b/src/renderer/nodes/ChatPanel.codexSend.test.tsx@@ -14,16 +14,16 @@ import type { PaneOwner } from '@shared/agents/pane-owner-predicate';(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true-const { sendText, paneOwner, session } = vi.hoisted(() => {- const sendText = vi.fn(async (_id: string, _text: string) => true as const)+const { sendChatPrompt, paneOwner, session } = vi.hoisted(() => {+ const sendChatPrompt = vi.fn(async (_id: string, _text: string, _agent: string) => true as const)const paneOwner = vi.fn(async (_id: string): Promise<PaneOwner | null> => null)const session = {api: {chat: { readTranscript: async () => ({ messages: [], found: true }) },- pty: { sendText, paneOwner }+ pty: { sendChatPrompt, paneOwner }}}- return { sendText, paneOwner, session }+ return { sendChatPrompt, paneOwner, session }})vi.mock('../session/session', () => ({ useSession: () => session }))@@ -57,7 +57,7 @@ async function send(ta: HTMLTextAreaElement, text: string): Promise<void> {}beforeEach(() => {- sendText.mockClear()+ sendChatPrompt.mockClear()paneOwner.mockReset()toasts = []window.addEventListener('nodeterm:toast', onToast)@@ -82,19 +82,19 @@ describe('ChatPanel — codex send asks the kernel', () => {paneOwner.mockResolvedValue(CODEX)await send(await mount('codex'), 'run the tests')expect(paneOwner).toHaveBeenCalledWith(NODE)- expect(sendText).toHaveBeenCalledWith(NODE, 'run the tests')+ expect(sendChatPrompt).toHaveBeenCalledWith(NODE, 'run the tests', 'codex')})it('refuses, with a toast, when a SHELL owns the pane though the store still reads done', async () => {paneOwner.mockResolvedValue(SHELL)await send(await mount('codex'), 'rm -rf build')- expect(sendText).not.toHaveBeenCalled()+ expect(sendChatPrompt).not.toHaveBeenCalled()expect(toasts).toEqual(['Codex is no longer running in this terminal — the message was not sent.'])})it('claude is not probed (its hooks announce a quit)', async () => {await send(await mount('claude'), 'hello')expect(paneOwner).not.toHaveBeenCalled()- expect(sendText).toHaveBeenCalled()+ expect(sendChatPrompt).toHaveBeenCalled()})})diff --git a/src/renderer/nodes/ChatPanel.composer.test.tsx b/src/renderer/nodes/ChatPanel.composer.test.tsxindex 7b45f7065..9432c11cd 100644--- a/src/renderer/nodes/ChatPanel.composer.test.tsx+++ b/src/renderer/nodes/ChatPanel.composer.test.tsx@@ -16,15 +16,17 @@ 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(() => {+// `sendText` types the picker commands (`/model`, `/effort`); a message goes through `sendChatPrompt`.+const { sendText, sendChatPrompt, session } = vi.hoisted(() => {const sendText = vi.fn((_id: string, _text: string): Promise<boolean | 'pasted-not-submitted'> => Promise.resolve(true))+ const sendChatPrompt = vi.fn(async (_id: string, _text: string, _agent: string) => true as const)const session = {api: {chat: { readTranscript: async () => ({ messages: [], found: true }) },- pty: { sendText }+ pty: { sendText, sendChatPrompt }}}- return { sendText, session }+ return { sendText, sendChatPrompt, session }})vi.mock('../session/session', () => ({ useSession: () => session }))@@ -90,6 +92,7 @@ const flush = () => act(async () => {beforeEach(() => {sendText.mockReset()sendText.mockResolvedValue(true)+ sendChatPrompt.mockClear()// Production's own escaper (the one `droppedPaths` applies), not a re-implementation of it.pathsForFiles = vi.fn(async (files: File[]) => files.map((f) => escapeDroppedPath(`/tmp/${f.name}`)))onShowTerminal = vi.fn()@@ -134,6 +137,7 @@ describe('composer attach ("+", paste, drop)', () => {expect(textarea().value).toBe('look at /tmp/shot\\ 1.png ')// Attaching never sends: the user decides when.expect(sendText).not.toHaveBeenCalled()+ expect(sendChatPrompt).not.toHaveBeenCalled()})it('a pasted file (a screenshot) becomes a path in the draft, not raw text', async () => {@@ -259,6 +263,7 @@ describe('composer mic', () => {expect(delivered).toBe(true)expect(textarea().value).toBe('please fix the tests')expect(sendText).not.toHaveBeenCalled()+ expect(sendChatPrompt).not.toHaveBeenCalled()})})@@ -405,7 +410,7 @@ describe('model / effort labels', () => {textarea().dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))})await flush()- expect(sendText).toHaveBeenCalledWith(NODE, 'go')+ expect(sendChatPrompt).toHaveBeenCalledWith(NODE, 'go', 'claude')expect(modelBtn()!.disabled).toBe(true)expect(effortBtn()!.disabled).toBe(true)// The real state speaks (the turn ran and finished): the labels come back.diff --git a/src/renderer/nodes/ChatPanel.live.test.tsx b/src/renderer/nodes/ChatPanel.live.test.tsxindex 90067c222..473cdce87 100644--- a/src/renderer/nodes/ChatPanel.live.test.tsx+++ b/src/renderer/nodes/ChatPanel.live.test.tsx@@ -22,7 +22,7 @@ interface Pending {reject: (e: unknown) => void}-const { pending, session, sendText } = vi.hoisted(() => {+const { pending, session, sendChatPrompt } = vi.hoisted(() => {const pending: Pending[] = []const readTranscript = (_s: string | undefined,@@ -32,9 +32,9 @@ const { pending, session, sendText } = vi.hoisted(() => {_g?: string,page?: ChatTranscriptPageRequest) => new Promise<ChatTranscriptResult>((resolve, reject) => pending.push({ page, resolve, reject }))- const sendText = vi.fn(async (_id: string, _t: string) => true as const)- const session = { api: { chat: { readTranscript }, pty: { sendText } } }- return { pending, session, sendText }+ const sendChatPrompt = vi.fn(async (_id: string, _t: string, _agent: string) => true as const)+ const session = { api: { chat: { readTranscript }, pty: { sendChatPrompt } } }+ return { pending, session, sendChatPrompt }})vi.mock('../session/session', () => ({ useSession: () => session }))@@ -76,7 +76,7 @@ async function advance(ms: number): Promise<void> {beforeEach(() => {vi.useFakeTimers()pending.length = 0- sendText.mockClear()+ sendChatPrompt.mockClear()geo.clientHeight = 400host = document.createElement('div')document.body.appendChild(host)@@ -107,7 +107,7 @@ describe('ChatPanel live progress', () => {await act(async () => {ta.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))})- expect(sendText).toHaveBeenCalledOnce()+ expect(sendChatPrompt).toHaveBeenCalledOnce()const row = activity()!expect(row.textContent).toBe('Claude Code is working…')expect(row.getAttribute('role')).toBe('status')@@ -482,7 +482,7 @@ describe('ChatPanel — a sent built-in that opens a dialog in the TUI', () => {it('/rewind is sent, THEN the view flips to the terminal (the dialog is there, and the next Enter would answer it)', async () => {const onShowTerminal = vi.fn(() => {// The flip happens only after the pane accepted the text.- expect(sendText).toHaveBeenCalledWith(NODE, '/rewind')+ expect(sendChatPrompt).toHaveBeenCalledWith(NODE, '/rewind', 'claude')})await hook('done')await renderWith(onShowTerminal)@@ -498,13 +498,13 @@ describe('ChatPanel — a sent built-in that opens a dialog in the TUI', () => {await settle(0, { messages: [say(0, 'hello')] })await send('/compact')await send('please rewind the file')- expect(sendText).toHaveBeenCalledTimes(2)+ expect(sendChatPrompt).toHaveBeenCalledTimes(2)expect(onShowTerminal).not.toHaveBeenCalled()})it('a refused send (pane not writable) never flips', async () => {const onShowTerminal = vi.fn()- sendText.mockResolvedValueOnce(false as never)+ sendChatPrompt.mockResolvedValueOnce(false as never)await hook('done')await renderWith(onShowTerminal)await settle(0, { messages: [say(0, 'hello')] })diff --git a/src/renderer/nodes/ChatPanel.screenDialog.test.tsx b/src/renderer/nodes/ChatPanel.screenDialog.test.tsxnew file mode 100644index 000000000..80e84e6f5--- /dev/null+++ b/src/renderer/nodes/ChatPanel.screenDialog.test.tsx@@ -0,0 +1,181 @@+// @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 type { ChatPromptResult } from '@shared/text-delivery'+import { useAgentStatus } from '../state/agentStatus'+import { CHAT_SCREEN_POLL_MS } from '../lib/chatLive'++/**+ * The agent's OWN dialogs (folder trust, /model, setup questions) fire no hook, so the chat view+ * reads the pane's screen: a local pane is polled while the view is visible (composer disabled, the+ * dialog's text in the thread), and every send is refused by core before writing when one is up —+ * the draft stays. The screen reader itself is tested in shared/agents/claude-screen.test.ts.+ */++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++const RULE = '─'.repeat(80)+const IDLE = [RULE, '❯ ', RULE, ' ⏵⏵ auto mode on'].join('\n')+const TRUST = [RULE, ' Accessing workspace:', ' ❯ No, exit', ' Yes, I trust this folder', ' Enter to confirm · Esc to cancel'].join(+ '\n'+)++const { screen, capture, sendChatPrompt, session } = vi.hoisted(() => {+ const screen = { now: '' }+ const capture = vi.fn(async (_id: string) => screen.now)+ const sendChatPrompt = vi.fn(async (_id: string, _t: string, _a: string): Promise<ChatPromptResult> => true)+ const session = {+ source: 'local',+ api: {+ chat: { readTranscript: async () => ({ messages: [], found: true, olderCursor: null, unmatchedResults: [] }) },+ pty: { capture, sendChatPrompt, sendText: vi.fn() }+ }+ }+ return { screen, capture, sendChatPrompt, session }+})+vi.mock('../session/session', () => ({ useSession: () => session }))++import { ChatPanel } from './ChatPanel'++const NODE = 'n-chat-screen'+let host: HTMLDivElement+let root: Root++const textarea = (): HTMLTextAreaElement => host.querySelector('textarea') as HTMLTextAreaElement+const notice = (): HTMLElement | null => host.querySelector('.term-chat__screen-block')++// An SSH node is the one whose panel gets `sshProjectId` (TerminalNode / CardModal).+async function mount(props: { remote?: boolean } = {}): Promise<void> {+ const sshProjectId = props.remote === true ? 'ssh-project' : undefined+ await act(async () => {+ root.render(<ChatPanel nodeId={NODE} sessionId="s1" agentId="claude" sshProjectId={sshProjectId} />)+ })+ const el = host.querySelector('.term-chat__msgs') as HTMLDivElement+ Object.defineProperty(el, 'clientHeight', { configurable: true, get: () => 400 })+}+async function tick(): Promise<void> {+ await act(async () => {+ vi.advanceTimersByTime(CHAT_SCREEN_POLL_MS)+ })+}+async function typeAndEnter(text: string): Promise<void> {+ const ta = textarea()+ await act(async () => {+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(ta, text)+ ta.dispatchEvent(new Event('input', { bubbles: true }))+ })+ await act(async () => {+ ta.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))+ })+}++beforeEach(() => {+ vi.useFakeTimers()+ screen.now = IDLE+ capture.mockClear()+ sendChatPrompt.mockReset()+ sendChatPrompt.mockResolvedValue(true)+ useAgentStatus.setState((s) => ({ byId: { ...s.byId, [NODE]: { state: 'done' } as (typeof s.byId)[string] } }))+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})+afterEach(async () => {+ await act(async () => root.unmount())+ host.remove()+ useAgentStatus.setState((s) => {+ const byId = { ...s.byId }+ delete byId[NODE]+ return { byId }+ })+ vi.useRealTimers()+})++describe('ChatPanel — the agent\'s own dialog on screen', () => {+ it('disables the composer and shows the dialog while a local pane shows one, then recovers', async () => {+ screen.now = TRUST+ await mount()+ await tick()++ expect(textarea().disabled).toBe(true)+ expect(textarea().placeholder).toMatch(/is showing a dialog — .* to answer it in the terminal/)+ expect(notice()?.textContent).toContain('No, exit')++ screen.now = IDLE+ await tick()++ expect(textarea().disabled).toBe(false)+ expect(notice()).toBeNull()+ })++ it('never polls a remote pane', async () => {+ await mount({ remote: true })+ await tick()+ await tick()++ expect(capture).not.toHaveBeenCalled()+ })++ it('never polls a relay tab (the pane is on the peer)', async () => {+ session.source = 'relay'+ try {+ await mount()+ await tick()++ expect(capture).not.toHaveBeenCalled()+ } finally {+ session.source = 'local'+ }+ })++ it('never polls for an agent whose screen it cannot read', async () => {+ await act(async () => {+ root.render(<ChatPanel nodeId={NODE} sessionId="s1" agentId="codex" />)+ })+ await tick()++ expect(capture).not.toHaveBeenCalled()+ })++ it('keeps the draft when core refuses the send before writing, and shows why', async () => {+ sendChatPrompt.mockResolvedValue({ blocked: 'screen', dialog: 'Set up auto mode?\n❯ Yes\n No' })+ await mount({ remote: true })++ await typeAndEnter('do the thing')++ expect(textarea().value).toBe('do the thing')+ expect(host.querySelector('.term-chat__msg--user')).toBeNull()+ expect(notice()?.textContent).toContain('Set up auto mode?')+ // Remote: nothing will clear this notice by itself, so the draft stays editable for the resend.+ expect(textarea().disabled).toBe(false)+ })++ it('a send that gets through clears a refused-send notice', async () => {+ sendChatPrompt.mockResolvedValueOnce({ blocked: 'screen', dialog: null }).mockResolvedValueOnce(true)+ await mount({ remote: true })+ await typeAndEnter('first try')+ expect(notice()?.textContent).toMatch(/input box isn't on screen/)++ await typeAndEnter('first try')++ expect(notice()).toBeNull()+ expect(host.querySelector('.term-chat__msg--user')?.textContent).toContain('first try')+ })++ it('shows the dialog\'s own lines in the thread', async () => {+ screen.now = TRUST+ await mount()+ await tick()++ expect(notice()?.querySelector('.term-chat__screen-block-text')?.textContent).toContain('Yes, I trust this folder')+ })++ it('asks core to check the screen for THIS agent', async () => {+ await mount()++ await typeAndEnter('hello')++ expect(sendChatPrompt).toHaveBeenCalledWith(NODE, 'hello', 'claude')+ })+})diff --git a/src/renderer/nodes/ChatPanel.sendGate.test.tsx b/src/renderer/nodes/ChatPanel.sendGate.test.tsxindex ed23fbf87..b3206e664 100644--- a/src/renderer/nodes/ChatPanel.sendGate.test.tsx+++ b/src/renderer/nodes/ChatPanel.sendGate.test.tsx@@ -16,15 +16,15 @@ import { useAgentStatus } from '../state/agentStatus'// 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 { sendChatPrompt, session } = vi.hoisted(() => {+ const sendChatPrompt = vi.fn(async (_id: string, _text: string, _agent: string) => true as const)const session = {api: {chat: { readTranscript: async () => ({ messages: [], found: true }) },- pty: { sendText }+ pty: { sendChatPrompt }}}- return { sendText, session }+ return { sendChatPrompt, session }})vi.mock('../session/session', () => ({ useSession: () => session }))@@ -61,7 +61,7 @@ const enter = (ta: HTMLTextAreaElement): void => {}beforeEach(() => {- sendText.mockClear()+ sendChatPrompt.mockClear()host = document.createElement('div')document.body.appendChild(host)root = createRoot(host)@@ -84,7 +84,7 @@ describe('ChatPanel send gate', () => {expect(ta.disabled).toBe(false)await act(async () => type(ta, 'hello'))await act(async () => enter(ta))- expect(sendText).toHaveBeenCalledWith(NODE, 'hello')+ expect(sendChatPrompt).toHaveBeenCalledWith(NODE, 'hello', 'claude')})it.each(['waiting', 'blocked'] as const)('disables the composer and explains while %s', async (state) => {@@ -104,7 +104,7 @@ describe('ChatPanel send gate', () => {setAgentState('waiting')enter(ta)})- expect(sendText).not.toHaveBeenCalled()+ expect(sendChatPrompt).not.toHaveBeenCalled()})it('disables the composer on a hibernated node: its state still reads done, but a SHELL owns the pane', async () => {@@ -122,7 +122,7 @@ describe('ChatPanel send gate', () => {setAgentState('done', { hibernated: true })enter(ta)})- expect(sendText).not.toHaveBeenCalled()+ expect(sendChatPrompt).not.toHaveBeenCalled()})it('disables the composer after the CLI exited (/exit, Ctrl+D): state undefined, a SHELL owns the pane', async () => {@@ -140,6 +140,6 @@ describe('ChatPanel send gate', () => {setAgentState(undefined, { sessionEnded: true })enter(ta)})- expect(sendText).not.toHaveBeenCalled()+ expect(sendChatPrompt).not.toHaveBeenCalled()})})diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsxindex cbe4247f0..7ea718756 100644--- a/src/renderer/nodes/ChatPanel.tsx+++ b/src/renderer/nodes/ChatPanel.tsx@@ -1,10 +1,11 @@-import { TEXT_NOT_SUBMITTED } from '@shared/text-delivery'+import { TEXT_NOT_SUBMITTED, isChatPromptBlocked } from '@shared/text-delivery'+import { claudeScreenBlocksInput, readClaudeScreen } from '@shared/agents/claude-screen'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 { chatComposerPlaceholder, chatSendRefusal, screenBlockedSentence, type ScreenBlock } from '../lib/chatSendGate'import { chatPaneRefusal, chatPaneRefusalToast } from '../lib/chatPaneGate'import { chatAgentLabel, isNearBottom, shouldFollowOnLoad, toolCardTitle } from '../lib/chatPanel'import { useSettings } from '../state/settings'@@ -22,10 +23,17 @@ import {import { E_UNSUPPORTED } from '@shared/rpc'import { GROK_AMBIGUOUS_SESSION_MESSAGE, isGrokAmbiguousSessionError } from '@shared/chat-page'import { Spinner } from '../components/Spinner'-import { CHAT_LIVE_RELOAD_MIN_MS, CHAT_OPTIMISTIC_WORKING_MS, chatActivity, planLiveReload } from '../lib/chatLive'+import {+ CHAT_LIVE_RELOAD_MIN_MS,+ CHAT_OPTIMISTIC_WORKING_MS,+ CHAT_SCREEN_POLL_MS,+ chatActivity,+ planLiveReload,+ shouldPollScreen+} from '../lib/chatLive'import { sentCommand } from '@shared/chat-command'import { isInteractiveBuiltin } from '@shared/chat-catalog'-import { capabilityAgentId, chatReadsLocalOnly } from '@shared/agents/config'+import { capabilityAgentId, chatReadsLocalOnly, readsScreenDialogs } from '@shared/agents/config'import { ChatLoadingStatus } from './ChatPanelFallback'import { answerCardState, answerRebindPending, rebindRetryDelay, type BoundAnswerCard } from '../lib/chatAnswer'import { AnswerControlsUpdating, PlanAnswerControls, QuestionAnswerControls } from './ChatAnswerControls'@@ -178,7 +186,7 @@ export function ChatPanel({}: ChatPanelProps) {// This node's core api (stable for the session — the chat transcript and the tmux session// both live on the core this panel's project belongs to).- const { api } = useSession()+ const { api, source } = useSession()// Which transcript this panel reads. Keys are byte offsets into ONE file, so a thread is only// ever merged with a read of the same identity (see lib/chatPaging.ts).const identity = JSON.stringify([nodeId, sessionId ?? null, cwd ?? null, accountId ?? null, agentId])@@ -219,6 +227,21 @@ export function ChatPanel({// Not just `working`: a TUI dialog (`waiting`/`blocked`) would be ANSWERED by sendText's Enter,// and a pane whose CLI is gone (hibernated/paused/dropped/exited) is a SHELL that would execute it.const refusal = chatSendRefusal(agentId, { state, hibernated, paused, dropped, sessionEnded })+ // The agent's OWN dialog on the pane's screen (folder trust, /model, setup questions): no hook+ // reports those, so the state gate above cannot see them. Found by the poll (local panes, `live`+ // — the poll also clears it) or by a send core refused before writing (`live: false` — it then+ // stays until a send gets through or the view closes). `text`: the dialog's own lines.+ const [screenBlock, setScreenBlock] = useState<{ kind: ScreenBlock; text: string | null; live: boolean } | null>(+ null+ )+ const pollScreen = shouldPollScreen({+ readable: readsScreenDialogs(agentId),+ readOnly: readOnly === true,+ // An SSH node's tmux is on its host (`sshProjectId` is set exactly for those); a relay tab's+ // is on the peer. Either way each read is a network round trip.+ remote: sshProjectId !== undefined || source !== 'local',+ refusal+ })const agentLabel = chatAgentLabel(agentId, customAgents)// What the row closing the thread says (lib/chatLive.ts). `optimistic` covers the gap between a// send and the first hook event: set by `send`, retired by the next state change (the real state@@ -597,6 +620,38 @@ export function ChatPanel({return () => clearTimeout(t)}, [optimistic])+ // Re-read the pane's screen while the view is visible (see `screenBlock`). A read that fails or+ // finds a blank screen changes nothing: unknown is not evidence either way.+ useEffect(() => {+ if (!pollScreen) {+ setScreenBlock((b) => (b?.live === true ? null : b))+ return+ }+ let cancelled = false+ const tick = async (): Promise<void> => {+ const el = msgsRef.current+ if (el === null || el.clientHeight === 0 || document.hidden) return+ let screen: string+ try {+ screen = await api.pty.capture(nodeId)+ } catch {+ return+ }+ if (cancelled) return+ const read = readClaudeScreen(screen)+ if (read.kind === 'unknown') return+ if (!claudeScreenBlocksInput(read)) setScreenBlock(null)+ else if (read.kind === 'dialog') setScreenBlock({ kind: 'dialog', text: read.text, live: true })+ else setScreenBlock({ kind: 'no-prompt', text: null, live: true })+ }+ void tick()+ const t = setInterval(() => void tick(), CHAT_SCREEN_POLL_MS)+ return () => {+ cancelled = true+ clearInterval(t)+ }+ }, [pollScreen, api, nodeId])+// Follow the newest message only when the user was already at the bottom or just sent; a user// scrolled up reading an earlier answer keeps their place. Layout effect: the jump lands before// paint, so a followed thread never flashes one frame short.@@ -618,8 +673,8 @@ export function ChatPanel({nearBottomRef.current = true}justSentRef.current = false- // `activity`: the status row appearing at the end grows the thread like a message does.- }, [messages, olderState, activity])+ // `activity` / `screenBlock`: a row appearing at the end grows the thread like a message does.+ }, [messages, olderState, activity, screenBlock])const maybeLoadOlder = useCallback(() => {const el = msgsRef.current@@ -689,7 +744,14 @@ export function ChatPanel({window.dispatchEvent(new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message } }))return}- const ok = await api.pty.sendText(nodeId, text)+ // Through core's chat-prompt path: where it can read the agent's screen, it refuses before+ // writing anything when the agent's own dialog owns the keyboard (such dialogs fire no hook).+ const ok = await api.pty.sendChatPrompt(nodeId, text, agentId)+ if (isChatPromptBlocked(ok)) {+ // Nothing reached the pane: the draft stays for a resend once the dialog is answered.+ setScreenBlock({ kind: ok.dialog === null ? 'no-prompt' : 'dialog', text: ok.dialog, live: pollScreen })+ return+ }if (ok === 'pasted-not-submitted') {window.dispatchEvent(new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message: TEXT_NOT_SUBMITTED } }))setInput('')@@ -701,6 +763,7 @@ export function ChatPanel({}// Optimistic: show the prompt immediately. A live read keeps it until the transcript carries it// (`carryUnconfirmed`); the turn-end reload / ↻ reconcile from the transcript outright.+ setScreenBlock(null)justSentRef.current = truesetThread((t) => ({ ...t, messages: [...t.messages, { role: 'user', parts: [{ kind: 'text', text }] }] }))setOptimistic(true)@@ -728,7 +791,7 @@ export function ChatPanel({}commandReadTimerRef.current = setTimeout(fire, CHAT_LIVE_RELOAD_MIN_MS)}- }, [api, input, nodeId, agentId, onShowTerminal])+ }, [api, input, nodeId, agentId, onShowTerminal, pollScreen])// The scheduled command read belongs to THIS transcript and this mount.useEffect(@@ -908,6 +971,14 @@ export function ChatPanel({)}</div>))}+ {screenBlock && (+ <div className="term-chat__screen-block" role="status" aria-live="polite">+ <div className="term-chat__screen-block-title">+ {screenBlockedSentence(screenBlock.kind, agentLabel, mdChip)}+ </div>+ {screenBlock.text !== null && <pre className="term-chat__screen-block-text">{screenBlock.text}</pre>}+ </div>+ )}{activity && (// One live region for both sentences, so working → waiting changes its text instead of// remounting it (a remounted role=status is announced again). The words are the@@ -938,9 +1009,12 @@ export function ChatPanel({refusal,agentLabel,chip: mdChip,- answerOnCard: answerCard !== null+ answerOnCard: answerCard !== null,+ screen: screenBlock?.live === true ? screenBlock.kind : null})}- disabled={readonly || refusal !== null}+ // A dialog the POLL found is also cleared by it; one a refused send found is not (a remote+ // pane is never polled), so that one leaves the draft editable for the resend.+ disabled={readonly || refusal !== null || screenBlock?.live === true}onWriteRefused={onWriteRefused}sendUnconfirmed={optimistic}pathsForFiles={pathsForFiles}diff --git a/src/renderer/nodes/ChatPanel.ux.test.tsx b/src/renderer/nodes/ChatPanel.ux.test.tsxindex 543b89937..1f5be8baa 100644--- a/src/renderer/nodes/ChatPanel.ux.test.tsx+++ b/src/renderer/nodes/ChatPanel.ux.test.tsx@@ -21,15 +21,15 @@ interface Pending {// 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, readTranscript, pending, session } = vi.hoisted(() => {+const { sendChatPrompt, readTranscript, pending, session } = vi.hoisted(() => {const pending: Pending[] = []- const sendText = vi.fn(async (_id: string, _text: string) => true as const)+ const sendChatPrompt = vi.fn(async (_id: string, _text: string, _agent: string) => true as const)const readTranscript = vi.fn((sessionId: string | undefined) =>new Promise<ChatTranscriptResult>((resolve, reject) => pending.push({ sessionId, resolve, reject })))- const session = { api: { chat: { readTranscript }, pty: { sendText } } }- return { sendText, readTranscript, pending, session }+ const session = { api: { chat: { readTranscript }, pty: { sendChatPrompt } } }+ return { sendChatPrompt, readTranscript, pending, session }})vi.mock('../session/session', () => ({ useSession: () => session }))@@ -76,7 +76,7 @@ function geometry(el: HTMLElement, g: { scrollHeight: number; clientHeight: numb}beforeEach(() => {- sendText.mockClear()+ sendChatPrompt.mockClear()readTranscript.mockClear()pending.length = 0host = document.createElement('div')@@ -103,7 +103,7 @@ describe('ChatPanel composer keys', () => {await act(async () => {ev = key(textarea(), { key: 'Enter', shiftKey: true })})- expect(sendText).not.toHaveBeenCalled()+ expect(sendChatPrompt).not.toHaveBeenCalled()expect(ev.defaultPrevented).toBe(false)})@@ -114,7 +114,7 @@ describe('ChatPanel composer keys', () => {await act(async () => {key(textarea(), { key: 'Enter', isComposing: true })})- expect(sendText).not.toHaveBeenCalled()+ expect(sendChatPrompt).not.toHaveBeenCalled()})it('plain Enter still sends', async () => {@@ -124,7 +124,7 @@ describe('ChatPanel composer keys', () => {await act(async () => {key(textarea(), { key: 'Enter' })})- expect(sendText).toHaveBeenCalledWith(NODE, 'hi')+ expect(sendChatPrompt).toHaveBeenCalledWith(NODE, 'hi', 'claude')})})diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex cb660db8b..6d82b57ff 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -3452,6 +3452,30 @@ body,font-size: 11px;opacity: 0.85;}+/* The agent's OWN dialog is on the pane's screen (ChatPanel's `screenBlock`): the sentence saying+ where to answer it, then the dialog's lines as the terminal shows them. Shaped like a tool card+ so it reads as part of the thread; monospace because the options are laid out in columns. */+.term-chat__screen-block {+ margin: 6px 0;+ padding: 10px 12px;+ background: rgba(var(--tint-rgb), 0.04);+ border: 1px solid rgba(var(--tint-rgb), 0.08);+ border-left: 2px solid var(--warn);+ border-radius: 8px;+ min-width: 0;+}+.term-chat__screen-block-title {+ font-size: 12px;+ font-weight: 600;+ color: var(--text-strong);+}+.term-chat__screen-block-text {+ margin: 8px 0 0;+ white-space: pre-wrap;+ font-family: ui-monospace, monospace;+ font-size: 11px;+ color: var(--muted);+}/* An expanded tool card: a tool part with a readable `body` (an ExitPlanMode plan, anAskUserQuestion question). Same tint as the chip so it still reads as "the agent's tool call",but open and full-width; no max-height, so a long plan scrolls with the thread. */diff --git a/src/shared/agents/claude-screen.test.ts b/src/shared/agents/claude-screen.test.tsnew file mode 100644index 000000000..1ef157cc5--- /dev/null+++ b/src/shared/agents/claude-screen.test.ts@@ -0,0 +1,152 @@+import { describe, expect, it } from 'vitest'+import { claudeScreenBlocksInput, readClaudeScreen } from './claude-screen'++// Shapes from Claude Code 2.1.283 captures (capture-pane, blank lines dropped, 100x40 pane), with+// the account, path and anything under the input box reduced to stock Claude Code. The reader never+// reads those lines; a custom statusline under the box has its own test below.+const RULE = '─'.repeat(100)+const HEADER = [' ▐▛███▛█ Claude Code v2.1.283', '▝▜██████▀ Sonnet 5 · API Usage Billing', ' ▝▝ ▝▝ ~/project']+const STATUS = [' ? for shortcuts']++const IDLE = [+ ...HEADER,+ ' ● high · /effort',+ RULE,+ '❯ Try "how do I log an error?"',+ RULE,+ ...STATUS+].join('\n')++const TRUST = [+ RULE,+ ' Accessing workspace:',+ ' ~/project',+ ' Quick safety check: Is this a project you created or one you trust? (Like your own code, a',+ ' well-known open source project, or work from your team). If not, take a moment to review what\'s in',+ ' this folder first.',+ " Claude Code'll be able to read, edit, and execute files here.",+ ' Security guide',+ ' ❯ No, exit',+ ' Yes, I trust this folder',+ ' Enter to confirm · Esc to cancel'+].join('\n')++const MODEL = [+ ...HEADER,+ '▔'.repeat(81) + ' ● high · /effort ▔',+ ' Select model',+ ' Switch between Claude models. Your pick becomes the default for new sessions. For',+ ' other/previous model names, specify with --model.',+ ' ❯ 1. Default (recommended) ✔ Opus 5.5 · Best for everyday, complex tasks',+ ' 2. Opus 5.5 Most capable for ambitious work',+ ' … +1 model',+ ' ● High effort ←/→ to adjust',+ ' Enter to set as default · s to use this session only · Esc to cancel'+].join('\n')++describe('readClaudeScreen', () => {+ it('reads the idle input box as a prompt', () => {+ expect(readClaudeScreen(IDLE)).toEqual({ kind: 'prompt' })+ })++ it('reads a working screen with a multi-line draft in the box as a prompt', () => {+ const working = [+ '⏺ Bash(sleep 20)',+ '✻ Working… (12s · esc to interrupt)',+ RULE,+ '❯ first line of a queued message',+ ' second line',+ RULE,+ ...STATUS+ ].join('\n')++ expect(readClaudeScreen(working)).toEqual({ kind: 'prompt' })+ })++ it('reads the folder-trust prompt as a dialog, with its text', () => {+ const s = readClaudeScreen(TRUST)++ expect(s.kind).toBe('dialog')+ expect(s.kind === 'dialog' && s.text.split('\n')[0]).toBe('Accessing workspace:')+ expect(s.kind === 'dialog' && s.text).toContain('❯ No, exit')+ expect(s.kind === 'dialog' && s.text.endsWith('Enter to confirm · Esc to cancel')).toBe(true)+ })++ it('reads the /model picker as a dialog, starting under its ▔ border', () => {+ const s = readClaudeScreen(MODEL)++ expect(s.kind).toBe('dialog')+ expect(s.kind === 'dialog' && s.text.split('\n')[0]).toBe('Select model')+ })++ it('starts the dialog under a border that has a notice painted over its start', () => {+ // Real 2.1.283 capture: the /model picker's ▔ edge with a tmux notice drawn over it.+ const noticed = MODEL.replace(/^▔+ ● high · \/effort ▔$/m, " tmux focus-events off · add 'set -g focus-events on' to ~/.tmux.conf… ▔")+ const s = readClaudeScreen(noticed)++ expect(s.kind === 'dialog' && s.text.split('\n')[0]).toBe('Select model')+ })++ it('reads the shell-mode input box (a `!` draft) as a prompt', () => {+ // 2.1.284: typing `!ls` swaps the `❯` for `!` (followed by a NO-BREAK SPACE) and the hint under+ // the box changes.+ const shellMode = [...HEADER, RULE, '!\u00a0ls', RULE, ' ! for shell mode'].join('\n')++ expect(readClaudeScreen(shellMode)).toEqual({ kind: 'prompt' })+ })++ it('reads the input box as a prompt under a multi-line custom statusline', () => {+ const statusline = [' model: sonnet-5 | ctx 12% | $0.42', ' branch: main | 3 files changed', ' ⏵⏵ accept edits on (shift+tab to cycle)']+ const screen = [...HEADER, RULE, '❯ ', RULE, ...statusline].join('\n')++ expect(readClaudeScreen(screen)).toEqual({ kind: 'prompt' })+ })++ it('a dialog ABOVE a visible input box is still a dialog — the footer decides', () => {+ const above = [...HEADER, ' Set up auto mode defaults?', ' ❯ Yes', ' No', ' Enter to confirm · Esc to cancel', RULE, '❯ ', RULE, ...STATUS].join('\n')++ expect(readClaudeScreen(above).kind).toBe('dialog')+ })++ it('a footer-looking line typed INTO the input box is the draft, not a dialog', () => {+ const draft = [...HEADER, RULE, '❯ the hint says Enter to confirm · Esc to cancel', RULE, ...STATUS].join('\n')++ expect(readClaudeScreen(draft)).toEqual({ kind: 'prompt' })+ })++ it('ignores a dialog left in the HISTORY above a live input box', () => {+ // Callers capture ~200 lines; a non-fullscreen CLI leaves an old trust prompt up there.+ const history = [TRUST, '⏺ Earlier reply', 'more text', 'and more', 'still more', 'and the last line', IDLE].join('\n')++ expect(readClaudeScreen(history)).toEqual({ kind: 'prompt' })+ })++ it('ignores an input box left in the history when something else now owns the bottom', () => {+ // The CLI died and a shell now owns the pane: more lines under the old box than a statusline has.+ const shellOutput = Array.from({ length: 9 }, (_, i) => `line ${i}`)+ const gone = [IDLE, 'Resume this session with: claude --resume abc', ...shellOutput, 'user@host ~ % '].join('\n')+ // A dialog drawn under an old box, ending in its footer.+ const dialogUnder = [IDLE, ...TRUST.split('\n').slice(1)].join('\n')++ expect(readClaudeScreen(gone)).toEqual({ kind: 'no-prompt' })+ expect(readClaudeScreen(dialogUnder).kind).toBe('dialog')+ })++ it('a shell prompt, or a CLI still starting, has no input box', () => {+ expect(readClaudeScreen('user@host ~ % ')).toEqual({ kind: 'no-prompt' })+ })++ it('a blank screen is unknown, and ANSI colour codes are ignored', () => {+ expect(readClaudeScreen('\n\n \n')).toEqual({ kind: 'unknown' })+ expect(readClaudeScreen(IDLE.replace('❯ Try', '\x1b[1m❯\x1b[0m Try'))).toEqual({ kind: 'prompt' })+ })+})++describe('claudeScreenBlocksInput', () => {+ it('blocks a dialog and a missing input box, never an unreadable screen', () => {+ expect(claudeScreenBlocksInput({ kind: 'dialog', text: '' })).toBe(true)+ expect(claudeScreenBlocksInput({ kind: 'no-prompt' })).toBe(true)+ expect(claudeScreenBlocksInput({ kind: 'prompt' })).toBe(false)+ expect(claudeScreenBlocksInput({ kind: 'unknown' })).toBe(false)+ })+})diff --git a/src/shared/agents/claude-screen.ts b/src/shared/agents/claude-screen.tsnew file mode 100644index 000000000..7c3601860--- /dev/null+++ b/src/shared/agents/claude-screen.ts@@ -0,0 +1,109 @@+/**+ * Does Claude Code's own UI own the keyboard right now? Read from the pane's SCREEN, because the+ * dialogs that matter here fire no hook: the folder-trust prompt, `/model`, one-time setup questions.+ * The agent state keeps reading idle (or working) while one is up, so the ⌘M chat view would type into+ * it — the text is swallowed and the Enter answers the dialog. On the trust prompt the highlighted+ * default is "No, exit".+ *+ * MEASURED on Claude Code 2.1.283 (fullscreen TUI, which nodeterm enables):+ * - At its prompt — idle, or working with the queue open — the bottom of the screen is the input+ * box: a `────` rule, a line starting `❯ ` at column 0 (continuation lines under it), another rule,+ * then the status lines. In shell mode (a draft starting `!`) the prompt character is `!` instead+ * (2.1.284; `#`, `&` and `@` drafts keep `❯`).+ * - The trust prompt and the `/model` picker REPLACE that box, and end in a key-hint footer+ * ("Enter to confirm · Esc to cancel", "… · s to use this session only · Esc to cancel").+ * - A setup dialog seen in the field took the Enter while the typed text landed in the input box, so+ * a dialog can also sit ABOVE a visible box. The footer alone is therefore enough to say "dialog".+ *+ * Only the BOTTOM of the capture is read: callers capture ~200 lines, history included, and a CLI+ * not in fullscreen mode leaves old dialogs and old input boxes in that history. The live box must+ * end within `BOX_TAIL_LINES` of the bottom, and a footer counts only in the last `FOOTER_TAIL_LINES`+ * lines, or at most `FOOTER_ABOVE_BOX_LINES` above the box — never further up the history.+ *+ * Only `prompt` means "safe to type". `unknown` (nothing readable) is left to the caller; a screen+ * with text but no input box and no footer is `no-prompt` — not necessarily a dialog (the CLI may be+ * starting, or gone and a shell owns the pane), but still no place to type a prompt.+ */+export type ClaudeScreen =+ | { kind: 'prompt' }+ | { kind: 'dialog'; text: string }+ | { kind: 'no-prompt' }+ | { kind: 'unknown' }++// eslint-disable-next-line no-control-regex+const ANSI = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g++/** A full-width rule of the input box (`─`, U+2500). */+const isRule = (line: string): boolean => /^─{20,}/.test(line.trim())+/** Any border a dialog is drawn under: the rule, or the `▔` top edge the `/model` picker uses. A+ * label or notice can be painted over part of it (measured: "● high · /effort", a tmux notice),+ * so it only has to START or END with the border characters. */+const isBorder = (line: string): boolean => /^\s*[─▔]{3,}/.test(line) || /[─▔]$/.test(line)+/** A key-hint footer. Capitalized on purpose: the working spinner says "esc to interrupt". */+const isFooter = (line: string): boolean => {+ const t = line.trim()+ return /^Enter to confirm\b/.test(t) || /(?:^|\s·\s)Esc to (?:cancel|exit|go back)$/.test(t)+}++/** Non-blank lines allowed under the box's bottom rule — the status lines (a custom statusline can+ * take several). */+const BOX_TAIL_LINES = 8+/** A footer with no box: a dialog's key hints are its last line (measured: trust prompt, /model). */+const FOOTER_TAIL_LINES = 3+/** A footer above a live box: a dialog drawn right on top of the input box. */+const FOOTER_ABOVE_BOX_LINES = 4++/** The input box's first line: the `❯` prompt, or `!` in shell mode — followed by a NO-BREAK SPACE+ * (U+00A0) there, measured, which `\s` covers. */+const isPromptLine = (line: string | undefined): boolean =>+ line !== undefined && (line.startsWith('❯') || /^!(\s|$)/.test(line))++/** Indexes of the non-blank lines, bottom first. */+const nonBlankFromBottom = (lines: readonly string[]): number[] =>+ lines.flatMap((l, i) => (l.trim() === '' ? [] : [i])).reverse()++/** The live input box: `[top rule, bottom rule]` line indexes, or null. */+function inputBox(lines: readonly string[]): [number, number] | null {+ const tail = nonBlankFromBottom(lines).slice(0, BOX_TAIL_LINES + 1)+ for (const bottom of tail) {+ if (bottom === 0 || !isRule(lines[bottom])) continue+ for (let top = bottom - 1; top >= 0 && bottom - top <= 40; top--) {+ if (!isRule(lines[top])) continue+ return isPromptLine(lines[top + 1]) && top + 1 < bottom ? [top, bottom] : null+ }+ return null+ }+ return null+}++/** The dialog's own lines: from the border above the footer down to the footer, dedented. */+function dialogText(lines: readonly string[], footer: number): string {+ let start = footer+ while (start > 0 && footer - start < 30 && !isBorder(lines[start - 1])) start--+ const body = lines.slice(start, footer + 1).filter((l) => l.trim() !== '')+ const indent = Math.min(...body.map((l) => l.length - l.trimStart().length))+ return body.map((l) => l.slice(indent)).join('\n')+}++export function readClaudeScreen(screen: string): ClaudeScreen {+ const lines = screen.replace(ANSI, '').split(/\r?\n/).map((l) => l.trimEnd())+ if (lines.every((l) => l === '')) return { kind: 'unknown' }+ const box = inputBox(lines)+ const bottom = nonBlankFromBottom(lines)+ // Where a footer may be: under the box (or at the very bottom when there is no box), and right+ // above the box. Never inside it — a footer there is the user's own draft.+ const candidates = box+ ? [+ ...bottom.filter((i) => i > box[1]),+ ...bottom.filter((i) => i < box[0]).slice(0, FOOTER_ABOVE_BOX_LINES)+ ]+ : bottom.slice(0, FOOTER_TAIL_LINES)+ const footer = candidates.find((i) => isFooter(lines[i]))+ if (footer !== undefined) return { kind: 'dialog', text: dialogText(lines, footer) }+ return box ? { kind: 'prompt' } : { kind: 'no-prompt' }+}++/** Refuse to type: anything but a visible input box, except a screen we could not read at all. */+export function claudeScreenBlocksInput(s: ClaudeScreen): boolean {+ return s.kind === 'dialog' || s.kind === 'no-prompt'+}diff --git a/src/shared/agents/config.capabilities.test.ts b/src/shared/agents/config.capabilities.test.tsindex 0fbc48743..dbf099e32 100644--- a/src/shared/agents/config.capabilities.test.ts+++ b/src/shared/agents/config.capabilities.test.ts@@ -26,6 +26,7 @@ import {agentLaunchProgram,resumeCommand,hasHooksOverSsh,+ readsScreenDialogs,LOCAL_ONLY_HOOK_AGENTS,reportsSessionEnd} from './config'@@ -455,3 +456,10 @@ describe('title read vs rename write', () => {expect(canRename('custom:abc')).toBe(false)})})++describe('readsScreenDialogs — whose own dialogs the chat view can see on screen', () => {+ it('is claude only: its reader would read every other CLI\'s screen as a permanent dialog', () => {+ expect(readsScreenDialogs('claude')).toBe(true)+ for (const id of BUILTIN_AGENT_IDS.filter((a) => a !== 'claude')) expect(readsScreenDialogs(id)).toBe(false)+ })+})diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.tsindex 0ea95f66a..c740810cc 100644--- a/src/shared/agents/config.ts+++ b/src/shared/agents/config.ts@@ -325,6 +325,13 @@ export const CHAT_LOCAL_ONLY = ['gemini', 'copilot'] as const// wrong answer is a read of SOMEONE ELSE'S session (see the comment above), which fails OPEN — it// shows data rather than hiding it. `config.capabilities.test.ts` pins that grok is absent.export const CLAUDE_TRANSCRIPT_READABLE = ['claude'] as const+// Agents whose own UI dialogs we can recognize on SCREEN (shared/agents/claude-screen.ts). A CLI's+// built-in dialogs — the folder-trust prompt, /model, one-time setup questions — fire NO hook, so the+// agent state still reads idle while the dialog owns the keyboard, and anything the chat view types+// into the pane is swallowed, or worse: the trust prompt's default is "No, exit". The reader matches+// claude's screen layout (MEASURED on 2.1.283); another CLI's layout would read as a permanent+// dialog and lock its chat view, so each agent needs its own measured reader.+export const SCREEN_DIALOG_READABLE = ['claude'] as const// Agents whose native transcript we can read + render for cross-agent transfer.export const TRANSFER_SOURCE_CAPABLE = ['claude', 'codex', 'gemini', 'grok'] as const// Agents whose hooks announce that a session ENDED — i.e. whose orderly `/exit` we will hear about.@@ -537,6 +544,7 @@ export const canContextLink = (id: AgentId): boolean => includes(CONTEXT_LINK_CAexport const hasUsage = (id: AgentId): boolean => includes(USAGE_CAPABLE, id)export const canChat = (id: AgentId): boolean => includes(CHAT_CAPABLE, id)export const chatReadsLocalOnly = (id: AgentId): boolean => includes(CHAT_LOCAL_ONLY, id)+export const readsScreenDialogs = (id: AgentId): boolean => includes(SCREEN_DIALOG_READABLE, id)/** Can CLAUDE's transcript resolver locate and parse this agent's conversation? Never widen this* to mean "can we read this agent" — see CLAUDE_TRANSCRIPT_READABLE. */export const readsClaudeShapedTranscript = (id: AgentId): boolean =>diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 49ceb2524..0c7b6e4ef 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -28,6 +28,7 @@ export const IPC = {ptySessionAge: 'pty:session-age',ptyReadScrollback: 'pty:read-scrollback',ptySendText: 'pty:send-text',+ ptySendChatPrompt: 'pty:send-chat-prompt',ptyTmuxStatus: 'pty:tmux-status',/** The foreground command of a node's tmux pane (`#{pane_current_command}`) — how the in-place* agent restart sees that the CLI has exited and a shell owns the pane again. */diff --git a/src/shared/text-delivery.ts b/src/shared/text-delivery.tsindex 5a886dd7d..541fd6aa4 100644--- a/src/shared/text-delivery.ts+++ b/src/shared/text-delivery.ts@@ -1,3 +1,17 @@/** A partial or transport-uncertain paste must never be retried or represented as submitted. */export type TextDeliveryResult = boolean | 'pasted-not-submitted'export const TEXT_NOT_SUBMITTED = 'Text may already be pasted, but submission could not be confirmed. Do not resend it. Inspect the terminal before taking further action.'++/**+ * The ⌘M chat view's send was refused BEFORE anything was written: the agent's own UI owns the+ * keyboard (shared/agents/claude-screen.ts). `dialog` is the dialog's text when one was recognized,+ * `null` when the input box is simply not on screen. The draft is untouched — nothing reached the pane.+ */+export interface ChatPromptBlocked {+ blocked: 'screen'+ dialog: string | null+}+/** What a chat-view send answers: a text delivery, or a refusal before writing. */+export type ChatPromptResult = TextDeliveryResult | ChatPromptBlocked+export const isChatPromptBlocked = (r: ChatPromptResult): r is ChatPromptBlocked =>+ typeof r === 'object' && r !== null && r.blocked === 'screen'diff --git a/src/shared/types.ts b/src/shared/types.tsindex d7a515843..c8a7df079 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1,4 +1,4 @@-import type { TextDeliveryResult } from './text-delivery'+import type { ChatPromptResult, TextDeliveryResult } from './text-delivery'import type { PushWebhookMinted, PushWebhookResult, PushWebhookTokenInfo } from './push-webhook'import type { IdentitySeedEntry } from './agent-identity-seed'import type { PrWaitHold } from './pr-wait'@@ -1290,6 +1290,10 @@ export interface PtyApi {* false if unavailable; `pasted-not-submitted` means input was accepted but Enter was not* confirmed written. Surface it without automatically resending. True is not an app receipt. */sendText(persistKey: string, text: string, opts?: { enter?: boolean }): Promise<TextDeliveryResult>+ /** Submit a prompt from the ⌘M chat view. For an agent whose screen can be read+ * (`readsScreenDialogs`), refused BEFORE anything is written when the agent's own dialog owns the+ * keyboard (`ChatPromptBlocked`) — such dialogs fire no hook. Otherwise the `sendText` contract. */+ sendChatPrompt(persistKey: string, text: string, agentId: string): Promise<ChatPromptResult>/** Is tmux available on this host (else the silent plain-shell fallback), plus a suggested* install command for the "tmux not found" banner. */tmuxStatus(): Promise<TmuxStatus>