Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(chat): take back an interrupted prompt that wraps or scrolls

Paul Robertson24f02c46f39b
diff --git a/CLAUDE.md b/CLAUDE.md
index a2bfbe969..ceac49f57 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4459,9 +4459,13 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
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
+ core takes it back out ONLY when the box holds 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. MEASURED on 2.1.319: one Ctrl-U clears one WRAPPED
+ ROW, not a whole line, and the box stops growing at about half the pane's height and scrolls, so a
+ long prompt shows only its end. So "holds the last send" accepts that end, each burst is two
+ Ctrl-Us per row on screen (`readClaudeDraftBox`) plus spares, and bursts repeat while what is left
+ ends earlier in the sent text (`endsEarlierIn`). 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.
diff --git a/src/core/pty-manager.interrupt-chat.test.ts b/src/core/pty-manager.interrupt-chat.test.ts
index 4cc923f16..c51db7327 100644
--- a/src/core/pty-manager.interrupt-chat.test.ts
+++ b/src/core/pty-manager.interrupt-chat.test.ts
@@ -16,6 +16,9 @@ const screen = (promptLine: string): string => [RULE, promptLine, RULE, ' ? for
const EMPTY = screen('❯ ')
const PLACEHOLDER = screen(`❯ ${DIM}finish the story${RESET}`)
const draft = (text: string): string => screen(`❯ ${text}`)
+/** An input box showing `rows` as wrapped rows, the way Claude draws a long draft. */
+const rows = (shown: string[]): string =>
+ [RULE, `❯ ${shown[0]}`, ...shown.slice(1).map((r) => ` ${r}`), RULE, ' ? for shortcuts'].join('\n')
const TRUST = [RULE, ' Accessing workspace:', ' ❯ No, exit', ' Yes, I trust this folder', ' Enter to confirm · Esc to cancel'].join('\n')
type Private = { captureStyledScreen: (key: string) => Promise<string> }
@@ -133,4 +136,92 @@ describe('PtyManager.interruptChat', () => {
expect(result).toEqual({ sent: true, restored: null })
})
+
+ it('clears a long single line wrapped onto several rows: two Ctrl-Us per row on screen', async () => {
+ const wrapped = ['w1 w2 w3', 'w4 w5 w6', 'w7 w8 w9', 'w10 w11', 'w12 w13', 'w14 w15']
+ const sent = wrapped.join(' ')
+ const { mgr, sendPaneKeys } = await manager({ plain: EMPTY, styled: [EMPTY, rows(wrapped), PLACEHOLDER] })
+
+ const pending = mgr.interruptChat(NODE, 'claude', sent)
+ await vi.runAllTimersAsync()
+ const result = await pending
+
+ // One line sent, six rows on screen: Ctrl-U clears a visual row (MEASURED, 2.1.319).
+ expect(sendPaneKeys.mock.calls.map((c) => c[1])).toEqual(['\x1b', '\x15'.repeat(14)])
+ expect(result).toEqual({ sent: true, restored: sent })
+ })
+
+ it('takes back a prompt taller than the box, which shows only its end, in rounds', async () => {
+ const sent = 'a1 a2 a3 a4 b1 b2 b3 b4 c1 c2 c3 c4'
+ const { mgr, sendPaneKeys } = await manager({
+ plain: EMPTY,
+ styled: [EMPTY, rows(['c1 c2', 'c3 c4']), rows(['a3 a4', 'b1 b2']), rows(['a1 a2']), PLACEHOLDER]
+ })
+
+ const pending = mgr.interruptChat(NODE, 'claude', sent)
+ await vi.runAllTimersAsync()
+ const result = await pending
+
+ expect(sendPaneKeys.mock.calls.map((c) => c[1])).toEqual(['\x1b', '\x15'.repeat(6), '\x15'.repeat(6), '\x15'.repeat(4)])
+ expect(result).toEqual({ sent: true, restored: sent })
+ })
+
+ it('stops clearing when what is left is not part of what was sent', async () => {
+ const sent = 'a1 a2 a3 a4 b1 b2'
+ const { mgr, sendPaneKeys } = await manager({
+ plain: EMPTY,
+ styled: [EMPTY, rows(['b1 b2']), rows(['typed meanwhile'])]
+ })
+
+ const pending = mgr.interruptChat(NODE, 'claude', sent)
+ await vi.runAllTimersAsync()
+ const result = await pending
+
+ expect(sendPaneKeys.mock.calls.map((c) => c[1])).toEqual(['\x1b', '\x15'.repeat(4)])
+ expect(result).toEqual({ sent: true, restored: null })
+ })
+
+ it('stops when a burst leaves the box as it was, even for text that repeats', async () => {
+ const { mgr, sendPaneKeys } = await manager({ plain: EMPTY, styled: [EMPTY, draft('ok ok')] })
+
+ const pending = mgr.interruptChat(NODE, 'claude', 'ok ok ok ok')
+ await vi.runAllTimersAsync()
+ const result = await pending
+
+ expect(sendPaneKeys.mock.calls.map((c) => c[1])).toEqual(['\x1b', '\x15'.repeat(4)])
+ expect(result).toEqual({ sent: true, restored: null })
+ })
+
+ it('does not take back text that is only the START of what was sent', async () => {
+ const { mgr, sendPaneKeys } = await manager({ plain: EMPTY, styled: [draft('Write a')] })
+
+ 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 })
+ })
+})
+
+describe('endsEarlierIn', () => {
+ it('finds where the text ends, before the limit', async () => {
+ const { endsEarlierIn } = await import('./pty-manager')
+
+ expect(endsEarlierIn('a1a2b1b2c1c2', 'b1b2', 12)).toBe(8)
+ })
+
+ it('takes the latest place before the limit when the text repeats', async () => {
+ const { endsEarlierIn } = await import('./pty-manager')
+
+ expect(endsEarlierIn('abab', 'ab', 4)).toBe(2)
+ expect(endsEarlierIn('abab', 'ab', 2)).toBeNull()
+ })
+
+ it('is null for text that is not in it, or would not end earlier', async () => {
+ const { endsEarlierIn } = await import('./pty-manager')
+
+ expect(endsEarlierIn('a1a2b1b2', 'zz', 8)).toBeNull()
+ expect(endsEarlierIn('a1a2b1b2', 'a1a2b1b2', 8)).toBeNull()
+ })
})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 8d197ef6e..07bd8ec7c 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -9,6 +9,7 @@ import {
claudeScreenBlocksInput,
readClaudeComposer,
readClaudeDraft,
+ readClaudeDraftBox,
readClaudeScreen,
readClaudeSuggestion,
type ChatScreenRead
@@ -1193,6 +1194,15 @@ function screenGate(screen: string): ChatPromptBlocked | null {
* 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
+/** Bursts of Ctrl-U `takeBackInterruptedPrompt` sends at most; each must end the draft earlier. */
+export const INTERRUPT_CLEAR_MAX_ROUNDS = 20
+
+/** Where `text` ends in `whole` when it ends before `limit`, the latest such place; null if nowhere. */
+export function endsEarlierIn(whole: string, text: string, limit: number): number | null {
+ if (text.length >= limit) return null
+ const start = whole.lastIndexOf(text, limit - text.length - 1)
+ return start < 0 ? null : start + text.length
+}
/** 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). */
@@ -6884,11 +6894,11 @@ export class PtyManager {
* 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.
+ * that text (or, for a prompt taller than the box, its end), 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' }
@@ -6906,27 +6916,43 @@ export class PtyManager {
}
/** 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. */
+ * box, then clear it. true only when the box held 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> => {
+ type Box = { draft: string; rows: number } | null
+ const readBox = async (): Promise<Box> => readClaudeDraftBox(await this.captureStyledScreen(persistKey))
+ const until = async (done: (box: Box) => boolean, ms: number): Promise<Box> => {
const deadline = Date.now() + ms
for (;;) {
- const draft = await readDraft()
- if (done(draft) || Date.now() >= deadline) return draft
+ const box = await readBox()
+ if (done(box) || Date.now() >= deadline) return box
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.
+ let box = await until((b) => b !== null && b.draft !== '', INTERRUPT_RESTORE_WAIT_MS)
+ // A prompt taller than the box shows only its end (`readClaudeDraftBox`), so the end of what was
+ // sent counts as ours. Text that happens to be that end loses nothing: the whole prompt goes back.
+ if (box === null || box.draft === '' || !want.endsWith(box.draft)) return false
+ // MEASURED (2.1.319): one Ctrl-U clears the visual ROW the caret is on, so a long line wrapped onto
+ // several rows needs one per row, and at the start of a line one more joins it to the line above.
+ // Two per row on screen (never fewer than two per line sent) plus spares clears what the box shows;
+ // a Ctrl-U on an empty box does nothing. A box scrolled past its height stays full height and shows
+ // earlier rows, so this repeats while what is left still ends, caret and all, earlier in what was
+ // sent than it did before the round.
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)) === ''
+ let end = want.length
+ for (let round = 0; round < INTERRUPT_CLEAR_MAX_ROUNDS; round++) {
+ const before: string = box.draft
+ const cleared = await this.sendPaneKeys(persistKey, '\x15'.repeat(2 * Math.max(box.rows, lines) + 2))
+ if (!cleared.ok) return false
+ box = await until((b) => b === null || b.draft !== before, INTERRUPT_RESTORE_WAIT_MS)
+ if (box === null || box.draft === before) return false
+ if (box.draft === '') return true
+ const next = endsEarlierIn(want, box.draft, end)
+ if (next === null) return false
+ end = next
+ }
+ return false
}
/** The visible screen WITH its SGR, for `readClaudeComposer`: an ssh-project node's capture already
diff --git a/src/shared/agents/__fixtures__/claude/scrolled-draft-capture.json b/src/shared/agents/__fixtures__/claude/scrolled-draft-capture.json
new file mode 100644
index 000000000..bc1b5a8c7
--- /dev/null
+++ b/src/shared/agents/__fixtures__/claude/scrolled-draft-capture.json
@@ -0,0 +1,4 @@
+{
+ "_note": "Claude Code 2.1.319, `capture-pane -p -e` of a 60x40 pane holding a typed draft of `w1 w2 … w300` on one line. The box stops at 15 rows and scrolls: only w142 to w300 are on screen, with the caret after w300. Lines above the input box are dropped.",
+ "screen": "\u001b[38;5;244m────────────────────────────────────────────────────────────\n\u001b[39m❯ w142 w143 w144 w145 w146 w147 w148 w149 w150 w151 w152\n w153 w154 w155 w156 w157 w158 w159 w160 w161 w162 w163\n w164 w165 w166 w167 w168 w169 w170 w171 w172 w173 w174\n w175 w176 w177 w178 w179 w180 w181 w182 w183 w184 w185\n w186 w187 w188 w189 w190 w191 w192 w193 w194 w195 w196\n w197 w198 w199 w200 w201 w202 w203 w204 w205 w206 w207\n w208 w209 w210 w211 w212 w213 w214 w215 w216 w217 w218\n w219 w220 w221 w222 w223 w224 w225 w226 w227 w228 w229\n w230 w231 w232 w233 w234 w235 w236 w237 w238 w239 w240\n w241 w242 w243 w244 w245 w246 w247 w248 w249 w250 w251\n w252 w253 w254 w255 w256 w257 w258 w259 w260 w261 w262\n w263 w264 w265 w266 w267 w268 w269 w270 w271 w272 w273\n w274 w275 w276 w277 w278 w279 w280 w281 w282 w283 w284\n w285 w286 w287 w288 w289 w290 w291 w292 w293 w294 w295\n w296 w297 w298 w299 w300\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"
+}
diff --git a/src/shared/agents/claude-composer.test.ts b/src/shared/agents/claude-composer.test.ts
index 94cb221fa..fc7ed61d9 100644
--- a/src/shared/agents/claude-composer.test.ts
+++ b/src/shared/agents/claude-composer.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
-import { readClaudeComposer, readClaudeDraft } from './claude-screen'
+import { readClaudeComposer, readClaudeDraft, readClaudeDraftBox } from './claude-screen'
import capture from './__fixtures__/claude/composer-capture.json'
+import scrolled from './__fixtures__/claude/scrolled-draft-capture.json'
// Real captures (Claude Code 2.1.301, `capture-pane -p -e`) — see the fixture's `_note`. Issue #1144.
const S = capture.screens as Record<string, string>
@@ -87,3 +88,17 @@ describe('readClaudeDraft', () => {
expect(readClaudeDraft('')).toBeNull()
})
})
+
+describe('readClaudeDraftBox', () => {
+ it('counts the rows a one-line draft occupies on screen', () => {
+ expect(readClaudeDraftBox(S.draft)).toEqual({ draft: 'hebikgetest', rows: 1 })
+ })
+
+ it('reads only the end of a draft taller than the box, and the rows the box shows (2.1.319)', () => {
+ const tail = Array.from({ length: 159 }, (_, i) => `w${i + 142}`).join('')
+
+ const box = readClaudeDraftBox(scrolled.screen)
+
+ expect(box).toEqual({ draft: tail, rows: 15 })
+ })
+})
diff --git a/src/shared/agents/claude-screen.ts b/src/shared/agents/claude-screen.ts
index e2fdbb2b8..f224a4612 100644
--- a/src/shared/agents/claude-screen.ts
+++ b/src/shared/agents/claude-screen.ts
@@ -245,6 +245,16 @@ export function readClaudeComposer(styledScreen: string): ClaudeComposer {
* the draft read before typing, so that only costs a match when the placeholder ends the same way.
*/
export function readClaudeDraft(styledScreen: string): string | null {
+ return readClaudeDraftBox(styledScreen)?.draft ?? null
+}
+
+/**
+ * `readClaudeDraft` plus how many screen rows the input box shows. MEASURED on Claude Code 2.1.319:
+ * a long line wraps onto several rows, and the box stops growing at about half the pane's height
+ * (7 rows at 24, 15 at 40, 25 at 60) and scrolls, showing the end of the draft with the caret there.
+ * So `draft` can be only the tail of what the box holds, and `rows` only what is on screen.
+ */
+export function readClaudeDraftBox(styledScreen: string): { draft: string; rows: number } | null {
const styled = styledScreen.split(/\r?\n/)
const lines = styled.map((l) => l.replace(ANSI, '').trimEnd())
if (lines.every((l) => l === '')) return null
@@ -256,7 +266,7 @@ export function readClaudeDraft(styledScreen: string): string | null {
const from = i === box[0] + 1 && lines[i].startsWith('❯') ? 1 : 0
draft += undimmedText(styled[i], from)
}
- return draft.replace(/\s/g, '')
+ return { draft: draft.replace(/\s/g, ''), rows: box[1] - box[0] - 1 }
}
/**