Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(terminal): a superseded seed still wires input, and the resync repaint waits for the parser
enesb1669670586d
diff --git a/docs/team-presence.md b/docs/team-presence.mdindex 2ab9c91f4..d6236f938 100644--- a/docs/team-presence.md+++ b/docs/team-presence.md@@ -238,6 +238,19 @@ history seed would then write an even older screen on top of that. The resync hapass-through) and marks the seed **superseded**, so the seed writes nothing when its capture returns.Everything that arrives after the capture streams straight through, in order.+Two details that are easy to get wrong, and are pinned by tests in `terminal-config.test.ts`:++- **Superseded means "paint nothing", never "return".** The seed lives inside the spawn continuation,+ which still has to wire `onExit`, `term.onData` (**the keyboard input path**) and the+ `initialCommand` / cold-start agent resume *below* it. Returning early there yields a terminal that+ streams output and looks perfectly alive while silently accepting no input, forever. The decision+ is a pure helper — `seedPaint()` — whose result type has no abort member for exactly that reason.+- **The repaint's `reset()` is sequenced behind a write callback** (`repaintResync()`): `term.write()`+ is parsed asynchronously while `reset()` clears the buffer immediately, so an inline reset landing+ between the seed's (up to a megabyte of) history writes and xterm parsing them would clear an+ almost-empty buffer, let the stale history paint onto the cleared screen, and append the fresh+ capture *below* it.+### Typing attribution — and why it is server-side`cast()` used to discard the sender (`void uiId`). `pty:write` is routed through the sender-awarediff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex fff20bf1a..ffccc8fde 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -28,7 +28,9 @@ import {letterboxFor,markRecycled,recycleAction,+ repaintResync,reportedSize,+ seedPaint,setFittedSize,shouldApplyResync,stripTrailingNewline,@@ -855,17 +857,20 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN// seed would then write an even older screen over that. So the redraw SUPERSEDES both —// `gate.reset()` drops the queue (returning its bytes to the flow accounting) and switches// to pass-through, and `superseded` tells the seed its capture is now stale and to write- // nothing. Everything arriving after the capture streams straight through, in order.+ // nothing (it still wires the rest of the session — see seedPaint). Everything arriving+ // after the capture streams straight through, in order.+ //+ // `repaintResync` sequences the reset behind a write callback: writes already handed to+ // xterm (up to a megabyte of history seed) are parsed asynchronously, and an inline+ // `term.reset()` would clear the buffer before they land — see terminal-config.let superseded = falseif (transport.onResync) {cleanups.push(- transport.onResync(sid, (screen) => {- if (!shouldApplyResync(screen)) return+ transport.onResync(sid, (resyncScreen) => {+ if (!shouldApplyResync(resyncScreen)) returnsuperseded = truerelieve(gate.reset())- term.reset()- term.write(toXtermText(screen))- term.write('\r\n\x1b[90m── reconnected — earlier output skipped ──\x1b[0m\r\n')+ repaintResync(term, resyncScreen)}))}@@ -887,7 +892,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNif (replay === 'cold-snapshot') {const snapshot = await scrollbackPromiseif ((toreDown = onDisposed())) return- if (snapshot && !superseded) {+ if (seedPaint({ replay, superseded, snapshot }) === 'snapshot') {// The snapshot comes from `capture-pane -p`: LF-separated, no CR bytes. xterm runs// with convertEol:false, so writing it raw would render as a staircase.term.write(toXtermText(snapshot))@@ -907,11 +912,13 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN// node would come up with an empty scrollback.const history = await transport.captureHistory(id).catch(() => '')if ((toreDown = onDisposed())) return- // A resync repainted this screen from tmux while we were awaiting the capture — it is- // strictly newer than what we just fetched. Writing the history now would paint an- // older screen over it.- if (superseded) return- if (history) {+ // A resync that landed while we awaited the capture is strictly newer than what we just+ // fetched, so `seedPaint` says 'none' and we write nothing. It is a CONDITION, never a+ // `return`: everything below this try/finally — the onExit notice, `term.onData` (the+ // KEYBOARD INPUT path) and the initialCommand / agent-resume — must still be wired, or+ // the terminal streams output, looks alive, and silently accepts no input forever.+ const paint = seedPaint({ replay, superseded, history, screen })+ if (paint === 'history') {// The capture is byte-trimmed at the head, so it can begin mid-escape-sequence —// start the block from a known-clean SGR state rather than an arbitrary one.term.write('\x1b[0m')@@ -919,7 +926,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN// row below the last captured row, xterm would scroll, and tmux's redraw would// repaint that row again — one duplicated line at the seam.term.write(toXtermText(stripTrailingNewline(history)))- } else if (shouldApplyResync(screen)) {+ } else if (paint === 'create-screen' && screen) {// CO-ATTACH JOINER, history capture failed. A joiner also gets `fresh:false`, so it// lands here — and `captureHistory` is the source that WINS for it: it is a strict// superset of `PtyCreateResult.screen` (the same tmux pane, plus the scrollback abovediff --git a/src/renderer/terminal/terminal-config.test.ts b/src/renderer/terminal/terminal-config.test.tsindex 167c4b95c..ff260ca04 100644--- a/src/renderer/terminal/terminal-config.test.ts+++ b/src/renderer/terminal/terminal-config.test.ts@@ -11,13 +11,16 @@ import {letterboxFor,markRecycled,recycleAction,+ repaintResync,reportedSize,+ seedPaint,setFittedSize,shouldApplyResync,stripTrailingNewline,takeRecycled,toXtermText,xtermScrollback,+ RESYNC_NOTICE,XTERM_SCROLLBACK_MAX,XTERM_SCROLLBACK_MIN,type CopyShortcutEvent@@ -429,3 +432,108 @@ describe('copyKeyAction', () => {expect(copyKeyAction(ev({ ctrlKey: true }), false)).toBe('pass')})})++describe('seedPaint', () => {+ it('paints the snapshot on a cold restore, and nothing when there is none', () => {+ expect(seedPaint({ replay: 'cold-snapshot', superseded: false, snapshot: 'old' })).toBe(+ 'snapshot'+ )+ expect(seedPaint({ replay: 'cold-snapshot', superseded: false, snapshot: '' })).toBe('none')+ })++ it('paints tmux history on a warm reattach', () => {+ expect(seedPaint({ replay: 'warm-history', superseded: false, history: 'scrollback' })).toBe(+ 'history'+ )+ })++ it('falls back to the create-result screen for a joiner whose history capture came back empty', () => {+ expect(+ seedPaint({ replay: 'warm-history', superseded: false, history: '', screen: 'live screen' })+ ).toBe('create-screen')+ // history WINS when both are available — it is a strict superset of the screen, and painting+ // both would splice the same screen onto the canvas twice.+ expect(+ seedPaint({ replay: 'warm-history', superseded: false, history: 'hist', screen: 'scr' })+ ).toBe('history')+ // Neither: a blank-but-live terminal beats a wrongly painted one.+ expect(seedPaint({ replay: 'warm-history', superseded: false, history: '', screen: '' })).toBe(+ 'none'+ )+ })++ it('paints nothing for a parked terminal (its buffer is already correct)', () => {+ expect(+ seedPaint({ replay: 'none', superseded: false, snapshot: 'old', history: 'hist' })+ ).toBe('none')+ })++ it('a resync SUPERSEDES every seed: the decision is "write nothing", never "abort"', () => {+ // The whole point of the helper: a superseded seed still returns a PAINT decision, so the spawn+ // continuation carries on to wire onExit, term.onData (the keyboard input path) and the+ // initialCommand / agent resume. `none` is not a signal to return.+ for (const replay of ['cold-snapshot', 'warm-history', 'none'] as const) {+ expect(+ seedPaint({+ replay,+ superseded: true,+ snapshot: 'old snapshot',+ history: 'old history',+ screen: 'old screen'+ })+ ).toBe('none')+ }+ })+})++/** An xterm stand-in: `write` is PARSED ASYNCHRONOUSLY (callbacks fire on `parse()`). */+function fakeTerm(): {+ ops: string[]+ parse: () => void+ write(data: string, done?: () => void): void+ reset(): void+} {+ const queue: Array<() => void> = []+ return {+ ops: [] as string[],+ write(data: string, done?: () => void) {+ this.ops.push(`write:${data}`)+ if (done) queue.push(done)+ },+ reset() {+ this.ops.push('reset')+ },+ parse() {+ while (queue.length) queue.shift()!()+ }+ }+}++describe('repaintResync', () => {+ it('resets only AFTER the writes already queued have been parsed (never mid-flight)', () => {+ const term = fakeTerm()+ term.write('STALE HISTORY') // a warm-history seed, handed to xterm but not yet parsed+ repaintResync(term, 'FRESH')+ // Nothing repainted yet: an inline reset() would have cleared an almost-empty buffer and the+ // stale history would then parse on top of the cleared screen.+ expect(term.ops).toEqual(['write:STALE HISTORY', 'write:'])+ term.parse()+ expect(term.ops).toEqual([+ 'write:STALE HISTORY',+ 'write:',+ 'reset',+ 'write:FRESH',+ `write:${RESYNC_NOTICE}`+ ])+ const reset = term.ops.indexOf('reset')+ expect(reset).toBeGreaterThan(term.ops.indexOf('write:STALE HISTORY'))+ expect(reset).toBeLessThan(term.ops.indexOf('write:FRESH'))+ })++ it('CRLF-converts the capture (tmux emits bare LFs; xterm runs convertEol:false)', () => {+ const term = fakeTerm()+ repaintResync(term, 'a\nb')+ term.parse()+ expect(term.ops).toContain('write:a\r\nb')+ })+})diff --git a/src/renderer/terminal/terminal-config.ts b/src/renderer/terminal/terminal-config.tsindex bc8c98a8d..8e45670fd 100644--- a/src/renderer/terminal/terminal-config.ts+++ b/src/renderer/terminal/terminal-config.ts@@ -120,11 +120,6 @@ export function shouldApplyResync(screen: string | null | undefined): screen isreturn typeof screen === 'string' && screen.length > 0}-/**- * Pure decisions behind the xterm instance in `TerminalNode` — extracted so they can be- * tested without an xterm/DOM harness.- */-/** Hard cap on xterm's in-memory scrollback: the cost is per node and one canvas holds many. */export const XTERM_SCROLLBACK_MAX = 10000@@ -172,6 +167,71 @@ export function attachReplay(opts: {}/**+ * What a resolved seed PAINTS into the emulator:+ * - `snapshot` — the persisted cold-restore scrollback (with the "session restored" separator).+ * - `history` — tmux's own scrollback, pulled by `transport.captureHistory`.+ * - `create-screen` — the joiner fallback: the screen captured server-side inside `create()`, used+ * only when the history capture came back empty (tmux/ssh unavailable) — see "Painting the+ * joiner" in docs/team-presence.md.+ * - `none` — paint NOTHING.+ *+ * The decision is deliberately about PAINTING ONLY, and the type has no "abort" member, because the+ * spawn continuation that calls this must go on to do the rest of its job no matter what comes back:+ * subscribe `onExit`, subscribe `term.onData` (**the keyboard input path**) and send+ * `initialCommand` / the cold-start agent resume. A `superseded` seed (a `pty:resync` repainted this+ * screen from tmux while we awaited the capture, so our capture is now stale) therefore means "write+ * nothing", NOT "return": returning from the continuation would leave a terminal that streams output+ * and looks perfectly alive while silently accepting no input, forever.+ */+export type SeedPaint = 'snapshot' | 'history' | 'create-screen' | 'none'++/** What (if anything) the resolved seed should write. Never an instruction to stop. */+export function seedPaint(opts: {+ replay: AttachReplay+ /** A `pty:resync` landed while the seed was in flight — its screen is strictly newer than ours. */+ superseded: boolean+ /** The persisted scrollback snapshot (`cold-snapshot`), '' when there is none. */+ snapshot?: string | null+ /** tmux's scrollback (`warm-history`), '' when the capture failed or tmux was unreachable. */+ history?: string | null+ /** `PtyCreateResult.screen`: present (and non-empty) only for a joiner that did not resize. */+ screen?: string | null+}): SeedPaint {+ if (opts.replay === 'none' || opts.superseded) return 'none'+ if (opts.replay === 'cold-snapshot') return opts.snapshot ? 'snapshot' : 'none'+ if (opts.history) return 'history'+ return shouldApplyResync(opts.screen) ? 'create-screen' : 'none'+}++/** The slice of xterm the resync repaint drives (so it can be tested without a DOM). */+export interface ResyncTarget {+ write(data: string, done?: () => void): void+ reset(): void+}++/** The banner that marks the seam where a slow client's backlog was dropped. */+export const RESYNC_NOTICE = '\r\n\x1b[90m── reconnected — earlier output skipped ──\x1b[0m\r\n'++/**+ * Repaint a terminal from a `pty:resync` capture (the server dropped our backlog and redrew us from+ * tmux, so the capture IS the current screen and must REPLACE the buffer, not stack on top of it).+ *+ * The `reset()` is sequenced behind a zero-length write callback rather than called inline, because+ * `term.write()` is PARSED ASYNCHRONOUSLY while `reset()` clears the buffer IMMEDIATELY. The warm+ * reattach seed can hand xterm up to a megabyte of tmux history in one write; a resync landing after+ * those writes are issued but before the parser reaches them would reset an almost-empty buffer, let+ * the stale history parse onto the cleared screen, and append the fresh capture BELOW a full screen+ * of stale content — the exact splice the reset exists to prevent. Deferring the reset to a write+ * callback puts it after everything already queued has been parsed.+ */+export function repaintResync(term: ResyncTarget, screen: string): void {+ term.write('', () => {+ term.reset()+ term.write(toXtermText(screen))+ term.write(RESYNC_NOTICE)+ })+}+/*** Make text captured from tmux (`capture-pane`, LF-separated lines) safe to `term.write()`.* xterm runs with `convertEol: false` — a bare LF moves down but keeps the column, so raw capture