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
feat(chat): carry a half-typed draft across a ⌘M flip
Paul Robertsonf63293424d5b
diff --git a/CLAUDE.md b/CLAUDE.mdindex 4c77023a5..9c98913bc 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -4601,6 +4601,16 @@ command-bearing opens; this does not add a human-confirm dialog or change mobiledebounced, flushed on pagehide, and merge only this window's changes into the stored map (twoServer Edition tabs); bounded by age (30 days), count (50) and size (32,000 chars stays in memoryonly). Pruned by age, not node existence: a closed project still holds its nodes.+ **A draft carries across the user's own ⌘M flip** (`lib/chatDraftCarry.ts`, claude only; core+ `putChatDraft` / `takeChatDraft`). It MOVES, never copies, so it is never sent twice: chat → terminal+ types it unsent (`sendTyped`, `submit: false`) into an EMPTY input box only; terminal → chat takes+ only what `readClaudeDraftLine` can read back exactly (one row, the `❯` prompt, no `[Pasted text…]`+ placeholder — MEASURED on 2.1.319: a wrap and an M-Enter newline draw the same, and the wrap drops+ the space at the break), clears it with Ctrl-E Ctrl-U (Ctrl-U alone keeps what is right of a moved+ cursor), and hands it over only once the box reads empty. Anything else stays put and is named+ (a note under the chat box, or a toast). Only the chord and the header toggle carry; the composer's+ own flips (`onShowTerminal`: a `/model` label, an interactive built-in) never do, a picker having+ just opened there (`chat-draft-carry-wiring.test.ts`).Fix-round rules (same day): the composer is its OWN component (`nodes/ChatComposer.tsx`) so thethread and the composer restyle independently. A label click is an explicit "go to theterminal", so the flip FOCUSES the xterm whatever its entry state wasdiff --git a/src/core/pty-manager.chat-draft.test.ts b/src/core/pty-manager.chat-draft.test.tsnew file mode 100644index 000000000..e6a35d8a0--- /dev/null+++ b/src/core/pty-manager.chat-draft.test.ts@@ -0,0 +1,170 @@+// `PtyManager.putChatDraft` / `takeChatDraft` — carrying a half-typed draft between the ⌘M chat+// composer and Claude's own input box on a flip. The draft MOVES, so the rules are about never+// leaving it in both places and never losing it: type only into an empty box, take only what can be+// read back exactly, and hand a taken draft over only once the box reads empty. The screen reader is+// tested in shared/agents/claude-screen.draft-line.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'+import capture from '../shared/agents/__fixtures__/claude/draft-line-capture.json'++vi.mock('node-pty', () => ({ spawn: () => ({}) }))++const NODE = 'node-1'+const S = capture.screens as Record<string, string>+const DIALOG = S.empty.replace(/\n[^\n]*auto mode on[^\n]*/, '\n Enter to confirm · Esc to cancel')++type Internals = {+ sendTyped: (k: string, t: string, a: string, o?: unknown) => Promise<unknown>+}++async function manager(screens: string[], opts: { typed?: unknown; keysOk?: boolean } = {}) {+ const { PtyManager } = await import('./pty-manager')+ const mgr = new PtyManager()+ const queue = [...screens]+ // Each capture takes the next screen; the last one repeats.+ const snapshot = vi+ .spyOn(mgr, 'captureSnapshot')+ .mockImplementation(async () => (queue.length > 1 ? queue.shift()! : queue[0]))+ const typed = vi.spyOn(mgr as unknown as Internals, 'sendTyped').mockResolvedValue('typed' in opts ? opts.typed : true)+ const keys = vi+ .spyOn(mgr, 'sendPaneKeys')+ .mockResolvedValue(opts.keysOk === false ? { ok: false, reason: 'failed' } : { ok: true })+ return { mgr, snapshot, typed, keys }+}++beforeEach(() => {+ vi.resetModules()+ initPlatform(fakePlatform())+})+afterEach(() => {+ vi.useRealTimers()+ resetPlatformForTests()+})++describe('PtyManager.putChatDraft (chat → terminal)', () => {+ it('types the draft into an empty box, without the Enter', async () => {+ const { mgr, typed } = await manager([S.empty])++ const result = await mgr.putChatDraft(NODE, 'claude', 'line one\nline two')++ expect(result).toEqual({ put: true })+ expect(typed).toHaveBeenCalledWith(NODE, 'line one\nline two', 'claude', { submit: false })+ })++ it('does not merge into a draft the terminal already has', async () => {+ const { mgr, typed } = await manager([S.line])++ const result = await mgr.putChatDraft(NODE, 'claude', 'from chat')++ expect(result).toEqual({ put: false, reason: 'has-draft' })+ expect(typed).not.toHaveBeenCalled()+ })++ it.each([+ ['a dialog', DIALOG],+ ['an unreadable screen', '']+ ])('types nothing over %s', async (_name, screen) => {+ const { mgr, typed } = await manager([screen])++ const result = await mgr.putChatDraft(NODE, 'claude', 'from chat')++ expect(result).toEqual({ put: false, reason: 'unreadable' })+ expect(typed).not.toHaveBeenCalled()+ })++ it('reports typing it could not confirm, a failed transport and a backend with no typed path', async () => {+ const a = await manager([S.empty], { typed: 'pasted-not-submitted' })+ const b = await manager([S.empty], { typed: false })+ const c = await manager([S.empty], { typed: null })++ const results = [+ await a.mgr.putChatDraft(NODE, 'claude', 'x'),+ await b.mgr.putChatDraft(NODE, 'claude', 'x'),+ await c.mgr.putChatDraft(NODE, 'claude', 'x')+ ]++ expect(results).toEqual([+ { put: false, reason: 'unconfirmed' },+ { put: false, reason: 'failed' },+ { put: false, reason: 'unsupported' }+ ])+ })++ it('refuses an agent whose composer is not measured, without reading the screen', async () => {+ const { mgr, snapshot, typed } = await manager([S.empty])++ const result = await mgr.putChatDraft(NODE, 'codex', 'x')++ expect(result).toEqual({ put: false, reason: 'unsupported' })+ expect(snapshot).not.toHaveBeenCalled()+ expect(typed).not.toHaveBeenCalled()+ })+})++describe('PtyManager.takeChatDraft (terminal → chat)', () => {+ it('takes a one-row draft, clearing the whole row first', async () => {+ const { mgr, keys } = await manager([S.line, S.empty])++ const result = await mgr.takeChatDraft(NODE, 'claude')++ expect(result).toEqual({ taken: true, text: 'fix the login bug, then run tests' })+ // Ctrl-E first: Ctrl-U alone leaves whatever is right of the cursor.+ expect(keys).toHaveBeenCalledWith(NODE, '\x05\x15')+ })++ it.each([+ ['wrapped', 'multi-line'],+ ['multiline', 'multi-line'],+ ['pasted', 'placeholder'],+ ['shellmode', 'not-prompt']+ ])('leaves a %s draft where it is', async (name, reason) => {+ const { mgr, keys } = await manager([S[name]])++ const result = await mgr.takeChatDraft(NODE, 'claude')++ expect(result).toEqual({ taken: false, reason })+ expect(keys).not.toHaveBeenCalled()+ })++ it('has nothing to take from an empty box or an unreadable screen', async () => {+ const a = await manager([S.empty])+ const b = await manager([''])++ const results = [await a.mgr.takeChatDraft(NODE, 'claude'), await b.mgr.takeChatDraft(NODE, 'claude')]++ expect(results).toEqual([+ { taken: false, reason: 'empty' },+ { taken: false, reason: 'unreadable' }+ ])+ expect(a.keys).not.toHaveBeenCalled()+ expect(b.keys).not.toHaveBeenCalled()+ })++ it('hands nothing over when the box does not read empty after clearing', async () => {+ vi.useFakeTimers()+ const { mgr } = await manager([S.line])++ const pending = mgr.takeChatDraft(NODE, 'claude')+ await vi.advanceTimersByTimeAsync(5000)++ expect(await pending).toEqual({ taken: false, reason: 'not-cleared' })+ })++ it('hands nothing over when the clearing keys could not be sent', async () => {+ const { mgr } = await manager([S.line], { keysOk: false })++ const result = await mgr.takeChatDraft(NODE, 'claude')++ expect(result).toEqual({ taken: false, reason: 'failed' })+ })++ it('refuses an agent whose composer is not measured, without reading the screen', async () => {+ const { mgr, snapshot } = await manager([S.line])++ const result = await mgr.takeChatDraft(NODE, 'codex')++ expect(result).toEqual({ taken: false, reason: 'unsupported' })+ expect(snapshot).not.toHaveBeenCalled()+ })+})diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 8d197ef6e..71d8d1504 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -1,4 +1,6 @@import type {+ ChatDraftPutResult,+ ChatDraftTakeResult,ChatInterruptResult,ChatPromptBlocked,ChatPromptResult,@@ -9,6 +11,7 @@ import {claudeScreenBlocksInput,readClaudeComposer,readClaudeDraft,+ readClaudeDraftLine,readClaudeScreen,readClaudeSuggestion,type ChatScreenRead@@ -2316,6 +2319,15 @@ export class PtyManager {typeof sentText === 'string' ? sentText : undefined))+ platform().handle(IPC.ptyPutChatDraft, (persistKey: string, agentId: unknown, text: unknown) =>+ // `agentId` only picks the capability (a non-string picks none: `unsupported`).+ typeof text === 'string'+ ? this.putChatDraft(persistKey, typeof agentId === 'string' ? agentId : '', text)+ : Promise.resolve({ put: false, reason: 'failed' } as const)+ )+ platform().handle(IPC.ptyTakeChatDraft, (persistKey: string, agentId: unknown) =>+ this.takeChatDraft(persistKey, typeof agentId === 'string' ? agentId : '')+ )platform().handle(IPC.ptyTmuxStatus, () => this.tmuxStatus())platform().handle(IPC.ptyPaneCommand, (persistKey: string, opts?: { resolveUnmounted?: boolean }) =>this.paneCommand(persistKey, opts?.resolveUnmounted === true ? { resolveUnmounted: true } : undefined)@@ -6693,8 +6705,17 @@ export class PtyManager {* be stale by the time the Enter goes: for an agent whose screen we can read, the screen is* checked again right before the Enter, and a dialog that opened meanwhile gets no Enter — the* text stays in the composer and the caller hears `pasted-not-submitted`.+ *+ * `submit: false` (carrying a chat draft over, `putChatDraft`) types and confirms the text arrived,+ * and sends no Enter: `true` then means "in the composer, unsent".*/- private async sendTyped(persistKey: string, text: string, agentId: AgentId): Promise<TextDeliveryResult | null> {+ private async sendTyped(+ persistKey: string,+ text: string,+ agentId: AgentId,+ opts?: { submit?: boolean }+ ): Promise<TextDeliveryResult | null> {+ const submitting = opts?.submit !== falseconst target = sessionName(persistKey)const live = this.liveSessionForPersistKey(persistKey)if (live?.nativeWindowsPane || this.isZellij(persistKey, live)) return null@@ -6738,11 +6759,11 @@ export class PtyManager {type: (stdin) => ok(() => type(stdin)),// An empty capture is not evidence of a dialog (the `sendChatPrompt` rule).canSubmit: async () => {- if (!readsScreenDialogs(agentId)) return true+ if (!submitting || !readsScreenDialogs(agentId)) return trueconst screen = await this.captureSession(persistKey)return screen === '' || screenGate(screen) === null},- submit: () => ok(submit)+ submit: submitting ? () => ok(submit) : async () => true})} catch {return 'pasted-not-submitted'@@ -6929,6 +6950,59 @@ export class PtyManager {return (await until((d) => d === '', INTERRUPT_RESTORE_WAIT_MS)) === ''}+ /**+ * ⌘M chat view → terminal: type the chat composer's draft into the agent's own input box, WITHOUT+ * submitting it, so the user can carry on in the terminal. Only into an EMPTY box (two drafts are+ * never merged) and only when no dialog owns the keyboard; typed (`sendTyped`, `submit: false`), so+ * a multi-line draft keeps its lines (M-Enter) and is not recorded as a paste. The caller empties+ * its own draft only on `put: true`. Runs inside `serializePaneWrite`. An empty capture is NOT+ * evidence of anything here: nothing is typed into a box we cannot see.+ */+ async putChatDraft(persistKey: string, agentId: string, text: string): Promise<ChatDraftPutResult> {+ if (!readsScreenDialogs(agentId) || !typesChatInput(agentId)) return { put: false, reason: 'unsupported' }+ if (text.trim() === '') return { put: false, reason: 'empty' }+ return this.serializePaneWrite(persistKey, async (): Promise<ChatDraftPutResult> => {+ const styled = await this.captureStyledScreen(persistKey)+ if (styled === '' || screenGate(styled) !== null) return { put: false, reason: 'unreadable' }+ const composer = readClaudeComposer(styled)+ if (composer === 'draft') return { put: false, reason: 'has-draft' }+ if (composer !== 'empty') return { put: false, reason: 'unreadable' }+ const typed = await this.sendTyped(persistKey, text, agentId, { submit: false })+ if (typed === null) return { put: false, reason: 'unsupported' }+ if (typed === true) return { put: true }+ return { put: false, reason: typed === false ? 'failed' : 'unconfirmed' }+ })+ }++ /**+ * Terminal → ⌘M chat view: take the draft out of the agent's own input box, for the chat+ * composer. Only a draft that can be read back EXACTLY (`readClaudeDraftLine`: one row, the+ * ordinary prompt, no collapsed paste); anything else stays where it is and the caller says why.+ * Cleared with Ctrl-E then Ctrl-U — MEASURED (2.1.319): Ctrl-U alone deletes only what is left of+ * the cursor, so a draft whose cursor the user had moved lost only part of it; Ctrl-E first clears+ * the whole row. Never Ctrl-C (see `interruptChat`). The text is handed over only once the box+ * reads empty, so it is never in both places. Runs inside `serializePaneWrite`.+ */+ async takeChatDraft(persistKey: string, agentId: string): Promise<ChatDraftTakeResult> {+ if (!readsScreenDialogs(agentId)) return { taken: false, reason: 'unsupported' }+ return this.serializePaneWrite(persistKey, async (): Promise<ChatDraftTakeResult> => {+ const readLine = async () => readClaudeDraftLine(await this.captureStyledScreen(persistKey))+ const draft = await readLine()+ if (draft === null) return { taken: false, reason: 'unreadable' }+ if (draft.kind === 'empty') return { taken: false, reason: 'empty' }+ if (draft.kind === 'refused') return { taken: false, reason: draft.reason }+ const cleared = await this.sendPaneKeys(persistKey, '\x05\x15')+ if (!cleared.ok) return { taken: false, reason: cleared.reason === 'unsupported-backend' ? 'unsupported' : 'failed' }+ const deadline = Date.now() + INTERRUPT_RESTORE_WAIT_MS+ for (;;) {+ const now = await readLine()+ if (now?.kind === 'empty') return { taken: true, text: draft.text }+ if (Date.now() >= deadline) return { taken: false, reason: 'not-cleared' }+ await new Promise((r) => setTimeout(r, INTERRUPT_RESTORE_POLL_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.tsindex 7ef35e173..44d511f95 100644--- a/src/core/relay/access-policy.ts+++ b/src/core/relay/access-policy.ts@@ -344,6 +344,9 @@ export const EDITOR_ONLY: ReadonlySet<string> = new Set<string>([IPC.ptySendText,IPC.ptySendChatPrompt,IPC.ptySendToEmptyPrompt,+ // Carrying a draft between the ⌘M composer and the input box types into, or clears, the pane.+ IPC.ptyPutChatDraft,+ IPC.ptyTakeChatDraft,// The composer's screen poll; only an editor has a composer.IPC.ptyReadChatScreen,IPC.ptyInterruptChat,diff --git a/src/core/relay/scoped-guest-policy.ts b/src/core/relay/scoped-guest-policy.tsindex ee20a9688..3d3522167 100644--- a/src/core/relay/scoped-guest-policy.ts+++ b/src/core/relay/scoped-guest-policy.ts@@ -391,6 +391,8 @@ export const SCOPED: Readonly<Record<string, Check>> = Object.freeze({[IPC.ptySendToEmptyPrompt]: nodeArg0,[IPC.ptyReadChatScreen]: nodeArg0,[IPC.ptyInterruptChat]: nodeArg0,+ [IPC.ptyPutChatDraft]: nodeArg0,+ [IPC.ptyTakeChatDraft]: nodeArg0,[IPC.ptyTmuxStatus]: pass,[IPC.ptyPaneCommand]: nodeArg0,[IPC.ptyPaneCwd]: nodeArg0,diff --git a/src/preload/index.ts b/src/preload/index.tsindex 24c85842a..c9e4ae539 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -118,6 +118,8 @@ const api: NodeTerminalApi = {readChatScreen: (persistKey, agentId) => ipcRenderer.invoke(IPC.ptyReadChatScreen, persistKey, agentId),interruptChat: (persistKey, agentId, sentText) =>ipcRenderer.invoke(IPC.ptyInterruptChat, persistKey, agentId, sentText),+ putChatDraft: (persistKey, agentId, text) => ipcRenderer.invoke(IPC.ptyPutChatDraft, persistKey, agentId, text),+ takeChatDraft: (persistKey, agentId) => ipcRenderer.invoke(IPC.ptyTakeChatDraft, persistKey, agentId),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.tsindex 54306b08e..20ee8596e 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -28,7 +28,13 @@ import {type RpcMessage} from '../../shared/rpc'import { IPC } from '../../shared/ipc'-import type { ChatInterruptResult, ChatPromptResult, EmptyPromptResult } from '../../shared/text-delivery'+import type {+ ChatDraftPutResult,+ ChatDraftTakeResult,+ ChatInterruptResult,+ ChatPromptResult,+ EmptyPromptResult+} from '../../shared/text-delivery'import type { ChatScreenRead } from '../../shared/agents/claude-screen'import type { GitHubControlApi, GitHubIssuesApi } from '../../shared/github-issues'import {@@ -314,6 +320,15 @@ export function buildRealApi(client.request(IPC.ptyInterruptChat, persistKey, agentId, sentText).catch(() => ({ sent: false, reason: 'failed' })) as Promise<ChatInterruptResult>,+ // Real: core registers both. A failed request is `failed`, which changes nothing on either side.+ putChatDraft: (persistKey, agentId, text) =>+ client+ .request(IPC.ptyPutChatDraft, persistKey, agentId, text)+ .catch(() => ({ put: false, reason: 'failed' })) as Promise<ChatDraftPutResult>,+ takeChatDraft: (persistKey, agentId) =>+ client+ .request(IPC.ptyTakeChatDraft, persistKey, agentId)+ .catch(() => ({ taken: false, reason: 'failed' })) as Promise<ChatDraftTakeResult>,// A failed read is unknown, never evidence that persistence is available.tmuxStatus: () =>clientdiff --git a/src/renderer/components/kanban/CardModal.tsx b/src/renderer/components/kanban/CardModal.tsxindex 5b875c820..f427e979a 100644--- a/src/renderer/components/kanban/CardModal.tsx+++ b/src/renderer/components/kanban/CardModal.tsx@@ -81,6 +81,7 @@ import {type LocalFileTarget} from './LocalFilePreviewModal'import { ChatPanelFallback } from '../../nodes/ChatPanelFallback'+import { carryDraftToChat, carryDraftToTerminal } from '../../lib/chatDraftCarry'// Code-split exactly like the canvas node's: ChatPanel carries the markdown renderer, and the// card modal must not pull it onto the board's first paint.@@ -235,10 +236,8 @@ export function CardModal({ session, projectId, projectName, projectColor, columuseEffect(() => {setMdFor(initialView === 'md' ? session.id : null)}, [session.id, initialView])- const toggleMd = useCallback(() => {- setMdFor((cur) => (cur === session.id ? null : session.id))- setSearchOpen(false) // the FindBar searches the xterm the view now covers- }, [session.id])+ // `toggleMd` (the user's own flip) carries a half-typed draft across, as on the canvas node+ // (lib/chatDraftCarry.ts); it is declared below, once `useChat` is known.// Same decision the node makes (TerminalNode: `showChat` / `useChat`): the CREATED agent picks// the reader, ChatPanel only once the session id is known, else the output view.const createdAgent = session.agentId ?? session.spawn.agentId@@ -252,6 +251,32 @@ export function CardModal({ session, projectId, projectName, projectColor, columcwd: session.spawn.cwd})const useChat = mdOpen && !!createdAgent && canChat(createdAgent) && !!transcript.sessionId+ // Whether the ⌘M face is the chat panel, asked before it is open (the carry into the composer).+ const chatFace = !!createdAgent && canChat(createdAgent) && !!transcript.sessionId+ const chatFaceRef = useRef(chatFace)+ chatFaceRef.current = chatFace+ const mdOpenRef = useRef(mdOpen)+ mdOpenRef.current = mdOpen+ const carryingRef = useRef(false)+ const toggleMd = useCallback(() => {+ if (carryingRef.current) return+ setSearchOpen(false) // the FindBar searches the xterm the view now covers+ if (!mdOpenRef.current) {+ setMdFor(session.id)+ if (chatFaceRef.current) void carryDraftToChat(api.pty, session.id, createdAgent)+ return+ }+ if (!chatFaceRef.current) {+ setMdFor(null)+ return+ }+ // While the draft is typed into the terminal, a second press would type it again.+ carryingRef.current = true+ void carryDraftToTerminal(api.pty, session.id, createdAgent).finally(() => {+ carryingRef.current = false+ setMdFor((cur) => (cur === session.id ? null : cur))+ })+ }, [api.pty, session.id, createdAgent])const captureFull = useCallback((nodeId: string) => api.pty.capture(nodeId, true), [api])const mdChip = chipFor('node.toggleMarkdown')// The chord (main-intercepted on desktop, bridged in the browser) toggles THIS view while thediff --git a/src/renderer/lib/chatDraftCarry.test.ts b/src/renderer/lib/chatDraftCarry.test.tsnew file mode 100644index 000000000..62b963be1--- /dev/null+++ b/src/renderer/lib/chatDraftCarry.test.ts@@ -0,0 +1,150 @@+// @vitest-environment jsdom+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { ChatDraftPutResult, ChatDraftTakeResult } from '@shared/text-delivery'+import { useChatDraft } from '../state/chatDraft'+import { CARRY_TO_TERMINAL_WAIT_MS, carryDraftToChat, carryDraftToTerminal, type DraftCarryPty } from './chatDraftCarry'++const NODE = 'n1'+const draft = () => useChatDraft.getState().drafts[NODE] ?? ''+const note = () => useChatDraft.getState().notes[NODE] ?? null++function pty(put: Promise<ChatDraftPutResult> | ChatDraftPutResult, take: ChatDraftTakeResult = { taken: false, reason: 'empty' }) {+ return {+ putChatDraft: vi.fn<DraftCarryPty['putChatDraft']>(async () => put),+ takeChatDraft: vi.fn<DraftCarryPty['takeChatDraft']>(async () => take)+ }+}++let toasts: string[]+const onToast = (e: Event) => toasts.push((e as CustomEvent<{ message: string }>).detail.message)++beforeEach(() => {+ useChatDraft.setState({ drafts: {}, notes: {} })+ toasts = []+ window.addEventListener('nodeterm:toast', onToast)+})+afterEach(() => {+ window.removeEventListener('nodeterm:toast', onToast)+ vi.useRealTimers()+})++describe('carryDraftToTerminal', () => {+ it('moves the chat draft: typed into the terminal, then emptied here', async () => {+ useChatDraft.getState().setDraft(NODE, 'half a thought')+ const p = pty({ put: true })++ await carryDraftToTerminal(p, NODE, 'claude')++ expect(p.putChatDraft).toHaveBeenCalledWith(NODE, 'claude', 'half a thought')+ expect(draft()).toBe('')+ })++ it('keeps the chat draft, and says why, when the terminal already has one', async () => {+ useChatDraft.getState().setDraft(NODE, 'half a thought')++ await carryDraftToTerminal(pty({ put: false, reason: 'has-draft' }), NODE, 'claude')++ expect(draft()).toBe('half a thought')+ expect(toasts).toEqual([expect.stringMatching(/terminal already has a draft/)])+ })++ it('does nothing with an empty draft, or for an agent it cannot carry for', async () => {+ const a = pty({ put: true })+ useChatDraft.getState().setDraft(NODE, 'x')+ const b = pty({ put: true })++ useChatDraft.setState({ drafts: {} })+ await carryDraftToTerminal(a, NODE, 'claude')+ useChatDraft.getState().setDraft(NODE, 'x')+ await carryDraftToTerminal(b, NODE, 'codex')++ expect(a.putChatDraft).not.toHaveBeenCalled()+ expect(b.putChatDraft).not.toHaveBeenCalled()+ expect(draft()).toBe('x')+ })++ it('stops waiting after its limit, and still empties the draft when the typing lands', async () => {+ vi.useFakeTimers()+ useChatDraft.getState().setDraft(NODE, 'slow')+ let land: (r: ChatDraftPutResult) => void = () => {}+ const p = pty(new Promise<ChatDraftPutResult>((r) => (land = r)))++ const flip = carryDraftToTerminal(p, NODE, 'claude')+ await vi.advanceTimersByTimeAsync(CARRY_TO_TERMINAL_WAIT_MS)+ await flip+ const beforeLanding = draft()+ land({ put: true })+ await vi.advanceTimersByTimeAsync(0)++ expect(beforeLanding).toBe('slow')+ expect(draft()).toBe('')+ })++ it('leaves a draft the user changed while it was typed', async () => {+ useChatDraft.getState().setDraft(NODE, 'first')+ let land: (r: ChatDraftPutResult) => void = () => {}+ const p = pty(new Promise<ChatDraftPutResult>((r) => (land = r)))++ const flip = carryDraftToTerminal(p, NODE, 'claude')+ useChatDraft.getState().setDraft(NODE, 'first, and more')+ land({ put: true })+ await flip++ expect(draft()).toBe('first, and more')+ })+})++describe('carryDraftToChat', () => {+ it('fills the empty composer with the terminal draft', async () => {+ const p = pty({ put: true }, { taken: true, text: 'from the terminal' })++ await carryDraftToChat(p, NODE, 'claude')++ expect(draft()).toBe('from the terminal')+ })++ it('takes nothing when the chat composer already has a draft', async () => {+ useChatDraft.getState().setDraft(NODE, 'chat draft')+ const p = pty({ put: true }, { taken: true, text: 'terminal draft' })++ await carryDraftToChat(p, NODE, 'claude')++ expect(p.takeChatDraft).not.toHaveBeenCalled()+ expect(draft()).toBe('chat draft')+ })++ it('says why a terminal draft stayed in the terminal', async () => {+ await carryDraftToChat(pty({ put: true }, { taken: false, reason: 'multi-line' }), NODE, 'claude')++ expect(note()).toBe(+ "Multiline draft messages can't be copied from the terminal to chat view. Your draft is still available in the terminal."+ )+ })++ it('says nothing when there was nothing to take', async () => {+ await carryDraftToChat(pty({ put: true }, { taken: false, reason: 'empty' }), NODE, 'claude')++ expect(note()).toBeNull()+ })++ it('puts the taken draft first when the user typed in the composer meanwhile', async () => {+ let land: (r: ChatDraftTakeResult) => void = () => {}+ const p = pty({ put: true })+ p.takeChatDraft.mockImplementation(() => new Promise<ChatDraftTakeResult>((r) => (land = r)))++ const carry = carryDraftToChat(p, NODE, 'claude')+ useChatDraft.getState().setDraft(NODE, 'typed meanwhile')+ land({ taken: true, text: 'from the terminal' })+ await carry++ expect(draft()).toBe('from the terminal\ntyped meanwhile')+ })++ it('clears the note once the draft is edited', async () => {+ await carryDraftToChat(pty({ put: true }, { taken: false, reason: 'placeholder' }), NODE, 'claude')++ useChatDraft.getState().setDraft(NODE, 'x')++ expect(note()).toBeNull()+ })+})diff --git a/src/renderer/lib/chatDraftCarry.ts b/src/renderer/lib/chatDraftCarry.tsnew file mode 100644index 000000000..59b2c423b--- /dev/null+++ b/src/renderer/lib/chatDraftCarry.ts@@ -0,0 +1,98 @@+import { readsScreenDialogs, typesChatInput } from '@shared/agents/config'+import type { ChatDraftCarryRefusal, ChatDraftPutResult, ChatDraftTakeResult } from '@shared/text-delivery'+import { useChatDraft } from '../state/chatDraft'++// Carrying a half-typed draft across a ⌘M flip, so it is in front of the user on the side they+// switched to. The draft MOVES (core empties the side it leaves), so it is never sent twice.+// - chat → terminal: the chat draft is typed into the agent's EMPTY input box, unsent.+// - terminal → chat: a terminal draft that can be read back exactly (one row, no collapsed paste)+// comes into the EMPTY chat composer; anything else stays in the terminal and the composer says why.+// Only on the user's own flip (⌘M, the header toggle). A flip the composer makes itself (a `/model`+// label, an interactive built-in) carries nothing: a picker has just opened there.+// Claude only, as the core side is (its composer is measured).++export type DraftCarryPty = {+ putChatDraft(nodeId: string, agentId: string, text: string): Promise<ChatDraftPutResult>+ takeChatDraft(nodeId: string, agentId: string): Promise<ChatDraftTakeResult>+}++/** How long a flip to the terminal waits for the draft to be typed before flipping anyway. */+export const CARRY_TO_TERMINAL_WAIT_MS = 1500++export function carriesDraft(agentId: string | undefined | null): agentId is string {+ return typeof agentId === 'string' && readsScreenDialogs(agentId) && typesChatInput(agentId)+}++const toast = (message: string): void => {+ window.dispatchEvent(new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message } }))+}++/** What the composer says when a terminal draft stayed where it was. null = say nothing. */+export function stayedInTerminalNote(reason: ChatDraftCarryRefusal): string | null {+ const stillThere = 'Your draft is still available in the terminal.'+ switch (reason) {+ case 'multi-line':+ return `Multiline draft messages can't be copied from the terminal to chat view. ${stillThere}`+ case 'placeholder':+ return `Drafts with pasted text or images can't be copied from the terminal to chat view. ${stillThere}`+ case 'not-prompt':+ return `Shell-mode drafts can't be copied from the terminal to chat view. ${stillThere}`+ case 'not-cleared':+ return "Your draft couldn't be copied from the terminal to chat view. Check the terminal before sending: part of it may have been cleared."+ default:+ return null+ }+}++/** What the toast says when a chat draft did not move to the terminal. null = say nothing. */+export function stayedInChatMessage(reason: ChatDraftCarryRefusal): string | null {+ switch (reason) {+ case 'has-draft':+ return 'Your chat draft is still in the chat view: the terminal already has a draft.'+ case 'unconfirmed':+ return 'Your chat draft may not have reached the terminal. It is still in the chat view; check the terminal before sending either.'+ case 'empty':+ case 'unsupported':+ return null+ default:+ return "Your chat draft couldn't be moved to the terminal. It is still in the chat view."+ }+}++/**+ * Chat → terminal, run BEFORE the view flips: the draft is being typed into the pane, and typing in+ * the terminal at the same time would interleave with it. Waits at most CARRY_TO_TERMINAL_WAIT_MS;+ * a put still running after that keeps going, and its result is applied when it lands.+ */+export async function carryDraftToTerminal(pty: DraftCarryPty, nodeId: string, agentId: string | undefined): Promise<void> {+ if (!carriesDraft(agentId)) return+ const draft = useChatDraft.getState().drafts[nodeId] ?? ''+ if (draft.trim() === '') return+ const put = pty.putChatDraft(nodeId, agentId, draft).catch((): ChatDraftPutResult => ({ put: false, reason: 'failed' }))+ const settled = put.then((r) => {+ if (r.put) {+ // Only the draft that was typed: a draft changed meanwhile is the user's newer text.+ useChatDraft.getState().setDraft(nodeId, (cur) => (cur === draft ? '' : cur))+ return+ }+ const message = stayedInChatMessage(r.reason)+ if (message !== null) toast(message)+ })+ await Promise.race([settled, new Promise<void>((r) => setTimeout(r, CARRY_TO_TERMINAL_WAIT_MS))])+}++/** Terminal → chat, run AFTER the view flips: the chat composer fills in when the take lands. */+export async function carryDraftToChat(pty: DraftCarryPty, nodeId: string, agentId: string | undefined): Promise<void> {+ if (!carriesDraft(agentId)) return+ // Two drafts are never merged: a chat draft already waiting wins, and the terminal keeps its own.+ if ((useChatDraft.getState().drafts[nodeId] ?? '') !== '') return+ const r = await pty.takeChatDraft(nodeId, agentId).catch((): ChatDraftTakeResult => ({ taken: false, reason: 'failed' }))+ const store = useChatDraft.getState()+ if (r.taken) {+ // Typed into the composer while the take ran: the taken text goes first, as it was older.+ store.setDraft(nodeId, (cur) => (cur === '' ? r.text : `${r.text}\n${cur}`))+ return+ }+ const note = stayedInTerminalNote(r.reason)+ if (note !== null) store.setNote(nodeId, note)+}diff --git a/src/renderer/nodes/ChatComposer.tsx b/src/renderer/nodes/ChatComposer.tsxindex f9c3092f8..183db31b2 100644--- a/src/renderer/nodes/ChatComposer.tsx+++ b/src/renderer/nodes/ChatComposer.tsx@@ -27,6 +27,10 @@ import { Spinner } from '../components/Spinner'import { builtinSlashCommands, sanitizeChatCatalog, type ChatCatalogEntry } from '@shared/chat-catalog'import { prepareQuickOpenFiles, type QuickOpenIndexedFile } from '../lib/quickOpenSearch'import { commandSegments, mentionsSlashToken } from '../lib/chatComposerHighlight'+import { useChatDraft } from '../state/chatDraft'++/** How long the composer shows why a terminal draft was not carried over. */+const CARRY_NOTE_MS = 12_000import {CATALOG_REUSE_MS,applyCompletion,@@ -125,6 +129,14 @@ export function ChatComposer({const usage = useContextUsage({ sessionId, nodeId, scoped: false })const [composerWidth, setComposerWidth] = useState<number | null>(null)const [attachNote, setAttachNote] = useState<{ text: string; failed?: boolean } | null>(null)+ // Why a terminal draft was not carried over on the last ⌘M flip (lib/chatDraftCarry.ts). Editing+ // the draft clears it (the store does); otherwise it goes after CARRY_NOTE_MS.+ const carryNote = useChatDraft((s) => s.notes[nodeId] ?? null)+ useEffect(() => {+ if (carryNote === null) return+ const t = setTimeout(() => useChatDraft.getState().setNote(nodeId, null), CARRY_NOTE_MS)+ return () => clearTimeout(t)+ }, [carryNote, nodeId])const [dropping, setDropping] = useState(false)// A picker command on its way into the pane. `/model` and `/effort` are local pickers that fire// NO hook, so the agent state stays `done` and the send gate stays open: a second click (or an@@ -582,6 +594,11 @@ export function ChatComposer({rows={2}/></div>+ {carryNote !== null && (+ <div className="term-chat__carry-note" role="status">+ {carryNote}+ </div>+ )}<div className="term-chat__toolbar">{pathsForFiles && (<>diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 74df70fec..07e1f1f20 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -242,6 +242,7 @@ import {useMdModeFocus} from '../terminal/useMdModeFocus'import { canvasOwnsMarkdownChord } from '../lib/markdownChord'+import { carryDraftToChat, carryDraftToTerminal } from '../lib/chatDraftCarry'import { IconBroadcast, IconChat, IconChevronDown, IconChevronRight, IconClose, IconEye, IconEyeOff, IconGrid, IconMic, IconMoveTo, IconPlay, IconReload, IconSearch, IconSparkle } from '../components/icons'import { NodeLabels } from '../components/kanban/NodeLabels'import { MdViewHintButton } from '../components/MdViewHintButton'@@ -6106,14 +6107,40 @@ export function TerminalNode({}}, [id, gates.titleSync, canReadTitleNode, status?.sessionId, data.titleAuto, updateNodeData])+ // The user's own ⌘M flip (the chord, the header toggle) carries a half-typed draft across+ // (lib/chatDraftCarry.ts): into the agent's input box before leaving the chat view, out of it+ // after opening it. A flip the composer makes itself (`onShowTerminal`) carries nothing. While a+ // draft is being typed into the terminal, further presses are ignored: a second carry would type+ // it again.+ const chatAvailableRef = useRef(chatAvailable)+ chatAvailableRef.current = chatAvailable+ const carryingRef = useRef(false)+ const toggleMdView = useCallback(() => {+ if (carryingRef.current) return+ if (!mdModeRef.current) {+ updateNodeData(id, () => ({ mdMode: true }))+ if (chatAvailableRef.current) void carryDraftToChat(session.api.pty, id, agentId)+ return+ }+ if (!chatAvailableRef.current) {+ updateNodeData(id, () => ({ mdMode: false }))+ return+ }+ carryingRef.current = true+ void carryDraftToTerminal(session.api.pty, id, agentId).finally(() => {+ carryingRef.current = false+ updateNodeData(id, () => ({ mdMode: false }))+ })+ }, [id, agentId, session.api.pty, updateNodeData])+// Cmd/Ctrl+M toggles markdown view of this terminal's output — only when hovered, and never while// a board is up (the card modal owns the chord there; see `canvasOwnsMarkdownChord`).useEffect(() => {return window.nodeTerminal.onMarkdownToggle(() => {if (!canvasOwnsMarkdownChord(hoveredRef.current, isGlobalKanbanOpen() || isKanbanOpen(useProjects.getState().activeProjectId ?? ''))) return- updateNodeData(id, (n) => ({ mdMode: !n.data.mdMode }))+ toggleMdView()})- }, [id, updateNodeData])+ }, [toggleMdView])// Best-effort: highlight matches that are in the live xterm buffer (on-screen scrollback).useEffect(() => {@@ -6758,8 +6785,8 @@ export function TerminalNode({<MdViewHintButtonhint={mdHint}tooltip={commandTooltip(mdMode ? 'Back to the terminal' : `Open ${mdHint.label.toLowerCase()}`, 'node.toggleMarkdown')}- // The same flip as the chord handler and the context-menu item.- onToggle={() => updateNodeData(id, (n) => ({ mdMode: !n.data.mdMode }))}+ // The same flip as the chord handler, draft carry included.+ onToggle={toggleMdView}/>)}diff --git a/src/renderer/nodes/chat-draft-carry-wiring.test.ts b/src/renderer/nodes/chat-draft-carry-wiring.test.tsnew file mode 100644index 000000000..253095d75--- /dev/null+++ b/src/renderer/nodes/chat-draft-carry-wiring.test.ts@@ -0,0 +1,39 @@+import { readFileSync } from 'fs'+import { join } from 'path'+import { describe, expect, it } from 'vitest'++// The draft carry (lib/chatDraftCarry.ts) runs on the USER's own ⌘M flip only. A flip the composer+// makes itself (`onShowTerminal`: a `/model` label, an interactive built-in) opens a picker in the+// terminal, and typing a draft into it would answer the picker. Both surfaces wire this by hand, and+// a dropped call compiles, so it is pinned at source level.++const read = (f: string): string => readFileSync(join(__dirname, f), 'utf8').replace(/\r\n/g, '\n')++/** The JSX/code from `onShowTerminal={` to the end of its handler. */+function showTerminalHandler(src: string): string {+ const at = src.indexOf('onShowTerminal={')+ expect(at).toBeGreaterThan(-1)+ return src.slice(at, src.indexOf('}}', at) + 2)+}++describe('draft carry wiring', () => {+ it('the canvas node carries on its chord and its header toggle, not on the composer flip', () => {+ const src = read('TerminalNode.tsx')+ const toggle = src.slice(src.indexOf('const toggleMdView = useCallback('), src.indexOf('// Cmd/Ctrl+M toggles markdown view'))++ expect(toggle).toContain('carryDraftToChat(')+ expect(toggle).toContain('carryDraftToTerminal(')+ expect(src).toMatch(/onMarkdownToggle\(\(\) => \{[\s\S]*?toggleMdView\(\)/)+ expect(src).toContain('onToggle={toggleMdView}')+ expect(showTerminalHandler(src)).not.toContain('carryDraft')+ })++ it('the card modal carries on its toggle, not on the composer flip', () => {+ const src = read('../components/kanban/CardModal.tsx')+ const toggle = src.slice(src.indexOf('const toggleMd = useCallback('))++ expect(toggle.slice(0, toggle.indexOf('}, ['))).toContain('carryDraftToChat(')+ expect(toggle.slice(0, toggle.indexOf('}, ['))).toContain('carryDraftToTerminal(')+ expect(showTerminalHandler(src)).not.toContain('carryDraft')+ })+})diff --git a/src/renderer/state/chatDraft.ts b/src/renderer/state/chatDraft.tsindex 27c2ec8fc..543489365 100644--- a/src/renderer/state/chatDraft.ts+++ b/src/renderer/state/chatDraft.ts@@ -109,12 +109,17 @@ function loadDrafts(): Record<string, string> {interface ChatDraftState {drafts: Record<string, string>+ /** One line the composer shows about its draft (lib/chatDraftCarry.ts: why a terminal draft was+ * not carried over). In memory only; any change to that node's draft clears it. */+ notes: Record<string, string>/** Sets one node's draft; a function gets the current draft, as React's state setter does. */setDraft(nodeId: string, next: SetStateAction<string>): void+ setNote(nodeId: string, note: string | null): void}export const useChatDraft = create<ChatDraftState>((set) => ({drafts: loadDrafts(),+ notes: {},setDraft: (nodeId, next) =>set((s) => {const cur = s.drafts[nodeId] ?? ''@@ -125,7 +130,18 @@ export const useChatDraft = create<ChatDraftState>((set) => ({else drafts[nodeId] = valuepending.set(nodeId, value === '' ? null : { text: value, at: Date.now() })scheduleSave()- return { drafts }+ if (s.notes[nodeId] === undefined) return { drafts }+ const notes = { ...s.notes }+ delete notes[nodeId]+ return { drafts, notes }+ }),+ setNote: (nodeId, note) =>+ set((s) => {+ if ((s.notes[nodeId] ?? null) === note) return s+ const notes = { ...s.notes }+ if (note === null) delete notes[nodeId]+ else notes[nodeId] = note+ return { notes }})}))diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 5d8de15f9..8fa2771ad 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -4219,6 +4219,14 @@ body,.term-chat__effort {color: var(--muted);}+/* Why a terminal draft stayed in the terminal on the last ⌘M flip (lib/chatDraftCarry.ts): its own+ row under the text box, wrapping, since the reason is a sentence. */+.term-chat__carry-note {+ padding: 0 6px 2px;+ font-size: 11px;+ line-height: 1.35;+ color: var(--muted);+}.term-chat__attach-note {display: inline-flex;align-items: center;diff --git a/src/shared/agents/__fixtures__/claude/draft-line-capture.json b/src/shared/agents/__fixtures__/claude/draft-line-capture.jsonnew file mode 100644index 000000000..8f0383d28--- /dev/null+++ b/src/shared/agents/__fixtures__/claude/draft-line-capture.json@@ -0,0 +1,13 @@+{+ "_note": "Captured 2026-11-07 from Claude Code 2.1.319 (haiku, fullscreen TUI) in a private tmux server, 100x30, `tmux capture-pane -p -e`. Drafts typed with `send-keys -l`; `multiline` joins two lines with M-Enter; `wrapped` is ONE line long enough to wrap; `pasted` is a 12-line bracketed paste; `shellmode` typed `!` then `ls -la`; `slash-partial` typed `/he` (its command menu is open above the box). Read by readClaudeDraftLine (shared/agents/claude-screen.ts). Sanitized: one row of the `/he` menu (a locally installed skill) was removed, and the working-directory path in the header replaced with `/…/project`.",+ "claudeVersion": "2.1.319",+ "screens": {+ "empty": "\n\u001b[38;5;174m ▐\u001b[48;5;16m▛███▛█\u001b[39m\u001b[49m \u001b[1mClaude Code\u001b[0m \u001b[38;5;246mv2.1.319\u001b[39m\n\u001b[38;5;174m▝▜\u001b[48;5;16m█████\u001b[49m█▀\u001b[39m \u001b[38;5;246mHaiku 5.5 · Claude Ultra\u001b[39m\n\u001b[38;5;174m ▝▝ ▝▝ \u001b[39m \u001b[38;5;246m/…/project\u001b[39m\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m❯ \u001b[2mTry \"refactor <filepath>\"\u001b[0m\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m \u001b[38;5;246m🧠 \u001b[38;5;147mHaiku 5.5\u001b[38;5;246m \u001b[38;5;245m|\u001b[38;5;246m \u001b[38;5;117m┤ ├\u001b[38;5;246m \u001b[38;5;117m0%\u001b[38;5;246m \u001b[38;5;245m|\u001b[38;5;246m 💰 \u001b[38;5;222m$0.00\u001b[39m\n \u001b[38;5;220m⏵⏵ auto mode on\u001b[38;5;246m (shift+tab to cycle)\u001b[39m\n",+ "line": "\n\u001b[38;5;174m ▐\u001b[48;5;16m▛███▛█\u001b[39m\u001b[49m \u001b[1mClaude Code\u001b[0m \u001b[38;5;246mv2.1.319\u001b[39m\n\u001b[38;5;174m▝▜\u001b[48;5;16m█████\u001b[49m█▀\u001b[39m \u001b[38;5;246mHaiku 5.5 · Claude Ultra\u001b[39m\n\u001b[38;5;174m ▝▝ ▝▝ \u001b[39m \u001b[38;5;246m/…/project\u001b[39m\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m❯ fix the login bug, then run tests\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m \u001b[38;5;246m🧠 \u001b[38;5;147mHaiku 5.5\u001b[38;5;246m \u001b[38;5;245m|\u001b[38;5;246m \u001b[38;5;117m┤ ├\u001b[38;5;246m \u001b[38;5;117m0%\u001b[38;5;246m \u001b[38;5;245m|\u001b[38;5;246m 💰 \u001b[38;5;222m$0.00\u001b[39m\n \u001b[38;5;220m⏵⏵ auto mode on\u001b[38;5;246m (shift+tab to cycle)\u001b[39m\n",+ "wrapped": "\n\u001b[38;5;174m ▐\u001b[48;5;16m▛███▛█\u001b[39m\u001b[49m \u001b[1mClaude Code\u001b[0m \u001b[38;5;246mv2.1.319\u001b[39m\n\u001b[38;5;174m▝▜\u001b[48;5;16m█████\u001b[49m█▀\u001b[39m \u001b[38;5;246mHaiku 5.5 · Claude Ultra\u001b[39m\n\u001b[38;5;174m ▝▝ ▝▝ \u001b[39m \u001b[38;5;246m/…/project\u001b[39m\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \u001b[38;5;246mCtrl+Y to paste deleted text\u001b[39m\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m❯ word word word word word word word word word word word word word word word word word word word\n word word word word word word word word word word word end\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m \u001b[38;5;246m🧠 \u001b[38;5;147mHaiku 5.5\u001b[38;5;246m \u001b[38;5;245m|\u001b[38;5;246m \u001b[38;5;117m┤ ├\u001b[38;5;246m \u001b[38;5;117m0%\u001b[38;5;246m \u001b[38;5;245m|\u001b[38;5;246m 💰 \u001b[38;5;222m$0.00\u001b[39m\n \u001b[38;5;220m⏵⏵ auto mode on\u001b[38;5;246m (shift+tab to cycle)\u001b[39m\n",+ "multiline": "\n\u001b[38;5;174m ▐\u001b[48;5;16m▛███▛█\u001b[39m\u001b[49m \u001b[1mClaude Code\u001b[0m \u001b[38;5;246mv2.1.319\u001b[39m\n\u001b[38;5;174m▝▜\u001b[48;5;16m█████\u001b[49m█▀\u001b[39m \u001b[38;5;246mHaiku 5.5 · Claude Ultra\u001b[39m\n\u001b[38;5;174m ▝▝ ▝▝ \u001b[39m \u001b[38;5;246m/…/project\u001b[39m\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \u001b[38;5;246mctrl+g to edit in Vim\u001b[39m\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m❯ line one\n line two\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m \u001b[38;5;246m🧠 \u001b[38;5;147mHaiku 5.5\u001b[38;5;246m \u001b[38;5;245m|\u001b[38;5;246m \u001b[38;5;117m┤ ├\u001b[38;5;246m \u001b[38;5;117m0%\u001b[38;5;246m \u001b[38;5;245m|\u001b[38;5;246m 💰 \u001b[38;5;222m$0.00\u001b[39m\n \u001b[38;5;220m⏵⏵ auto mode on\u001b[38;5;246m (shift+tab to cycle)\u001b[39m\n",+ "pasted": "\n\u001b[38;5;174m ▐\u001b[48;5;16m▛███▛█\u001b[39m\u001b[49m \u001b[1mClaude Code\u001b[0m \u001b[38;5;246mv2.1.319\u001b[39m\n\u001b[38;5;174m▝▜\u001b[48;5;16m█████\u001b[49m█▀\u001b[39m \u001b[38;5;246mHaiku 5.5 · Claude Ultra\u001b[39m\n\u001b[38;5;174m ▝▝ ▝▝ \u001b[39m \u001b[38;5;246m/…/project\u001b[39m\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \u001b[38;5;246mCtrl+Y to paste deleted text\u001b[39m\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m❯ [Pasted text #2 +12 lines]\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m \u001b[38;5;246m🧠 \u001b[38;5;147mHaiku 5.5\u001b[38;5;246m \u001b[38;5;245m|\u001b[38;5;246m \u001b[38;5;117m┤ ├\u001b[38;5;246m \u001b[38;5;117m0%\u001b[38;5;246m \u001b[38;5;245m|\u001b[38;5;246m 💰 \u001b[38;5;222m$0.00\u001b[39m\n \u001b[38;5;246mpaste again to expand\u001b[39m\n",+ "shellmode": "\n\u001b[38;5;174m ▐\u001b[48;5;16m▛███▛█\u001b[39m\u001b[49m \u001b[1mClaude Code\u001b[0m \u001b[38;5;246mv2.1.319\u001b[39m\n\u001b[38;5;174m▝▜\u001b[48;5;16m█████\u001b[49m█▀\u001b[39m \u001b[38;5;246mHaiku 5.5 · Claude Ultra\u001b[39m\n\u001b[38;5;174m ▝▝ ▝▝ \u001b[39m \u001b[38;5;246m/…/project\u001b[39m\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \u001b[38;5;246mCtrl+Y to paste deleted text\u001b[39m\n\u001b[38;5;211m────────────────────────────────────────────────────────────────────────────────────────────────────\n! \u001b[39mls -la\n\u001b[38;5;211m────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m \u001b[38;5;246mpaste again to expand\u001b[39m\n",+ "slash-partial": "\n\u001b[38;5;174m ▐\u001b[48;5;16m▛███▛█\u001b[39m\u001b[49m \u001b[1mClaude Code\u001b[0m \u001b[38;5;246mv2.1.319\u001b[39m\n\u001b[38;5;174m▝▜\u001b[48;5;16m█████\u001b[49m█▀\u001b[39m \u001b[38;5;246mHaiku 5.5 · Claude Ultra\u001b[39m\n\u001b[38;5;174m ▝▝ ▝▝ \u001b[39m \u001b[38;5;246m/…/project\u001b[39m\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \u001b[38;5;153m❯ /\u001b[1mhe\u001b[0m\u001b[38;5;153mlp Show \u001b[1mhe\u001b[0m\u001b[38;5;153mlp and available commands\u001b[39m\n \u001b[38;5;246m /t\u001b[1m\u001b[39mhe\u001b[0m\u001b[38;5;246mme Change t\u001b[1m\u001b[39mhe\u001b[0m\u001b[38;5;246m theme\u001b[39m\n \u001b[38;5;246m /sc\u001b[1m\u001b[39mhe\u001b[0m\u001b[38;5;246mdule Create and manage routines: cloud agents on a sc\u001b[1m\u001b[39mhe\u001b[0m\u001b[38;5;246mdule\u001b[39m\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m❯ /he\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m \u001b[38;5;246m🧠 \u001b[38;5;147mHaiku 5.5\u001b[38;5;246m \u001b[38;5;245m|\u001b[38;5;246m \u001b[38;5;117m┤ ├\u001b[38;5;246m \u001b[38;5;117m0%\u001b[38;5;246m \u001b[38;5;245m|\u001b[38;5;246m 💰 \u001b[38;5;222m$0.00\u001b[39m\n \u001b[38;5;246mpaste again to expand\u001b[39m\n"+ }+}\ No newline at end of filediff --git a/src/shared/agents/claude-screen.draft-line.test.ts b/src/shared/agents/claude-screen.draft-line.test.tsnew file mode 100644index 000000000..7847e0b89--- /dev/null+++ b/src/shared/agents/claude-screen.draft-line.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from 'vitest'+import capture from './__fixtures__/claude/draft-line-capture.json'+import older from './__fixtures__/claude/composer-capture.json'+import { readClaudeDraftLine } from './claude-screen'++const screen = (name: keyof typeof capture.screens): string => capture.screens[name]++describe('readClaudeDraftLine (Claude Code 2.1.319 captures)', () => {+ it('reads an empty box as empty, never its placeholder', () => {+ expect(readClaudeDraftLine(screen('empty'))).toEqual({ kind: 'empty' })+ })++ it('reads a one-row draft exactly, doubled spaces included', () => {+ expect(readClaudeDraftLine(screen('line'))).toEqual({ kind: 'line', text: 'fix the login bug, then run tests' })+ })++ it('reads a half-typed command with its menu open', () => {+ expect(readClaudeDraftLine(screen('slash-partial'))).toEqual({ kind: 'line', text: '/he' })+ })++ it('refuses a line that wraps, since a wrap looks like a newline', () => {+ expect(readClaudeDraftLine(screen('wrapped'))).toEqual({ kind: 'refused', reason: 'multi-line' })+ })++ it('refuses real newlines', () => {+ expect(readClaudeDraftLine(screen('multiline'))).toEqual({ kind: 'refused', reason: 'multi-line' })+ })++ it('refuses a collapsed paste', () => {+ expect(readClaudeDraftLine(screen('pasted'))).toEqual({ kind: 'refused', reason: 'placeholder' })+ })++ it('refuses shell mode', () => {+ expect(readClaudeDraftLine(screen('shellmode'))).toEqual({ kind: 'refused', reason: 'not-prompt' })+ })++ it('has nothing to read without a screen', () => {+ expect(readClaudeDraftLine('')).toBeNull()+ })+})++describe('readClaudeDraftLine (Claude Code 2.1.301 captures)', () => {+ it('agrees with the older composer fixture', () => {+ expect(readClaudeDraftLine(older.screens.empty)).toEqual({ kind: 'empty' })+ expect(readClaudeDraftLine(older.screens.draft)?.kind).toBe('line')+ expect(readClaudeDraftLine(older.screens.multiline)).toEqual({ kind: 'refused', reason: 'multi-line' })+ expect(readClaudeDraftLine(older.screens.pasted)).toEqual({ kind: 'refused', reason: 'placeholder' })+ expect(readClaudeDraftLine(older.screens.shellmode)).toEqual({ kind: 'refused', reason: 'not-prompt' })+ })+})diff --git a/src/shared/agents/claude-screen.ts b/src/shared/agents/claude-screen.tsindex e2fdbb2b8..33105caff 100644--- a/src/shared/agents/claude-screen.ts+++ b/src/shared/agents/claude-screen.ts@@ -259,6 +259,50 @@ export function readClaudeDraft(styledScreen: string): string | null {return draft.replace(/\s/g, '')}+/**+ * Why a draft in Claude Code's input box cannot be read back EXACTLY (`readClaudeDraftLine`):+ * - `multi-line` — it takes more than one row. MEASURED (2.1.319): a line that wraps and a real+ * newline (M-Enter) look the same, a second row indented two spaces, and the wrap drops the space+ * at the break, so neither the newlines nor the spaces could be put back.+ * - `placeholder` — it holds a collapsed paste or image (`[Pasted text #1 +12 lines]`, `[Image #1]`):+ * the screen shows the placeholder, not the text behind it.+ * - `not-prompt` — the row does not start with the ordinary `❯` prompt (shell mode's `!`, say).+ */+export type ClaudeDraftLineRefusal = 'multi-line' | 'placeholder' | 'not-prompt'++export type ClaudeDraftLine =+ | { kind: 'empty' }+ | { kind: 'line'; text: string }+ | { kind: 'refused'; reason: ClaudeDraftLineRefusal }++const DRAFT_PLACEHOLDER = /\[(?:Pasted text|Image) #\d+/++/**+ * The user's draft in Claude Code's input box, read from a STYLED capture, EXACTLY: only when it is+ * one row with the ordinary prompt and no collapsed paste, so the text can be handed to the ⌘M chat+ * composer as typed (the dim placeholder and any dim inline hint are not part of it; trailing spaces+ * are lost, as tmux trims them). null when there is no live input box to read.+ */+export function readClaudeDraftLine(styledScreen: string): ClaudeDraftLine | null {+ const composer = readClaudeComposer(styledScreen)+ if (composer === 'empty') return { kind: 'empty' }+ if (composer !== 'draft') return null+ const styled = styledScreen.split(/\r?\n/)+ const lines = styled.map((l) => l.replace(ANSI, '').trimEnd())+ const box = inputBox(lines)+ if (!box) return null+ const promptAt = box[0] + 1+ for (let i = promptAt + 1; i < box[1]; i++) {+ if (lines[i].trim() !== '') return { kind: 'refused', reason: 'multi-line' }+ }+ if (!lines[promptAt].startsWith('❯')) return { kind: 'refused', reason: 'not-prompt' }+ // The prompt is `❯` and one space; everything after it that is not dim is the draft.+ const text = undimmedText(styled[promptAt], 1).replace(/^[ \u00a0]/, '').trimEnd()+ if (text === '') return { kind: 'empty' }+ if (DRAFT_PLACEHOLDER.test(text)) return { kind: 'refused', reason: 'placeholder' }+ return { kind: 'line', text }+}+/*** The next prompt Claude Code suggests after a turn, read from a STYLED capture: the dim text on its* prompt line while the input box holds no draft. null when there is none to offer.diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 4ae58e9f1..8ce07e5f2 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -32,6 +32,9 @@ export const IPC = {ptySendToEmptyPrompt: 'pty:send-to-empty-prompt',ptyReadChatScreen: 'pty:read-chat-screen',ptyInterruptChat: 'pty:interrupt-chat',+ /** Carry a draft between the ⌘M chat composer and the agent's own input box (PtyManager). */+ ptyPutChatDraft: 'pty:put-chat-draft',+ ptyTakeChatDraft: 'pty:take-chat-draft',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 1335296e7..3ba7336dc 100644--- a/src/shared/text-delivery.ts+++ b/src/shared/text-delivery.ts@@ -45,3 +45,32 @@ export type ChatInterruptRefusal = 'unsupported' | 'dialog' | 'not-connected' |export type ChatInterruptResult =| { sent: true; restored: string | null }| { sent: false; reason: ChatInterruptRefusal; dialog?: string | null }++/**+ * Carrying a draft between the ⌘M chat composer and the agent's own input box when the user flips+ * the view (`pty.putChatDraft` / `pty.takeChatDraft`). The draft MOVES: whichever side receives it,+ * the other is emptied, so it is never sent twice. Claude only (its composer is measured).+ * - `unsupported` — not an agent whose composer we can read and type into, or a backend with no+ * typed path (Zellij, the Windows session host, a native Windows pane).+ * - `unreadable` — the screen could not be read, or shows no input box (a dialog, a shell).+ * - `has-draft` — (put) the input box already holds a draft: the two are not merged.+ * - `empty` — (take) nothing to carry.+ * - `multi-line` / `placeholder` / `not-prompt` — (take) a draft that cannot be read back exactly+ * (`readClaudeDraftLine`); it stays in the input box.+ * - `unconfirmed` — (put) the text was typed but did not show in the box in time: it may be there.+ * - `not-cleared` — (take) the box did not read empty after clearing it: nothing is handed over.+ * - `failed` — the pane could not be reached or typed into; nothing was changed.+ */+export type ChatDraftCarryRefusal =+ | 'unsupported'+ | 'unreadable'+ | 'has-draft'+ | 'empty'+ | 'multi-line'+ | 'placeholder'+ | 'not-prompt'+ | 'unconfirmed'+ | 'not-cleared'+ | 'failed'+export type ChatDraftPutResult = { put: true } | { put: false; reason: ChatDraftCarryRefusal }+export type ChatDraftTakeResult = { taken: true; text: string } | { taken: false; reason: ChatDraftCarryRefusal }diff --git a/src/shared/types.ts b/src/shared/types.tsindex 34a7a6db1..b0454d133 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1,4 +1,8 @@-import type { ChatInterruptResult, ChatPromptResult, EmptyPromptResult, TextDeliveryResult } from './text-delivery'+import type {+ ChatDraftPutResult,+ ChatDraftTakeResult,+ ChatInterruptResult,+ ChatPromptResult, EmptyPromptResult, TextDeliveryResult } from './text-delivery'import type { ChatScreenRead } from './agents/claude-screen'import type { PushWebhookMinted, PushWebhookResult, PushWebhookTokenInfo } from './push-webhook'import type { IdentitySeedEntry } from './agent-identity-seed'@@ -1433,6 +1437,12 @@ export interface PtyApi {* 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>+ /** ⌘M chat → terminal: type the chat draft into the agent's EMPTY input box, unsent. Never+ * rejects on the desktop. */+ putChatDraft(persistKey: string, agentId: string, text: string): Promise<ChatDraftPutResult>+ /** Terminal → ⌘M chat: take a draft that can be read back exactly out of the agent's input box+ * (it is cleared there). Never rejects on the desktop. */+ takeChatDraft(persistKey: string, agentId: string): Promise<ChatDraftTakeResult>/** 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>