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.

feat(chat): Esc in the ⌘M view interrupts a working Claude

Paul Robertson678474995df9
diff --git a/CLAUDE.md b/CLAUDE.md
index 839a4f8b0..b4581bbd1 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4442,6 +4442,26 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
elsewhere; the screen-wide count never rose and every such send ended `pasted-not-submitted` with
the answer sitting in the box. The screen-wide count stays only as the fallback for a poll with
no readable input box (a draft too tall for the box reader).
+ **Esc in the chat view interrupts a running turn** (`lib/chatEscInterrupt.ts`, core
+ `PtyManager.interruptChat`, `pty:interrupt-chat`), as Esc in the terminal would. Only when ALL of:
+ the agent is in `CHAT_INTERRUPT_CAPABLE` (claude, MEASURED on 2.1.318), the state is `working`
+ (idle, two Escs open Claude's rewind picker, which fires no hook; blocked/waiting, Esc cancels the
+ dialog), and the composer is EMPTY (with a draft, Esc means "never mind"). Core reads the screen
+ first and refuses on a dialog, then sends a lone Esc through `sendPaneKeys`. An Esc before the
+ reply's first token makes Claude put the prompt back into its own input box (measured 0.05-0.11 s);
+ core takes it back out ONLY when the box holds exactly the chat view's last send, and hands it to
+ the composer. It clears the box with Ctrl-U, never Ctrl-C: Ctrl-C clears it too but then arms
+ "Press Ctrl-C again to exit" for a few seconds. Claude still writes such a prompt to the
+ transcript as a branch it drops from its context, so the chat view keeps showing it (the reader
+ does not follow `parentUuid`; known gap). The panel also makes the terminal's interrupt guess
+ (`inferInterruptAfterSettle`), since an early Esc writes no transcript marker.
+ **An interrupt is drawn as Claude draws it, not as a user bubble.** Claude saves its marker
+ (`CLAUDE_INTERRUPT_MARKERS`, now in `shared/agents/claude-interrupt.ts`, shared with the context
+ tail) as a USER record. On the `rich` read the parser turns it into an `interrupt` part on the
+ assistant side, drawn as `⎿ Interrupted · What should Claude do instead?`, and a tool call it
+ cancelled shows "Interrupted" instead of Claude's canned "The user doesn't want to proceed…"
+ result. Without `rich` (the phone's `chat.page`, the golden fixtures) nothing changes; the iOS
+ reader owes the same treatment (@eneskirca).
**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
diff --git a/src/core/context-tail.ts b/src/core/context-tail.ts
index 5b79a93db..925f75857 100644
--- a/src/core/context-tail.ts
+++ b/src/core/context-tail.ts
@@ -6,6 +6,7 @@ import fs from 'fs'
import type { ContextWindowUsage } from '../shared/types'
import { cachedWindowFor } from './model-window'
import { splitCompleteLines } from './subagent-tail'
+import { claudeInterruptMarkerOf } from '../shared/agents/claude-interrupt'
const POLL_MS = 1000
// Cap the initial read: a resumed Claude transcript can be many MB, and reading the whole file
@@ -133,18 +134,7 @@ export function parseToolResultIds(text: string | string[]): string[] {
return ids
}
-/**
- * The two texts Claude Code writes as a USER record when the user interrupts a turn (Esc, or
- * Ctrl+C once). A CLOSED set: measured on 2.1.285 (`shared/agents/__fixtures__/claude/
- * interrupt-capture.json`) — `[Request interrupted by user]` after streamed text,
- * `… for tool use]` when a tool call or its permission dialog was cancelled. Any other wording is
- * ignored, so a future CLI that words it differently degrades to what happened before this
- * existed (the node waits for its next hook, or the stale sweep), never to a guess.
- */
-export const CLAUDE_INTERRUPT_MARKERS: ReadonlySet<string> = new Set([
- '[Request interrupted by user]',
- '[Request interrupted by user for tool use]'
-])
+export { CLAUDE_INTERRUPT_MARKERS } from '../shared/agents/claude-interrupt'
const PROMPT_ID_RE = /^[A-Za-z0-9_-]{1,128}$/
@@ -159,12 +149,7 @@ type TranscriptRecord = {
message?: { content?: unknown }
}
-const isMarkerRecord = (o: TranscriptRecord): boolean => {
- const content = o.message?.content
- if (!Array.isArray(content) || content.length !== 1) return false
- const part = content[0] as { type?: unknown; text?: unknown } | null
- return part?.type === 'text' && typeof part.text === 'string' && CLAUDE_INTERRUPT_MARKERS.has(part.text)
-}
+const isMarkerRecord = (o: TranscriptRecord): boolean => claudeInterruptMarkerOf(o.message?.content) !== null
/** A main-thread user record that OPENS a turn: the typed (or dequeued) prompt itself — not a tool
* result, not a meta record, not the interrupt marker. */
diff --git a/src/core/gemini-chat.test.ts b/src/core/gemini-chat.test.ts
index 34eed7369..e0574aaba 100644
--- a/src/core/gemini-chat.test.ts
+++ b/src/core/gemini-chat.test.ts
@@ -44,7 +44,7 @@ const msg = (id: string, type: string, content: unknown, extra: Rec = {}): Rec =
})
const jsonl = (...recs: unknown[]): string => recs.map((r) => (typeof r === 'string' ? r : JSON.stringify(r))).join('\n') + '\n'
const texts = (ms: ChatMessage[]): string[] =>
- ms.map((m) => `${m.role}:${m.parts.map((p) => (p.kind === 'tool' ? `[${p.name}|${p.arg}|${p.result ?? ''}]` : p.kind === 'image' ? '[image]' : p.text)).join('+')}`)
+ ms.map((m) => `${m.role}:${m.parts.map((p) => (p.kind === 'tool' ? `[${p.name}|${p.arg}|${p.result ?? ''}]` : p.kind === 'image' ? '[image]' : p.kind === 'interrupt' ? '[interrupt]' : p.text)).join('+')}`)
describe('chatFromGemini — the fold', () => {
it('renders a typed prompt and the model answer, stamped with their own timestamps', () => {
diff --git a/src/core/pty-manager.interrupt-chat.test.ts b/src/core/pty-manager.interrupt-chat.test.ts
new file mode 100644
index 000000000..4cc923f16
--- /dev/null
+++ b/src/core/pty-manager.interrupt-chat.test.ts
@@ -0,0 +1,136 @@
+// `PtyManager.interruptChat` — Esc from the ⌘M chat view. The screen is read before the Esc (a dialog
+// would be cancelled by it), and an Esc that beat the reply's first token has its prompt taken back
+// out of Claude's input box (MEASURED on Claude Code 2.1.318: Claude puts it back there).
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform } from './platform-fake'
+import type { PaneKeysResult } from '../shared/types'
+
+vi.mock('node-pty', () => ({ spawn: () => ({}) }))
+
+const NODE = 'node-1'
+const RULE = '─'.repeat(80)
+const DIM = '\x1b[2m'
+const RESET = '\x1b[0m'
+const screen = (promptLine: string): string => [RULE, promptLine, RULE, ' ? for shortcuts'].join('\n')
+const EMPTY = screen('❯ ')
+const PLACEHOLDER = screen(`❯ ${DIM}finish the story${RESET}`)
+const draft = (text: string): string => screen(`❯ ${text}`)
+const TRUST = [RULE, ' Accessing workspace:', ' ❯ No, exit', ' Yes, I trust this folder', ' Enter to confirm · Esc to cancel'].join('\n')
+
+type Private = { captureStyledScreen: (key: string) => Promise<string> }
+
+async function manager(opts: { plain: string; styled?: string[]; keys?: PaneKeysResult }) {
+ const { PtyManager } = await import('./pty-manager')
+ const mgr = new PtyManager()
+ vi.spyOn(mgr, 'captureSession').mockResolvedValue(opts.plain)
+ const styled = [...(opts.styled ?? [])]
+ const last = styled.at(-1) ?? EMPTY
+ vi.spyOn(mgr as unknown as Private, 'captureStyledScreen').mockImplementation(async () => styled.shift() ?? last)
+ const sendPaneKeys = vi.spyOn(mgr, 'sendPaneKeys').mockResolvedValue(opts.keys ?? { ok: true })
+ return { mgr, sendPaneKeys }
+}
+
+describe('PtyManager.interruptChat', () => {
+ beforeEach(() => {
+ vi.resetModules()
+ vi.useFakeTimers()
+ initPlatform(fakePlatform())
+ })
+ afterEach(() => {
+ vi.useRealTimers()
+ resetPlatformForTests()
+ })
+
+ it('sends a lone Esc to a working claude', async () => {
+ const { mgr, sendPaneKeys } = await manager({ plain: EMPTY })
+
+ const result = await mgr.interruptChat(NODE, 'claude')
+
+ expect(sendPaneKeys).toHaveBeenCalledTimes(1)
+ expect(sendPaneKeys).toHaveBeenCalledWith(NODE, '\x1b')
+ expect(result).toEqual({ sent: true, restored: null })
+ })
+
+ it('refuses before writing when a dialog owns the screen, and returns its text', async () => {
+ const { mgr, sendPaneKeys } = await manager({ plain: TRUST })
+
+ const result = await mgr.interruptChat(NODE, 'claude')
+
+ expect(sendPaneKeys).not.toHaveBeenCalled()
+ expect(result).toEqual({ sent: false, reason: 'dialog', dialog: expect.stringContaining('No, exit') })
+ })
+
+ it('an empty capture is not evidence of a dialog: the Esc is sent', async () => {
+ const { mgr, sendPaneKeys } = await manager({ plain: '' })
+
+ const result = await mgr.interruptChat(NODE, 'claude')
+
+ expect(sendPaneKeys).toHaveBeenCalledWith(NODE, '\x1b')
+ expect(result).toEqual({ sent: true, restored: null })
+ })
+
+ it('refuses an agent whose interrupt is not measured, without reading or writing', async () => {
+ const { mgr, sendPaneKeys } = await manager({ plain: EMPTY })
+
+ const result = await mgr.interruptChat(NODE, 'codex')
+
+ expect(sendPaneKeys).not.toHaveBeenCalled()
+ expect(result).toEqual({ sent: false, reason: 'unsupported' })
+ })
+
+ it("passes on sendPaneKeys's refusal", async () => {
+ const { mgr } = await manager({ plain: EMPTY, keys: { ok: false, reason: 'unsupported-backend' } })
+
+ const result = await mgr.interruptChat(NODE, 'claude', 'hello')
+
+ expect(result).toEqual({ sent: false, reason: 'unsupported-backend' })
+ })
+
+ it('takes the interrupted prompt back out of the input box and clears it with Ctrl-U, never Ctrl-C', async () => {
+ const { mgr, sendPaneKeys } = await manager({
+ plain: EMPTY,
+ styled: [EMPTY, draft('Write a story'), draft('Write a story'), PLACEHOLDER]
+ })
+
+ const pending = mgr.interruptChat(NODE, 'claude', 'Write a\nstory')
+ await vi.runAllTimersAsync()
+ const result = await pending
+
+ // Two lines: two Ctrl-Us per line plus two spares (a Ctrl-U on an empty box does nothing).
+ expect(sendPaneKeys.mock.calls.map((c) => c[1])).toEqual(['\x1b', '\x15'.repeat(6)])
+ expect(result).toEqual({ sent: true, restored: 'Write a\nstory' })
+ })
+
+ it("leaves the user's own text in the box alone", async () => {
+ const { mgr, sendPaneKeys } = await manager({ plain: EMPTY, styled: [draft('something else')] })
+
+ const pending = mgr.interruptChat(NODE, 'claude', 'Write a story')
+ await vi.runAllTimersAsync()
+ const result = await pending
+
+ expect(sendPaneKeys.mock.calls.map((c) => c[1])).toEqual(['\x1b'])
+ expect(result).toEqual({ sent: true, restored: null })
+ })
+
+ it('gives up when nothing comes back into the box (an Esc mid-reply)', async () => {
+ const { mgr, sendPaneKeys } = await manager({ plain: EMPTY, styled: [PLACEHOLDER] })
+
+ const pending = mgr.interruptChat(NODE, 'claude', 'Write a story')
+ await vi.runAllTimersAsync()
+ const result = await pending
+
+ expect(sendPaneKeys.mock.calls.map((c) => c[1])).toEqual(['\x1b'])
+ expect(result).toEqual({ sent: true, restored: null })
+ })
+
+ it('does not report a restore when the box does not read empty after the Ctrl-C', async () => {
+ const { mgr } = await manager({ plain: EMPTY, styled: [draft('Write a story')] })
+
+ const pending = mgr.interruptChat(NODE, 'claude', 'Write a story')
+ await vi.runAllTimersAsync()
+ const result = await pending
+
+ expect(result).toEqual({ sent: true, restored: null })
+ })
+})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 2f1293b5c..803f83b8e 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -1,4 +1,10 @@
-import type { ChatPromptBlocked, ChatPromptResult, EmptyPromptResult, TextDeliveryResult } from '../shared/text-delivery'
+import type {
+ ChatInterruptResult,
+ ChatPromptBlocked,
+ ChatPromptResult,
+ EmptyPromptResult,
+ TextDeliveryResult
+} from '../shared/text-delivery'
import { claudeScreenBlocksInput, readClaudeComposer, readClaudeDraft, readClaudeScreen } from '../shared/agents/claude-screen'
import os from 'os'
import fs from 'fs'
@@ -188,6 +194,7 @@ import {
submitsSeparately,
hasSharedIdentity,
readsScreenDialogs,
+ interruptsFromChat,
setCustomAgentBaseResolver,
typesChatInput,
vanillaEnvStripPattern,
@@ -1174,6 +1181,12 @@ function screenGate(screen: string): ChatPromptBlocked | null {
* survives, so reopening the node or restarting the app reattaches and continues
* where it left off. Without tmux, it falls back to a plain shell (no persistence).
*/
+/** How long a chat-view interrupt waits for Claude to put the interrupted prompt back in its input
+ * box (MEASURED on 2.1.318: 0.05-0.11 s after the Esc), and how often it looks. Also the wait for
+ * the box to read empty after the Ctrl-Us that clear it. */
+export const INTERRUPT_RESTORE_WAIT_MS = 1500
+export const INTERRUPT_RESTORE_POLL_MS = 150
+
/** Gap between a paste and its separate Enter for SEPARATE_SUBMIT_AGENTS (the rename path's
* measured shape: paste, then Enter as its own tmux invocation). */
const SEPARATE_SUBMIT_DELAY_MS = 150
@@ -2283,6 +2296,15 @@ export class PtyManager {
// Like `agentId` above: it only picks the composer reader, and a non-string picks none.
this.sendToEmptyPrompt(persistKey, text, typeof agentId === 'string' ? agentId : '')
)
+ platform().handle(IPC.ptyInterruptChat, (persistKey: string, agentId: unknown, sentText: unknown) =>
+ // `agentId` only picks the capability (a non-string picks none: `unsupported`), and `sentText`
+ // is only compared with what the agent put back in its own input box.
+ this.interruptChat(
+ persistKey,
+ typeof agentId === 'string' ? agentId : '',
+ typeof sentText === 'string' ? sentText : undefined
+ )
+ )
platform().handle(IPC.ptyTmuxStatus, () => this.tmuxStatus())
platform().handle(IPC.ptyPaneCommand, (persistKey: string, opts?: { resolveUnmounted?: boolean }) =>
this.paneCommand(persistKey, opts?.resolveUnmounted === true ? { resolveUnmounted: true } : undefined)
@@ -6827,6 +6849,62 @@ export class PtyManager {
})
}
+ /**
+ * Esc from the ⌘M chat view: interrupt the running turn as Esc typed in the terminal would. Only
+ * for an agent whose interrupt and screen are measured (`interruptsFromChat`, claude), and refused
+ * before anything is written when the agent's own dialog owns the keyboard or no input box is on
+ * screen: Esc there would cancel the dialog. An empty capture is not evidence of a dialog (the
+ * `sendChatPrompt` rule). The Esc goes through `sendPaneKeys`, so it reaches the pane by node id
+ * with no mounted terminal, local or over the project's ControlMaster.
+ *
+ * MEASURED on Claude Code 2.1.318: an Esc before the reply's first token puts the prompt back into
+ * Claude's own input box, where the chat view cannot see it, and the next chat send would be typed
+ * after it. So when `sentText` (the chat view's last send) is given and the box comes to hold
+ * exactly that text, it is cleared and handed back as `restored`. Any other text in the box is the
+ * user's and is left alone. Cleared with Ctrl-U, never Ctrl-C: Ctrl-C clears it too but then
+ * shows "Press Ctrl-C again to exit" for a few seconds, and a Ctrl-C the user presses in that window
+ * would quit Claude. Runs inside `serializePaneWrite`, so a chat send cannot land between the Esc
+ * and the read.
+ */
+ async interruptChat(persistKey: string, agentId: string, sentText?: string): Promise<ChatInterruptResult> {
+ if (!interruptsFromChat(agentId) || !readsScreenDialogs(agentId)) return { sent: false, reason: 'unsupported' }
+ return this.serializePaneWrite(persistKey, async (): Promise<ChatInterruptResult> => {
+ const screen = await this.captureSession(persistKey)
+ const gate = screen === '' ? null : screenGate(screen)
+ if (gate !== null) return { sent: false, reason: 'dialog', dialog: gate.dialog }
+ const esc = await this.sendPaneKeys(persistKey, '\x1b')
+ if (!esc.ok) return { sent: false, reason: esc.reason }
+ const want = sentText === undefined ? '' : sentText.replace(/\s/g, '')
+ if (want === '') return { sent: true, restored: null }
+ const took = await this.takeBackInterruptedPrompt(persistKey, sentText ?? '', want)
+ return { sent: true, restored: took ? (sentText ?? null) : null }
+ })
+ }
+
+ /** After an interrupt: wait briefly for Claude to put `want` (whitespace removed) back in its input
+ * box, then clear it. true only when the box held exactly that text and reads empty afterwards. */
+ private async takeBackInterruptedPrompt(persistKey: string, sentText: string, want: string): Promise<boolean> {
+ const readDraft = async (): Promise<string | null> => readClaudeDraft(await this.captureStyledScreen(persistKey))
+ const until = async (done: (draft: string | null) => boolean, ms: number): Promise<string | null> => {
+ const deadline = Date.now() + ms
+ for (;;) {
+ const draft = await readDraft()
+ if (done(draft) || Date.now() >= deadline) return draft
+ await new Promise((r) => setTimeout(r, INTERRUPT_RESTORE_POLL_MS))
+ }
+ }
+ // Stop at the first non-empty draft: ours, or text the user typed into the terminal (left alone).
+ const draft = await until((d) => d !== null && d !== '', INTERRUPT_RESTORE_WAIT_MS)
+ if (draft !== want) return false
+ // One Ctrl-U clears a line; at the start of a line it joins it to the one above. MEASURED (2.1.318):
+ // repeated Ctrl-Us empty a multi-line box, and a Ctrl-U on an empty box does nothing, so one per
+ // line plus spares is safe in a single write.
+ const lines = sentText.split('\n').length
+ const cleared = await this.sendPaneKeys(persistKey, '\x15'.repeat(2 * lines + 2))
+ if (!cleared.ok) return false
+ return (await until((d) => d === '', INTERRUPT_RESTORE_WAIT_MS)) === ''
+ }
+
/** The visible screen WITH its SGR, for `readClaudeComposer`: an ssh-project node's capture already
* carries `-e` (`remoteCapturePaneArgs`), everything else is `captureSnapshot`. '' on any failure. */
private async captureStyledScreen(persistKey: string): Promise<string> {
diff --git a/src/core/relay/access-policy.ts b/src/core/relay/access-policy.ts
index 61c18acd3..6619184c7 100644
--- a/src/core/relay/access-policy.ts
+++ b/src/core/relay/access-policy.ts
@@ -344,6 +344,7 @@ export const EDITOR_ONLY: ReadonlySet<string> = new Set<string>([
IPC.ptySendText,
IPC.ptySendChatPrompt,
IPC.ptySendToEmptyPrompt,
+ IPC.ptyInterruptChat,
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.ts
index d79cea959..2fc671ec5 100644
--- a/src/core/relay/scoped-guest-policy.ts
+++ b/src/core/relay/scoped-guest-policy.ts
@@ -389,6 +389,7 @@ export const SCOPED: Readonly<Record<string, Check>> = Object.freeze({
[IPC.ptySendText]: nodeArg0,
[IPC.ptySendChatPrompt]: nodeArg0,
[IPC.ptySendToEmptyPrompt]: nodeArg0,
+ [IPC.ptyInterruptChat]: nodeArg0,
[IPC.ptyTmuxStatus]: pass,
[IPC.ptyPaneCommand]: nodeArg0,
[IPC.ptyPaneCwd]: nodeArg0,
diff --git a/src/core/transcript-reader.interrupt.test.ts b/src/core/transcript-reader.interrupt.test.ts
new file mode 100644
index 000000000..fa40bbcd8
--- /dev/null
+++ b/src/core/transcript-reader.interrupt.test.ts
@@ -0,0 +1,66 @@
+// An interrupted turn in the ⌘M thread (opt-in `rich`). Claude Code saves its interrupt marker as a
+// USER record, but the user did not type it: it becomes an `interrupt` part on the assistant side,
+// and a tool call it cancelled shows "Interrupted" instead of Claude's canned rejection. Read from
+// the captured transcripts (`__fixtures__/claude/interrupt-capture.json`, Claude Code 2.1.285).
+import fs from 'fs'
+import path from 'path'
+import { describe, expect, it } from 'vitest'
+import { INTERRUPTED_TOOL_RESULT, parseChatMessages } from './transcript-reader'
+import type { ChatMessage } from '../shared/types'
+
+const fixture = JSON.parse(
+ fs.readFileSync(path.join(__dirname, '../shared/agents/__fixtures__/claude/interrupt-capture.json'), 'utf8')
+) as { scenarios: Record<string, { transcript: unknown[] }> }
+const lines = (scenario: string): string[] => fixture.scenarios[scenario].transcript.map((r) => JSON.stringify(r))
+
+const shape = (ms: ChatMessage[]): string[] =>
+ ms.map(
+ (m) =>
+ `${m.role}:${m.parts
+ .map((p) => (p.kind === 'tool' ? `tool(${p.name}|${p.result ?? ''})` : p.kind === 'text' ? p.text : p.kind))
+ .join('+')}`
+ )
+
+describe('interrupt markers in the chat thread', () => {
+ it('rich: an interrupt mid-reply is an interrupt part, not a user bubble', () => {
+ const ms = parseChatMessages(lines('esc_streaming'), { rich: true })
+
+ const last = ms.at(-1)
+ expect(last).toMatchObject({ role: 'assistant', parts: [{ kind: 'interrupt' }] })
+ expect(shape(ms).some((s) => s.includes('[Request interrupted'))).toBe(false)
+ })
+
+ it.each(['esc_tool_call', 'esc_permission_prompt'])(
+ 'rich: a cancelled tool call (%s) says Interrupted, then the interrupt part',
+ (scenario) => {
+ const ms = parseChatMessages(lines(scenario), { rich: true })
+
+ expect(shape(ms).slice(-2)).toEqual([`assistant:tool(Bash|${INTERRUPTED_TOOL_RESULT})`, 'assistant:interrupt'])
+ }
+ )
+
+ it('without rich, the marker and the rejection stay as before (the phone reads this)', () => {
+ const ms = parseChatMessages(lines('esc_tool_call'))
+
+ const s = shape(ms)
+ expect(s.at(-1)).toBe('user:[Request interrupted by user for tool use]')
+ expect(s.at(-2)).toMatch(/^assistant:tool\(Bash\|The user doesn't want to proceed/)
+ })
+
+ it('a rejection with no interrupt after it keeps its own text', () => {
+ const all = lines('esc_tool_call')
+ const withoutMarker = all.filter((l) => !l.includes('[Request interrupted'))
+
+ const ms = parseChatMessages(withoutMarker, { rich: true })
+
+ expect(shape(ms).at(-1)).toMatch(/^assistant:tool\(Bash\|The user doesn't want to proceed/)
+ })
+
+ it('a user who types the marker text as a plain prompt is still the user', () => {
+ const typed = JSON.stringify({ type: 'user', message: { role: 'user', content: '[Request interrupted by user]' } })
+
+ const ms = parseChatMessages([typed], { rich: true })
+
+ expect(shape(ms)).toEqual(['user:[Request interrupted by user]'])
+ })
+})
diff --git a/src/core/transcript-reader.ts b/src/core/transcript-reader.ts
index acd0087b5..8bb5a1cb5 100644
--- a/src/core/transcript-reader.ts
+++ b/src/core/transcript-reader.ts
@@ -10,6 +10,7 @@ import { linkedClaudeConfigDirFor } from './claude-config-dir'
import { platform } from './platform'
import { capText, toolBody } from './chat-tool-body'
import { isRecord } from '../shared/is-record'
+import { CLAUDE_TOOL_INTERRUPT_MARKER, claudeInterruptMarkerOf } from '../shared/agents/claude-interrupt'
import { ASK_USER_QUESTION_TOOL, readQuestions } from '../shared/agents/permission-answer'
import { BASH_COMMAND_TOOL, CHAT_TOOL_ARG_MAX, COMMAND_OUTPUT_TOOL } from '../shared/chat-command'
import {
@@ -349,6 +350,17 @@ export function classifySystemRecord(
return null
}
+/** What a tool call cancelled by an interrupt shows as its result (`ChatParseOptions.rich`). */
+export const INTERRUPTED_TOOL_RESULT = 'Interrupted'
+
+/** The result Claude Code writes for a tool call the user cancelled or refused. MEASURED on 2.1.285
+ * (`__fixtures__/claude/interrupt-capture.json`): an `is_error` tool_result starting with this. */
+const TOOL_REJECTION_PREFIX = "The user doesn't want to proceed with this tool use."
+
+function isToolRejection(c: { is_error?: unknown; content?: unknown }): boolean {
+ return c.is_error === true && summarizeResult(c.content).startsWith(TOOL_REJECTION_PREFIX)
+}
+
/** A system record's tool part (`result` only when non-empty). */
function systemPart(r: SystemRecord): Extract<ChatPart, { kind: 'tool' }> {
const part: Extract<ChatPart, { kind: 'tool' }> = { kind: 'tool', name: r.name, arg: r.arg }
@@ -612,6 +624,9 @@ function parseChatRecords(
// The stamp of the newest `user` record so far, hidden meta lines included: when the request a
// thinking record answers was made, so its `ms` (see the type). Read only on the opt-in branch.
let lastUserAt: number | undefined
+ // The tool part the LAST user/assistant record rejected (Claude's canned "doesn't want to proceed"
+ // result), for an interrupt marker right after it. Read only on the opt-in branch.
+ let rejectedTool: Extract<ChatPart, { kind: 'tool' }> | null = null
const push = (m: ChatMessage, offset: number): void => {
awaitingOutput = null
// `at` rides BOTH paths (additive): the time the line was written, for the thread's relative
@@ -654,6 +669,17 @@ function parseChatRecords(
continue
}
if (opts?.rich && o.type === 'user' && o.isCompactSummary === true) continue
+ // Opt-in (see `ChatParseOptions.rich`): an interrupt marker is Claude's, not the user's words.
+ // A tool call it cancelled was answered just before with a canned rejection ("The user doesn't
+ // want to proceed with this tool use…"), which reads as the tool's output; it says Interrupted.
+ const interrupt = opts?.rich && o.type === 'user' ? claudeInterruptMarkerOf(content) : null
+ if (interrupt !== null) {
+ if (interrupt === CLAUDE_TOOL_INTERRUPT_MARKER && rejectedTool) rejectedTool.result = INTERRUPTED_TOOL_RESULT
+ rejectedTool = null
+ push({ role: 'assistant', parts: [{ kind: 'interrupt' }] }, offset)
+ continue
+ }
+ if (o.type === 'user' || o.type === 'assistant') rejectedTool = null
if (o.type === 'assistant' && Array.isArray(content)) {
const parts: ChatPart[] = []
for (const c of content as Array<{
@@ -707,6 +733,7 @@ function parseChatRecords(
tool_use_id?: string
content?: unknown
source?: unknown
+ is_error?: unknown
}>) {
if (!c || typeof c !== 'object') continue
// A non-string `text` is passed through as before; only a string is a paste to expand.
@@ -720,6 +747,7 @@ function parseChatRecords(
const s = summarizeResult(c.content)
if (tool) {
if (s) tool.result = s
+ if (opts?.rich && isToolRejection(c)) rejectedTool = tool
} else if (paged && s && typeof c.tool_use_id === 'string' && c.tool_use_id) {
// Its tool_use is in an OLDER window (claude writes the call before its result, so it
// can never be in a newer one). Carried so the renderer can attach it later.
diff --git a/src/preload/index.ts b/src/preload/index.ts
index be706b38f..af1e56ebf 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -115,6 +115,8 @@ const api: NodeTerminalApi = {
ipcRenderer.invoke(IPC.ptySendChatPrompt, persistKey, text, agentId),
sendToEmptyPrompt: (persistKey, text, agentId) =>
ipcRenderer.invoke(IPC.ptySendToEmptyPrompt, persistKey, text, agentId),
+ interruptChat: (persistKey, agentId, sentText) =>
+ ipcRenderer.invoke(IPC.ptyInterruptChat, persistKey, agentId, sentText),
tmuxStatus: () => ipcRenderer.invoke(IPC.ptyTmuxStatus),
paneCommand: (persistKey, opts) => ipcRenderer.invoke(IPC.ptyPaneCommand, persistKey, opts),
paneCwd: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneCwd, persistKey),
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index a90941bd4..71bb880f6 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -28,7 +28,7 @@ import {
type RpcMessage
} from '../../shared/rpc'
import { IPC } from '../../shared/ipc'
-import type { ChatPromptResult, EmptyPromptResult } from '../../shared/text-delivery'
+import type { ChatInterruptResult, ChatPromptResult, EmptyPromptResult } from '../../shared/text-delivery'
import type { GitHubControlApi, GitHubIssuesApi } from '../../shared/github-issues'
import {
UNKNOWN_CLAUDE_CLI_CAPS,
@@ -303,6 +303,11 @@ export function buildRealApi(
client.request(IPC.ptySendChatPrompt, persistKey, text, agentId) as Promise<ChatPromptResult>,
sendToEmptyPrompt: (persistKey, text, agentId) =>
client.request(IPC.ptySendToEmptyPrompt, persistKey, text, agentId) as Promise<EmptyPromptResult>,
+ // Real: core registers it. A failed request (a relay host refusing a non-editor) is `failed`.
+ interruptChat: (persistKey, agentId, sentText) =>
+ client
+ .request(IPC.ptyInterruptChat, persistKey, agentId, sentText)
+ .catch(() => ({ sent: false, reason: 'failed' })) as Promise<ChatInterruptResult>,
// A failed read is unknown, never evidence that persistence is available.
tmuxStatus: () =>
client
diff --git a/src/renderer/lib/chatEscInterrupt.test.ts b/src/renderer/lib/chatEscInterrupt.test.ts
new file mode 100644
index 000000000..fe57af288
--- /dev/null
+++ b/src/renderer/lib/chatEscInterrupt.test.ts
@@ -0,0 +1,81 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from 'vitest'
+import { chatEscInterrupts, chatInterruptRefusalText, type EscInterruptContext } from './chatEscInterrupt'
+
+const ESC = { key: 'Escape', altKey: false, ctrlKey: false, metaKey: false, shiftKey: false, isComposing: false }
+const WORKING: EscInterruptContext = { agentId: 'claude', state: 'working', draft: '', readOnly: false }
+
+function composer(expanded = false): HTMLTextAreaElement {
+ const ta = document.createElement('textarea')
+ ta.className = 'term-chat__input term-chat__composer-input'
+ if (expanded) ta.setAttribute('aria-expanded', 'true')
+ return ta
+}
+
+describe('chatEscInterrupts', () => {
+ it('interrupts a working claude from an empty composer', () => {
+ const result = chatEscInterrupts(ESC, composer(), WORKING)
+
+ expect(result).toBe(true)
+ })
+
+ it('interrupts from anywhere else in the panel that does not use Esc itself', () => {
+ const result = chatEscInterrupts(ESC, document.createElement('div'), WORKING)
+
+ expect(result).toBe(true)
+ })
+
+ it.each(['done', 'waiting', 'blocked', undefined])('does nothing while the state is %s', (state) => {
+ const result = chatEscInterrupts(ESC, composer(), { ...WORKING, state })
+
+ expect(result).toBe(false)
+ })
+
+ it('does nothing with a draft in the composer', () => {
+ const result = chatEscInterrupts(ESC, composer(), { ...WORKING, draft: 'half a thought' })
+
+ expect(result).toBe(false)
+ })
+
+ it('treats a whitespace-only draft as empty', () => {
+ const result = chatEscInterrupts(ESC, composer(), { ...WORKING, draft: ' \n' })
+
+ expect(result).toBe(true)
+ })
+
+ it('does nothing for an agent whose interrupt is not measured', () => {
+ for (const agentId of ['codex', 'gemini', 'grok', 'custom:abc']) {
+ expect(chatEscInterrupts(ESC, composer(), { ...WORKING, agentId })).toBe(false)
+ }
+ })
+
+ it('does nothing in a read-only view', () => {
+ const result = chatEscInterrupts(ESC, composer(), { ...WORKING, readOnly: true })
+
+ expect(result).toBe(false)
+ })
+
+ it('leaves Esc to a control that uses it', () => {
+ const other = document.createElement('input')
+ const select = document.createElement('select')
+
+ expect(chatEscInterrupts(ESC, other, WORKING)).toBe(false)
+ expect(chatEscInterrupts(ESC, select, WORKING)).toBe(false)
+ expect(chatEscInterrupts(ESC, composer(true), WORKING)).toBe(false)
+ })
+
+ it('ignores a modified Esc, an IME composition and other keys', () => {
+ expect(chatEscInterrupts({ ...ESC, shiftKey: true }, composer(), WORKING)).toBe(false)
+ expect(chatEscInterrupts({ ...ESC, metaKey: true }, composer(), WORKING)).toBe(false)
+ expect(chatEscInterrupts({ ...ESC, isComposing: true }, composer(), WORKING)).toBe(false)
+ expect(chatEscInterrupts({ ...ESC, key: 'Enter' }, composer(), WORKING)).toBe(false)
+ })
+})
+
+describe('chatInterruptRefusalText', () => {
+ it('points at the terminal when a dialog is up', () => {
+ const text = chatInterruptRefusalText('dialog', 'Claude')
+
+ expect(text).toMatch(/Claude is showing a prompt in the terminal/)
+ })
+})
diff --git a/src/renderer/lib/chatEscInterrupt.ts b/src/renderer/lib/chatEscInterrupt.ts
new file mode 100644
index 000000000..e2a0a9100
--- /dev/null
+++ b/src/renderer/lib/chatEscInterrupt.ts
@@ -0,0 +1,76 @@
+/**
+ * Esc in the ⌘M chat view interrupts the agent's running turn, as Esc in the terminal does, so the
+ * user does not have to flip back to the terminal to stop it.
+ *
+ * Only while the agent is WORKING and the composer is EMPTY:
+ * - idle, two Escs open Claude Code's rewind picker, which fires no hook and which this view cannot
+ * see; the next message would land in it;
+ * - blocked or waiting, Esc would cancel the permission prompt or question on screen (the answer
+ * cards here handle those);
+ * - with a draft in the composer, Esc reads as "never mind what I'm typing", not "stop the agent".
+ *
+ * Only for an agent whose interrupt is measured (`interruptsFromChat`, claude). A control that uses
+ * Esc itself keeps it: any other text field (the plan's "Revise…" box, a question's "Other" input), a
+ * `<select>`, editable content, and the composer while its `/` / `@` menu is open.
+ */
+import { interruptsFromChat } from '@shared/agents/config'
+import type { ChatInterruptRefusal } from '@shared/text-delivery'
+
+/** How Claude Code's TUI shows an interrupted turn (MEASURED on 2.1.318 after an Esc mid-reply; the
+ * same line hangs off a cancelled tool call), and so how the thread draws an `interrupt` part. */
+export const CLAUDE_INTERRUPT_LINE = 'Interrupted · What should Claude do instead?'
+
+/** The composer's textarea class (ChatComposer.tsx). */
+const COMPOSER_CLASS = 'term-chat__composer-input'
+
+export interface EscKeyEvent {
+ key: string
+ altKey: boolean
+ ctrlKey: boolean
+ metaKey: boolean
+ shiftKey: boolean
+ isComposing: boolean
+}
+
+export interface EscInterruptContext {
+ agentId: string
+ /** The agent's state, read from the store at keypress time. */
+ state: string | undefined
+ /** The composer's draft. */
+ draft: string
+ readOnly: boolean
+}
+
+export function chatEscInterrupts(e: EscKeyEvent, target: Element | null, ctx: EscInterruptContext): boolean {
+ if (e.key !== 'Escape' || e.isComposing) return false
+ if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) return false
+ if (ctx.readOnly || !interruptsFromChat(ctx.agentId)) return false
+ if (ctx.state !== 'working') return false
+ if (ctx.draft.trim() !== '') return false
+ return target === null || !ownsEscape(target)
+}
+
+function ownsEscape(target: Element): boolean {
+ if (target instanceof HTMLElement && target.isContentEditable) return true
+ const tag = target.tagName
+ if (tag === 'SELECT') return true
+ if (tag !== 'TEXTAREA' && tag !== 'INPUT') return false
+ if (!target.classList.contains(COMPOSER_CLASS)) return true
+ return target.getAttribute('aria-expanded') === 'true'
+}
+
+/** What the user is told when the Esc did not reach the agent. */
+export function chatInterruptRefusalText(reason: ChatInterruptRefusal, agentLabel: string): string {
+ switch (reason) {
+ case 'dialog':
+ return `${agentLabel} is showing a prompt in the terminal; Esc was not sent. Answer it there.`
+ case 'unsupported':
+ case 'unsupported-backend':
+ return `Esc can't be sent to ${agentLabel} from here. Switch to the terminal to interrupt it.`
+ case 'not-connected':
+ case 'no-ssh':
+ return `Couldn't reach ${agentLabel}'s terminal to interrupt it.`
+ case 'failed':
+ return `Couldn't send Esc to ${agentLabel}. Switch to the terminal to interrupt it.`
+ }
+}
diff --git a/src/renderer/lib/chatPaging.test.ts b/src/renderer/lib/chatPaging.test.ts
index aa912d5ad..b238655dc 100644
--- a/src/renderer/lib/chatPaging.test.ts
+++ b/src/renderer/lib/chatPaging.test.ts
@@ -26,7 +26,7 @@ const page = (
const texts = (t: ChatThread): string[] =>
t.messages.map((m) => {
const p = m.parts[0]
- return p.kind === 'tool' ? `tool:${p.id}:${p.result ?? '-'}` : p.kind === 'image' ? 'image' : p.text
+ return p.kind === 'tool' ? `tool:${p.id}:${p.result ?? '-'}` : p.kind === 'image' ? 'image' : p.kind === 'interrupt' ? 'interrupt' : p.text
})
describe('attachCarried', () => {
diff --git a/src/renderer/nodes/ChatPanel.escInterrupt.test.tsx b/src/renderer/nodes/ChatPanel.escInterrupt.test.tsx
new file mode 100644
index 000000000..17ce78a47
--- /dev/null
+++ b/src/renderer/nodes/ChatPanel.escInterrupt.test.tsx
@@ -0,0 +1,155 @@
+// @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'
+import type { ChatInterruptResult } from '@shared/text-delivery'
+
+/**
+ * Esc in the ⌘M chat view interrupts a working agent (lib/chatEscInterrupt.ts holds the rule). This
+ * file pins the GLUE: the keypress reaches core with the panel's last send, a prompt core took back
+ * out of the agent's input box lands in the composer, and a refusal is said out loud.
+ */
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+const { interruptChat, readTranscript, sendChatPrompt, session } = vi.hoisted(() => {
+ const readTranscript = vi.fn(async (): Promise<{ messages: unknown[]; found: boolean }> => ({ messages: [], found: true }))
+ const interruptChat = vi.fn(
+ async (_id: string, _agent: string, _sent?: string): Promise<ChatInterruptResult> => ({ sent: true, restored: null })
+ )
+ const sendChatPrompt = vi.fn(async (_id: string, _text: string, _agent: string) => true as const)
+ const session = {
+ api: {
+ chat: { readTranscript },
+ pty: { interruptChat, sendChatPrompt, paneOwner: async () => null }
+ }
+ }
+ return { interruptChat, readTranscript, sendChatPrompt, session }
+})
+vi.mock('../session/session', () => ({ useSession: () => session }))
+
+import { ChatPanel } from './ChatPanel'
+
+const NODE = 'n-chat-esc'
+let host: HTMLDivElement
+let root: Root
+
+function setAgentState(state: 'working' | 'done'): 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 press = (ta: HTMLTextAreaElement, key: string): void => {
+ ta.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }))
+}
+
+beforeEach(() => {
+ interruptChat.mockClear()
+ sendChatPrompt.mockClear()
+ 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 }
+ })
+})
+
+describe('ChatPanel Esc interrupt', () => {
+ it('interrupts a working agent from an empty composer', async () => {
+ setAgentState('working')
+ const ta = await mount()
+
+ await act(async () => press(ta, 'Escape'))
+
+ expect(interruptChat).toHaveBeenCalledWith(NODE, 'claude', undefined)
+ })
+
+ it('does nothing when the turn is done', async () => {
+ setAgentState('done')
+ const ta = await mount()
+
+ await act(async () => press(ta, 'Escape'))
+
+ expect(interruptChat).not.toHaveBeenCalled()
+ })
+
+ it('does nothing with a draft in the composer', async () => {
+ setAgentState('working')
+ const ta = await mount()
+ await act(async () => type(ta, 'half a thought'))
+
+ await act(async () => press(ta, 'Escape'))
+
+ expect(interruptChat).not.toHaveBeenCalled()
+ })
+
+ it('passes the last send, and puts a prompt core took back into the composer', async () => {
+ setAgentState('done')
+ const ta = await mount()
+ await act(async () => type(ta, 'Write a story'))
+ await act(async () => press(ta, 'Enter'))
+ expect(sendChatPrompt).toHaveBeenCalledWith(NODE, 'Write a story', 'claude')
+ expect(host.textContent).toContain('Write a story')
+ interruptChat.mockResolvedValueOnce({ sent: true, restored: 'Write a story' })
+ setAgentState('working')
+
+ await act(async () => press(ta, 'Escape'))
+
+ expect(interruptChat).toHaveBeenCalledWith(NODE, 'claude', 'Write a story')
+ expect(ta.value).toBe('Write a story')
+ })
+
+ it("draws an interrupt as Claude's own line, not as a user bubble", async () => {
+ setAgentState('done')
+ readTranscript.mockResolvedValueOnce({
+ messages: [
+ { role: 'user', parts: [{ kind: 'text', text: 'Write a story' }], key: 1 },
+ { role: 'assistant', parts: [{ kind: 'text', text: 'Once upon' }], key: 2 },
+ { role: 'assistant', parts: [{ kind: 'interrupt' }], key: 3 }
+ ],
+ found: true
+ })
+
+ await mount()
+
+ const line = host.querySelector('.term-chat__interrupt')
+ expect(line?.textContent).toBe('⎿Interrupted · What should Claude do instead?')
+ expect(line?.closest('.term-chat__bubble')).toBeNull()
+ })
+
+ it('says why when the Esc was refused', async () => {
+ setAgentState('working')
+ const ta = await mount()
+ const toasts: string[] = []
+ const onToast = (e: Event) => toasts.push((e as CustomEvent<{ message: string }>).detail.message)
+ window.addEventListener('nodeterm:toast', onToast)
+ interruptChat.mockResolvedValueOnce({ sent: false, reason: 'unsupported-backend' })
+
+ await act(async () => press(ta, 'Escape'))
+
+ window.removeEventListener('nodeterm:toast', onToast)
+ expect(toasts).toEqual([expect.stringMatching(/Esc can't be sent to Claude Code from here/)])
+ })
+})
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index f3b9628bb..f10effab0 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -2,7 +2,7 @@ import { TEXT_NOT_SUBMITTED, isChatPromptBlocked } from '@shared/text-delivery'
import { claudeScreenBlocksInput, readClaudeScreen } from '@shared/agents/claude-screen'
import { Fragment, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react'
import { renderMarkdown } from '../lib/markdown'
-import { useAgentStatus } from '../state/agentStatus'
+import { inferInterruptAfterSettle, useAgentStatus } from '../state/agentStatus'
import { useSession } from '../session/session'
import { chipFor } from '../lib/keybindingOverrides'
import {
@@ -65,6 +65,7 @@ import { ChatImage } from './ChatImage'
import { ChatToolDiff } from './ChatToolDiff'
import { FALLBACK_SESSION_NOTE, transcriptReadCwd } from '../lib/transcriptSession'
import { chatPageDirection, pageChatThread } from '../lib/chatPageKeys'
+import { CLAUDE_INTERRUPT_LINE, chatEscInterrupts, chatInterruptRefusalText } from '../lib/chatEscInterrupt'
// 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.
@@ -261,6 +262,8 @@ export function ChatPanel({
olderStateRef.current = olderState
const [input, setInput] = useState('')
const [readonly, setReadonly] = useState(false)
+ // The last prompt this panel sent, for taking it back out of the agent's input box after an Esc.
+ const lastSentRef = useRef<string | null>(null)
const [optimistic, setOptimistic] = useState(false)
const state = useAgentStatus((s) => s.byId[nodeId]?.state)
// The shell-owned-pane flags, each as its own primitive selector (an object selector would
@@ -836,15 +839,53 @@ export function ChatPanel({
// Page Up / Page Down page the thread from anywhere in the panel, the composer included
// (lib/chatPageKeys.ts). `contains`: a React portal's keydown bubbles here too.
- const onPageKey = (e: KeyboardEvent<HTMLDivElement>) => {
+ const onPanelKey = (e: KeyboardEvent<HTMLDivElement>) => {
const el = msgsRef.current
if (!el || e.defaultPrevented || !(e.target instanceof Element) || !e.currentTarget.contains(e.target)) return
+ if (
+ chatEscInterrupts({ ...e, isComposing: e.nativeEvent.isComposing }, e.target, {
+ agentId,
+ state: useAgentStatus.getState().byId[nodeId]?.state,
+ draft: input,
+ readOnly: readOnly === true || readonly
+ })
+ ) {
+ e.preventDefault()
+ void interrupt()
+ return
+ }
const direction = chatPageDirection(e, e.target)
if (direction === null) return
e.preventDefault()
pageChatThread(el, direction)
}
+ // Esc while the agent works (lib/chatEscInterrupt.ts). Core checks the screen for a dialog first
+ // and, when the Esc beat the reply's first token, takes the prompt Claude put back into its own
+ // input box out again: it goes into this composer instead, where the user can see and edit it.
+ const interrupt = async () => {
+ const r = await api.pty.interruptChat(nodeId, agentId, lastSentRef.current ?? undefined)
+ if (!r.sent) {
+ if (r.reason === 'dialog') {
+ const dialog = r.dialog ?? null
+ setScreenBlock({ kind: dialog === null ? 'no-prompt' : 'dialog', text: dialog, live: pollScreen })
+ }
+ const message = chatInterruptRefusalText(r.reason, chatAgentLabel(agentId, useSettings.getState().settings.customAgents))
+ window.dispatchEvent(new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message } }))
+ return
+ }
+ // An Esc before the first token writes no transcript marker and fires no hook, so the state would
+ // read working until the stale sweep. The same guess an Esc typed in the terminal makes: an
+ // interrupted `done` after a short settle, healed by the turn's next hook if the guess was wrong.
+ inferInterruptAfterSettle(nodeId)
+ const restored = r.restored
+ if (restored === null) return
+ lastSentRef.current = null
+ // The bubble for that send stays: Claude still writes the prompt to the transcript (as a branch it
+ // then drops from its context), so the next read would draw it again anyway.
+ setInput((cur) => (cur.trim() === '' ? restored : `${restored}\n${cur}`))
+ }
+
const scrollToLatest = () => {
const el = msgsRef.current
if (!el) return
@@ -900,6 +941,7 @@ export function ChatPanel({
// (`carryUnconfirmed`); the turn-end reload / ↻ reconcile from the transcript outright.
setScreenBlock(null)
justSentRef.current = true
+ lastSentRef.current = text
const sent: ChatMessage = { role: 'user', parts: [{ kind: 'text', text }] }
if (mode === 'queue') queuedRef.current.add(sent)
setThread((t) => ({ ...t, messages: [...t.messages, sent] }))
@@ -1023,6 +1065,13 @@ export function ChatPanel({
) : p.kind === 'image' ? (
// An image the user attached to the prompt (the opt-in `rich` read): a thumbnail, click to enlarge.
<ChatImage key={key} mediaType={p.mediaType} data={p.data} />
+ ) : p.kind === 'interrupt' ? (
+ // The user interrupted the turn (the opt-in `rich` read). Claude saves that as a user record,
+ // but the user did not type it: drawn as Claude's own TUI line, hanging off what came before.
+ <div key={key} className="term-chat__interrupt">
+ <span className="term-chat__interrupt-hook" aria-hidden="true">⎿</span>
+ {CLAUDE_INTERRUPT_LINE}
+ </div>
) : p.body && !staleTodo(p, i, latestTodo) ? (
// A plan / question / the latest todo list is the content itself, not plumbing: shown
// expanded, in full, flowing with the thread (no inner scroll box). The answer stays under it.
@@ -1083,7 +1132,7 @@ export function ChatPanel({
return (
// `data-chat-node-id`: which node's chat view this is — the mics that name only a node ask it
// (lib/chatComposerDictation.ts `dictationTargetForNode`) so a take never reaches the hidden pane.
- <div className="term-chat nodrag nowheel" data-chat-node-id={nodeId} onKeyDown={onPageKey}>
+ <div className="term-chat nodrag nowheel" data-chat-node-id={nodeId} onKeyDown={onPanelKey}>
<div className="term-chat__bar">
<span>{title ?? 'Chat'}</span>
<span className="term-chat__bar-end">
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 7651b9254..9addfd9d9 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -3688,6 +3688,20 @@ body,
font-size: 11px;
opacity: 0.85;
}
+/* An interrupted turn (an `interrupt` part): Claude's own TUI line, quiet and hanging off what came
+ before it, never a user bubble. */
+.term-chat__interrupt {
+ display: flex;
+ align-items: baseline;
+ gap: 6px;
+ margin-top: -2px;
+ padding-left: 4px;
+ font-size: 12px;
+ color: var(--muted);
+}
+.term-chat__interrupt-hook {
+ font-family: ui-monospace, monospace;
+}
/* An Edit / Write call (nodes/ChatToolDiff.tsx): the chip's summary ends in the `+N −M` counts, and
it opens to the line diff. The block is a one-column grid sized to its widest line (at least the
chip's width), so a line's tint spans the whole row even while the block is scrolled sideways;
diff --git a/src/shared/agents/claude-interrupt.ts b/src/shared/agents/claude-interrupt.ts
new file mode 100644
index 000000000..7246bf0ca
--- /dev/null
+++ b/src/shared/agents/claude-interrupt.ts
@@ -0,0 +1,25 @@
+/**
+ * The two texts Claude Code writes as a USER record when the user interrupts a turn (Esc, or
+ * Ctrl+C once). A CLOSED set: measured on 2.1.285 (`__fixtures__/claude/interrupt-capture.json`) —
+ * `[Request interrupted by user]` after streamed text, `… for tool use]` when a tool call or its
+ * permission dialog was cancelled. Any other wording is ignored, so a future CLI that words it
+ * differently degrades to what happened before this existed, never to a guess.
+ *
+ * Read by the context tail (an interrupt ends the turn: core/context-tail.ts) and by the ⌘M chat
+ * parser (drawn as Claude's own "Interrupted" line, not as a message the user typed).
+ */
+export const CLAUDE_INTERRUPT_MARKERS: ReadonlySet<string> = new Set([
+ '[Request interrupted by user]',
+ '[Request interrupted by user for tool use]'
+])
+
+/** The marker for an interrupt that cancelled a tool call (or its permission dialog). */
+export const CLAUDE_TOOL_INTERRUPT_MARKER = '[Request interrupted by user for tool use]'
+
+/** A record's `message.content` is exactly one interrupt marker. */
+export function claudeInterruptMarkerOf(content: unknown): string | null {
+ if (!Array.isArray(content) || content.length !== 1) return null
+ const part = content[0] as { type?: unknown; text?: unknown } | null
+ if (part?.type !== 'text' || typeof part.text !== 'string') return null
+ return CLAUDE_INTERRUPT_MARKERS.has(part.text) ? part.text : null
+}
diff --git a/src/shared/agents/config.capabilities.test.ts b/src/shared/agents/config.capabilities.test.ts
index 6e374ecb7..04a6b8e91 100644
--- a/src/shared/agents/config.capabilities.test.ts
+++ b/src/shared/agents/config.capabilities.test.ts
@@ -36,6 +36,8 @@ import {
typesChatInput,
readsScreenDialogs,
queuesInputWhileWorking,
+ interruptsFromChat,
+ CHAT_INTERRUPT_CAPABLE,
LOCAL_ONLY_HOOK_AGENTS,
reportsSessionEnd,
resumeCommandWith,
@@ -607,6 +609,14 @@ describe('readsScreenDialogs — whose own dialogs the chat view can see on scre
})
})
+describe('interruptsFromChat — who Esc in the chat view may interrupt', () => {
+ it('is claude only, and stays within the screen readers: core reads the screen before the Esc', () => {
+ expect(interruptsFromChat('claude')).toBe(true)
+ for (const id of BUILTIN_AGENT_IDS.filter((a) => a !== 'claude')) expect(interruptsFromChat(id)).toBe(false)
+ for (const id of CHAT_INTERRUPT_CAPABLE) expect(readsScreenDialogs(id)).toBe(true)
+ })
+})
+
describe('queuesInputWhileWorking — who may be sent to mid-turn from the chat view', () => {
it('is claude only: every other CLI\'s mid-turn input is unmeasured and may answer what is on screen', () => {
expect(queuesInputWhileWorking('claude')).toBe(true)
diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.ts
index 419a90ee2..a3f68cdfa 100644
--- a/src/shared/agents/config.ts
+++ b/src/shared/agents/config.ts
@@ -434,6 +434,12 @@ export const SCREEN_DIALOG_READABLE = ['claude'] as const
// delivered at the next tool boundary of the SAME turn (a `queued_command` transcript attachment, not
// a new user turn). Every other chat-capable agent is unmeasured and keeps "wait for the reply".
export const INPUT_QUEUE_CAPABLE = ['claude'] as const
+// Agents the ⌘M chat view may send a lone Esc to while a turn is running, to interrupt it as Esc in
+// the terminal would. MEASURED for claude (2.1.318, 2026-11-04): mid-reply it prints "Interrupted ·
+// What should Claude do instead?"; text in its own input box stays; a queued message is sent as the
+// next turn; an Esc before the first token puts the prompt back into its input box. Must stay within
+// SCREEN_DIALOG_READABLE: core reads the screen first, because Esc on a dialog would cancel it.
+export const CHAT_INTERRUPT_CAPABLE = ['claude'] as const
// Agents whose native transcript we can read + render for cross-agent transfer.
export const TRANSFER_SOURCE_CAPABLE = [
'claude',
@@ -723,6 +729,7 @@ export const chatReadsLocalOnly = (id: AgentId): boolean => includes(CHAT_LOCAL_
export const typesChatInput = (id: AgentId): boolean => includes(TYPED_INPUT_CAPABLE, id)
export const readsScreenDialogs = (id: AgentId): boolean => includes(SCREEN_DIALOG_READABLE, id)
export const queuesInputWhileWorking = (id: AgentId): boolean => includes(INPUT_QUEUE_CAPABLE, id)
+export const interruptsFromChat = (id: AgentId): boolean => includes(CHAT_INTERRUPT_CAPABLE, 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.ts
index e0828a3e2..fe370bdc7 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -30,6 +30,7 @@ export const IPC = {
ptySendText: 'pty:send-text',
ptySendChatPrompt: 'pty:send-chat-prompt',
ptySendToEmptyPrompt: 'pty:send-to-empty-prompt',
+ ptyInterruptChat: 'pty:interrupt-chat',
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.ts
index 9504b689a..1335296e7 100644
--- a/src/shared/text-delivery.ts
+++ b/src/shared/text-delivery.ts
@@ -27,3 +27,21 @@ export const isChatPromptBlocked = (r: ChatPromptResult): r is ChatPromptBlocked
*/
export type EmptyPromptRefusal = 'unsupported' | 'draft' | 'no-prompt' | 'unknown' | 'not-submitted' | 'failed'
export type EmptyPromptResult = { sent: true } | { sent: false; reason: EmptyPromptRefusal }
+
+/**
+ * Why Esc from the ⌘M chat view (`pty.interruptChat`) did not reach the agent. Every refusal is decided
+ * before the Esc is written.
+ * - `unsupported` — not an agent whose interrupt and screen we have measured (claude only).
+ * - `dialog` — the agent's own dialog owns the keyboard (Esc would cancel it), or no input box is on
+ * screen. `dialog` carries its text when one was recognized.
+ * - the rest are `sendPaneKeys`'s: the pane could not be reached or typed into.
+ */
+export type ChatInterruptRefusal = 'unsupported' | 'dialog' | 'not-connected' | 'unsupported-backend' | 'no-ssh' | 'failed'
+/**
+ * `restored` is the prompt Claude put back into its own input box when the Esc landed before the
+ * reply started, taken back out of it (the box is cleared) so the chat view can put it in its own
+ * composer. null when nothing was put back, or when it could not be taken out cleanly.
+ */
+export type ChatInterruptResult =
+ | { sent: true; restored: string | null }
+ | { sent: false; reason: ChatInterruptRefusal; dialog?: string | null }
diff --git a/src/shared/types.ts b/src/shared/types.ts
index f74f15a02..b2ca9e1b0 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1,4 +1,4 @@
-import type { ChatPromptResult, EmptyPromptResult, TextDeliveryResult } from './text-delivery'
+import type { ChatInterruptResult, ChatPromptResult, EmptyPromptResult, TextDeliveryResult } from './text-delivery'
import type { PushWebhookMinted, PushWebhookResult, PushWebhookTokenInfo } from './push-webhook'
import type { IdentitySeedEntry } from './agent-identity-seed'
import type { AgentStatusSnapshotEntry } from './agent-status-snapshot'
@@ -1423,6 +1423,11 @@ export interface PtyApi {
* (issue #1144 — the app's own link notes). Refused, with the reason, before anything is written
* when the composer holds a draft, a dialog owns the keyboard, or emptiness cannot be proven. */
sendToEmptyPrompt(persistKey: string, text: string, agentId: string): Promise<EmptyPromptResult>
+ /** Esc from the ⌘M chat view: interrupt a running turn, for an agent whose interrupt is measured
+ * (claude). Refused before writing when the agent's own dialog owns the keyboard. `sentText` (the
+ * chat view's last send) lets core take it back out of the agent's input box when the Esc landed
+ * before the reply started; it comes back as `restored`. Never rejects on the desktop. */
+ interruptChat(persistKey: string, agentId: string, sentText?: string): Promise<ChatInterruptResult>
/** 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>
@@ -3627,6 +3632,15 @@ export type ChatPart =
mediaType: string
data: string
}
+ | {
+ /**
+ * The user interrupted the turn here (Esc, or Ctrl+C once): one of Claude Code's fixed marker
+ * records (`CLAUDE_INTERRUPT_MARKERS`), which it saves as a USER record but which the user did
+ * not type. Present only on the opt-in `rich` read; without it the marker stays a user text
+ * part, as before. The renderer draws Claude's own TUI line for it.
+ */
+ kind: 'interrupt'
+ }
| {
kind: 'tool'
name: string