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(terminal): a bounded input buffer during wake — nothing splices into the resume line

Claude Code44be547ebdc3
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 990933647..1963e4be7 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -115,6 +115,7 @@ import {
type ExitPhaseOutcome,
type ResumePhaseOutcome
} from '../terminal/agent-restart'
+import { WakeInputBuffer } from '../terminal/wake-input-buffer'
import { FindBar } from '../components/FindBar'
import { IconSearch, IconChat, IconMic, IconReload } from '../components/icons'
import { NodeLabels } from '../components/kanban/NodeLabels'
@@ -1281,6 +1282,14 @@ export function TerminalNode({
// sweep that landed in between, must not deliver a second launch line into the same pane.
const wakeInFlightRef = useRef(false)
const wakeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+ // A wake types the resume line into this pane un-KILL_LINE'd (its "most fragile moment"), and the
+ // keyboard path writes straight to the transport throughout. This bounded buffer HOLDS anything
+ // the human types between `beginWake` and the resume's confirmed submit, then flushes it in order
+ // (a `resumed` outcome) or drops it (any other) — so nothing splices into the resume line. See
+ // wake-input-buffer.ts; the keyboard interception is in `term.onData` below, the writer is the
+ // session-scoped `restartIo.write` published here so the wake `.then` (component body) can reach it.
+ const wakeInputBufferRef = useRef(new WakeInputBuffer())
+ const paneWriteRef = useRef<(data: string) => void>(() => {})
const wakeRef = useRef<(attempt?: number) => void>(() => {})
wakeRef.current = (attempt = 0): void => {
// A wake that could not run YET is retried a couple of times: at mount the spawn is still in
@@ -1298,9 +1307,15 @@ export function TerminalNode({
const fns = agentHibernateFns(id)
if (!fns) return retryLater() // no terminal here yet (mid-spawn, or an offscreen revive)
wakeInFlightRef.current = true
+ // Hold keyboard input from HERE — before the resume line's first byte — until the resume
+ // resolves. `beginWake` is idempotent, so a retry that re-enters keeps what is already held.
+ wakeInputBufferRef.current.beginWake()
void fns
.resume()
.then((outcome) => {
+ // Flush on a confirmed resume (the held keystrokes land after the resume line submitted),
+ // drop on anything else (`expired` — the pane became something we did not resume into).
+ wakeInputBufferRef.current.endWake(outcome === 'resumed', paneWriteRef.current)
if (outcome === 'resumed') {
useAgentStatus.getState().setHibernated(id, false)
return
@@ -1312,7 +1327,9 @@ export function TerminalNode({
})
.catch(() => {
// A transport that threw leaves the node hibernated (and the chip clickable). Reporting a
- // wake here would clear the badge over a pane nothing was typed into.
+ // wake here would clear the badge over a pane nothing was typed into — and the held input is
+ // dropped, never spliced into whatever the pane became.
+ wakeInputBufferRef.current.endWake(false, paneWriteRef.current)
})
.finally(() => {
wakeInFlightRef.current = false
@@ -2690,6 +2707,12 @@ export function TerminalNode({
// interrupt, so probe the cancelled turn (still-silent working → done). Exact
// match — arrow keys etc. arrive as multi-byte \x1b[… sequences.
if (showStatus && (input === '\x1b' || input === '\x03')) inferInterruptAfterSettle(id)
+ // While a wake is in flight, HOLD this input rather than write it: the resume line is
+ // sitting un-submitted in the pane and a keystroke would splice into it. The buffer is
+ // bounded — a `queueFull`/`buffered` verdict means "held, do not write". Flushed (or
+ // dropped) when the resume resolves; see `wakeInputBufferRef`. `passthrough` is the
+ // ordinary case and is byte-for-byte the old behaviour.
+ if (wakeInputBufferRef.current.offer(input).kind !== 'passthrough') return
transport.write(sid, input)
}).dispose
)
@@ -2820,6 +2843,11 @@ export function TerminalNode({
},
onData: (cb) => (sessionId && !life.dead ? transport.onData(sessionId, cb) : () => {})
}
+ // The wake buffer flushes held keystrokes through the SAME session-scoped, lifetime-gated write
+ // as the resume line — so a flush into a torn-down session no-ops instead of throwing. Published
+ // to the ref the wake `.then` (component body) reads; re-set on every mount, which is when a new
+ // `restartIo` closure captures a live `sessionId`/`life`.
+ paneWriteRef.current = restartIo.write
// Is there still a pane to restart in? A spawn in flight has no session yet; a real teardown
// flips `life.dead`; and a session another client DESTROYED (or one recycled with no
// replacement) is gone while this component happily stays mounted showing the overlay — the
diff --git a/src/renderer/terminal/wake-input-buffer.test.ts b/src/renderer/terminal/wake-input-buffer.test.ts
new file mode 100644
index 000000000..2f04087a6
--- /dev/null
+++ b/src/renderer/terminal/wake-input-buffer.test.ts
@@ -0,0 +1,109 @@
+import { describe, it, expect } from 'vitest'
+import { WakeInputBuffer, WAKE_BUFFER_MAX_CHARS } from './wake-input-buffer'
+
+/**
+ * The bounded wake input buffer, every edge driven — and each key assertion is mutation-checked in
+ * the source (revert the mechanism → red → restore) rather than only asserted here.
+ *
+ * The one property that matters is the timing: while a wake is in flight, NOTHING the human types
+ * reaches the pane; it is held until the resume line is confirmed submitted, and dropped if the
+ * wake never resumed. Everything below is that property, split by edge.
+ */
+
+/** Collect what the buffer decides to write, so a test can assert both order and timing. */
+function sink(): { writes: string[]; write: (d: string) => void } {
+ const writes: string[] = []
+ return { writes, write: (d) => writes.push(d) }
+}
+
+describe('WakeInputBuffer', () => {
+ it('passes input straight through when no wake is in flight', () => {
+ const b = new WakeInputBuffer()
+ expect(b.isWaking).toBe(false)
+ expect(b.offer('ls\r')).toEqual({ kind: 'passthrough' })
+ // Passthrough holds nothing — the ordinary terminal is untouched.
+ expect(b.bufferedChars).toBe(0)
+ })
+
+ it('HOLDS input during a wake and writes NOTHING until the resume is confirmed', () => {
+ const b = new WakeInputBuffer()
+ const s = sink()
+ b.beginWake()
+ expect(b.isWaking).toBe(true)
+ expect(b.offer('a')).toEqual({ kind: 'buffered', bufferedChars: 1 })
+ expect(b.offer('bc')).toEqual({ kind: 'buffered', bufferedChars: 3 })
+ // The whole point: not one byte has been written while the resume line is un-submitted.
+ expect(s.writes).toEqual([])
+ expect(b.bufferedChars).toBe(3)
+ })
+
+ it('flushes the held input IN ORDER once the wake resumed', () => {
+ const b = new WakeInputBuffer()
+ const s = sink()
+ b.beginWake()
+ b.offer('one')
+ b.offer('two')
+ b.offer('three')
+ const drain = b.endWake(true, s.write)
+ expect(drain).toEqual({ reason: 'flushed', chars: 11 })
+ // Order preserved, and only now — after the resume line submitted.
+ expect(s.writes).toEqual(['one', 'two', 'three'])
+ // The window is closed again: the buffer is inert.
+ expect(b.isWaking).toBe(false)
+ expect(b.bufferedChars).toBe(0)
+ expect(b.offer('later')).toEqual({ kind: 'passthrough' })
+ })
+
+ it('DROPS the held input to `expired` when the wake did not resume', () => {
+ const b = new WakeInputBuffer()
+ const s = sink()
+ b.beginWake()
+ b.offer('rm -rf /')
+ const drain = b.endWake(false, s.write)
+ // The pane became whatever it became; the held bytes are discarded, not spliced into it.
+ expect(drain).toEqual({ reason: 'expired', chars: 8 })
+ expect(s.writes).toEqual([])
+ expect(b.isWaking).toBe(false)
+ expect(b.bufferedChars).toBe(0)
+ })
+
+ it('refuses with `queueFull` past the bound and holds nothing more (no silent drop)', () => {
+ const b = new WakeInputBuffer(8)
+ const s = sink()
+ b.beginWake()
+ expect(b.offer('12345')).toEqual({ kind: 'buffered', bufferedChars: 5 })
+ // 5 + 4 = 9 > 8: the chunk is refused WHOLE, and the buffer keeps exactly what it had.
+ expect(b.offer('6789')).toEqual({ kind: 'queueFull', capacity: 8 })
+ expect(b.bufferedChars).toBe(5)
+ // A smaller chunk that still fits is still accepted — the refusal was of the chunk, not a latch.
+ expect(b.offer('67')).toEqual({ kind: 'buffered', bufferedChars: 7 })
+ // On resume only what was actually buffered is written; the refused chunk never appears.
+ b.endWake(true, s.write)
+ expect(s.writes).toEqual(['12345', '67'])
+ expect(s.writes.join('')).not.toContain('6789')
+ })
+
+ it('the bound is exact — a chunk landing on the boundary is accepted, one past it is not', () => {
+ const b = new WakeInputBuffer(4)
+ b.beginWake()
+ expect(b.offer('abcd')).toEqual({ kind: 'buffered', bufferedChars: 4 })
+ expect(b.offer('e')).toEqual({ kind: 'queueFull', capacity: 4 })
+ })
+
+ it('beginWake is idempotent — re-entering a wake does not drop what is already held', () => {
+ const b = new WakeInputBuffer()
+ const s = sink()
+ b.beginWake()
+ b.offer('held')
+ b.beginWake() // the retry path re-arms; it must not clear the buffer
+ expect(b.bufferedChars).toBe(4)
+ b.endWake(true, s.write)
+ expect(s.writes).toEqual(['held'])
+ })
+
+ it('the default bound is a sane, finite number', () => {
+ // A bound that is 0 or Infinity is not a bound; pin that the default is neither.
+ expect(WAKE_BUFFER_MAX_CHARS).toBeGreaterThan(0)
+ expect(Number.isFinite(WAKE_BUFFER_MAX_CHARS)).toBe(true)
+ })
+})
diff --git a/src/renderer/terminal/wake-input-buffer.ts b/src/renderer/terminal/wake-input-buffer.ts
new file mode 100644
index 000000000..81920f2f2
--- /dev/null
+++ b/src/renderer/terminal/wake-input-buffer.ts
@@ -0,0 +1,131 @@
+/**
+ * A BOUNDED INPUT BUFFER FOR THE WAKE WINDOW — nothing the human types splices into the resume line.
+ *
+ * ── THE FRAGILE MOMENT THIS CLOSES ──────────────────────────────────────────────────────────────
+ *
+ * Waking a hibernated node re-launches its conversation with the provider's own `--resume`
+ * (`agent-restart.ts` `performResumePhase`). Between the first byte of that launch line and its
+ * submit there is a window — `agent-restart.ts:216` calls the un-submitted resume line *"the pane's
+ * most fragile moment"* — in which anything typed is spliced INTO the command: a stray keystroke
+ * turns `claude --resume <sid>` into `claude --resume <sid>x`, and the conversation is lost.
+ *
+ * Today there is no buffer at all: the only protections are `wakeInFlightRef` (one wake at a time)
+ * and the `hibernated` re-read, neither of which touches the KEYBOARD path — `term.onData` writes
+ * straight to the transport throughout the wake. cmux solved the same problem with a bounded buffer
+ * (`TerminalPanel.swift:737-740`); this is that piece, pure and testable.
+ *
+ * ── WHAT IT DOES, AND WHICH WAY EACH EDGE FAILS ─────────────────────────────────────────────────
+ *
+ * - NOT waking → `passthrough`: the caller writes the input as it always did. The buffer is inert
+ * outside a wake, so the ordinary terminal is byte-for-byte unchanged.
+ * - WAKING → `buffered`: the input is HELD, in order, and released only once the resume line is
+ * confirmed submitted (a `resumed` outcome means exactly that — `performResumePhase` resolves
+ * after the delivery settles). Held, not written: writing it now is the splice.
+ * - WAKING and OVER THE BOUND → `queueFull`: an unbounded hold is a memory-DoS on a paste or a
+ * key-repeat that never ends, so the buffer refuses past `maxChars` and holds nothing more. The
+ * refusal is LOUD (a verdict the caller can surface), never a silent drop — the same discipline
+ * the message queue applies to its own bound.
+ * - the wake ENDS resumed → `flushed`: the held input is written, in the order it arrived, into a
+ * pane whose resume line has already gone.
+ * - the wake ENDS any other way → `expired`: a wake that timed out or failed left the pane as
+ * whatever it became (a stranger's shell, a dead session), so the held bytes are DISCARDED rather
+ * than spliced into it. Dropping the buffer is the safe direction; writing it is the bug.
+ *
+ * `queueFull` / `expired` are named to match the message queue's outcomes on purpose: a human at a
+ * waking pane and a message to a busy agent hit the same two walls (a full buffer, a lapsed wait),
+ * and one vocabulary for both keeps the two features legible together.
+ *
+ * Pure: no DOM, no IPC, no timers. The write is injected, so the whole state machine is exercised
+ * without a terminal — `wake-input-buffer.test.ts` drives every edge and mutation-checks each.
+ */
+
+/** The most keyboard input (code units) held during one wake before the buffer refuses. Small on
+ * purpose: a wake is seconds, and the only legitimate content is what a human types in that window;
+ * anything larger is a paste or a stuck key, which `queueFull` is the honest answer to. */
+export const WAKE_BUFFER_MAX_CHARS = 4096
+
+/** The verdict on one offered chunk. `passthrough` is the only one that tells the caller to write. */
+export type WakeOfferVerdict =
+ | { kind: 'passthrough' }
+ | { kind: 'buffered'; bufferedChars: number }
+ | { kind: 'queueFull'; capacity: number }
+
+/** Why the buffer emptied: `flushed` wrote its contents, `expired` discarded them. */
+export type WakeDrainReason = 'flushed' | 'expired'
+
+export interface WakeDrainResult {
+ reason: WakeDrainReason
+ /** How much was held when the wake ended — for the trace, never the content itself. */
+ chars: number
+}
+
+/**
+ * One node's wake input buffer. Constructed per terminal node and driven by the node's wake
+ * choreography: `beginWake()` when a resume starts, `offer()` on every keystroke, `endWake()` when
+ * the resume resolves.
+ */
+export class WakeInputBuffer {
+ private waking = false
+ private held: string[] = []
+ private chars = 0
+
+ constructor(private readonly maxChars: number = WAKE_BUFFER_MAX_CHARS) {}
+
+ /** A wake for this node has started — hold keyboard input from here until `endWake`. Idempotent:
+ * a second `beginWake` inside one wake (the retry path re-enters) must not drop what is held. */
+ beginWake(): void {
+ this.waking = true
+ }
+
+ /** Is a wake currently holding input? */
+ get isWaking(): boolean {
+ return this.waking
+ }
+
+ /** How much is held right now (code units). For assertions and the trace, not the content. */
+ get bufferedChars(): number {
+ return this.chars
+ }
+
+ /**
+ * Offer one chunk of keyboard input. Returns the caller's instruction:
+ * - `passthrough` — not waking; the caller writes it to the transport as usual.
+ * - `buffered` — held; the caller writes NOTHING (writing is the splice this exists to stop).
+ * - `queueFull` — over the bound; held nothing, and the caller must not write it either. The
+ * partial chunk is refused whole rather than truncated: a half-written escape sequence is worse
+ * than a dropped one, and the caller learns the buffer is full.
+ */
+ offer(input: string): WakeOfferVerdict {
+ if (!this.waking) return { kind: 'passthrough' }
+ if (this.chars + input.length > this.maxChars) return { kind: 'queueFull', capacity: this.maxChars }
+ this.held.push(input)
+ this.chars += input.length
+ return { kind: 'buffered', bufferedChars: this.chars }
+ }
+
+ /**
+ * The wake resolved. Ends the buffering window and empties the buffer.
+ *
+ * - `resumed === true`: the resume line is confirmed submitted, so the held input is written
+ * through `write`, IN ORDER, into the pane it belongs to. This is the only path that writes.
+ * - `resumed === false`: the wake did not resume the conversation (it timed out, the pane became
+ * something else, or the transport threw). The held bytes are DROPPED — splicing them into a
+ * pane we did not resume into is the failure mode this whole module exists to prevent.
+ *
+ * Returns what happened and how much, so the caller can trace an `expired` drain (a non-silent
+ * drop, like the message queue's TTL expiry). Safe to call when not waking: it is then a no-op
+ * that reports `flushed` of 0.
+ */
+ endWake(resumed: boolean, write: (data: string) => void): WakeDrainResult {
+ const held = this.held
+ const chars = this.chars
+ this.held = []
+ this.chars = 0
+ this.waking = false
+ if (resumed) {
+ for (const chunk of held) write(chunk)
+ return { reason: 'flushed', chars }
+ }
+ return { reason: 'expired', chars }
+ }
+}