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 deferred resync repaint never touches a dead terminal
enes00c5af04ba3e
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex ffccc8fde..cb2e99b04 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -819,7 +819,14 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN// Bytes left the backlog (parsed by xterm, or dropped by a resync — see below). Both must// return the flow ticket, or a discarded queue would leave `pending` permanently high and// the source paused forever.+ // Both callers are DEFERRED (an xterm write callback, or a resync's gate reset), so both+ // can land after teardown — the write loop still runs the callbacks it holds even though+ // `cleanups` has unsubscribed everything and the session is killed. `life.dead` (flipped+ // before the teardown in BOTH paths: the effect cleanup and the park dispose) is the+ // authority: past it there is no session left to un-pause, and `transport.setFlow` would+ // address a dead one (RemoteTransport forwards to the relay unconditionally).const relieve = (bytes: number): void => {+ if (life.dead) returnpending -= bytesif (paused && pending < LOW_WATER) {paused = false@@ -862,7 +869,12 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN//// `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.+ // `term.reset()` would clear the buffer before they land — see terminal-config. That+ // deferral outlives teardown, so the repaint is gated on `!life.dead`: this listener is+ // unsubscribed and the xterm disposed, but a callback already inside xterm's write loop+ // still fires and would reset/write a disposed core. `life` is the session-scoped record+ // (shared with the park entry), so a PARK — which keeps the xterm and the PTY alive — does+ // not trip the guard and a resync arriving at a parked terminal still repaints it.let superseded = falseif (transport.onResync) {cleanups.push(@@ -870,7 +882,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNif (!shouldApplyResync(resyncScreen)) returnsuperseded = truerelieve(gate.reset())- repaintResync(term, resyncScreen)+ repaintResync(term, resyncScreen, () => !life.dead)}))}diff --git a/src/renderer/terminal/terminal-config.test.ts b/src/renderer/terminal/terminal-config.test.tsindex ff260ca04..816eb9f0b 100644--- a/src/renderer/terminal/terminal-config.test.ts+++ b/src/renderer/terminal/terminal-config.test.ts@@ -536,4 +536,51 @@ describe('repaintResync', () => {term.parse()expect(term.ops).toContain('write:a\r\nb')})++ it('touches NOTHING once the terminal is dead (the deferred reset outlives teardown)', () => {+ const term = fakeTerm()+ let dead = false+ repaintResync(term, 'FRESH', () => !dead)+ // Teardown: the node is destroyed while the zero-length write is still queued. The listener is+ // unsubscribed and the xterm disposed — but xterm's write loop still owns the callback.+ dead = true+ term.parse()+ // Only the zero-length probe write, which happened before teardown. No reset()/write() on a+ // disposed core (which throws inside xterm's async write loop).+ expect(term.ops).toEqual(['write:'])+ })++ it('still repaints while the terminal is alive (the guard is not a blanket no-op)', () => {+ const term = fakeTerm()+ repaintResync(term, 'FRESH', () => true)+ term.parse()+ expect(term.ops).toEqual(['write:', 'reset', 'write:FRESH', `write:${RESYNC_NOTICE}`])+ })++ it('coalesces back-to-back resyncs: only the LATEST capture is painted, once', () => {+ const term = fakeTerm()+ repaintResync(term, 'OLD')+ repaintResync(term, 'NEW') // lands before OLD's callback ran+ term.parse()+ // A stacked repaint would reset, paint OLD, reset, paint NEW — leaving OLD's parse output+ // spliced above NEW. Superseded captures are dropped instead: one reset, the newest screen.+ expect(term.ops).toEqual([+ 'write:',+ 'write:',+ 'reset',+ 'write:NEW',+ `write:${RESYNC_NOTICE}`+ ])+ })++ it('coalescing is per terminal and per round (a later, separate resync still paints)', () => {+ const term = fakeTerm()+ repaintResync(term, 'ONE')+ term.parse()+ repaintResync(term, 'TWO')+ term.parse()+ expect(term.ops.filter((o) => o === 'reset')).toHaveLength(2)+ expect(term.ops).toContain('write:ONE')+ expect(term.ops).toContain('write:TWO')+ })})diff --git a/src/renderer/terminal/terminal-config.ts b/src/renderer/terminal/terminal-config.tsindex 8e45670fd..3881b42e1 100644--- a/src/renderer/terminal/terminal-config.ts+++ b/src/renderer/terminal/terminal-config.ts@@ -212,6 +212,13 @@ export interface ResyncTarget {/** 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'+/**+ * The capture generation of the LAST repaint issued for a terminal, so a deferred repaint can tell+ * that a newer capture has superseded it (see `repaintResync`). Weak, and keyed by the xterm itself:+ * a disposed terminal takes its counter with it, and no node id has to be threaded through.+ */+const resyncGeneration = new WeakMap<ResyncTarget, number>()+/*** 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).@@ -223,9 +230,26 @@ export const RESYNC_NOTICE = '\r\n\x1b[90m── reconnected — earlier output* 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.+ *+ * Deferring it also hands the repaint to xterm's write loop, which outlives us in two ways the+ * inline reset never could — hence the two guards inside the callback:+ * - `alive` — teardown unsubscribes the resync listener and then DISPOSES the terminal, but a+ * callback already queued in the write loop still fires: reset()/write() would then run against a+ * disposed core and throw inside xterm's async loop. Pass the session's own liveness (`!life.dead`+ * in TerminalNode, the record shared with the park entry) — omitted, the repaint is unguarded, as+ * for a caller that owns the terminal outright.+ * - generation — back-to-back resyncs (a second backlog drop before the first repaint parsed) would+ * otherwise each reset and paint: capture #2's reset clears a buffer that #1's capture has not+ * parsed into yet, so #1 parses onto the fresh screen and #2 stacks below it. Only the LATEST+ * capture is painted; superseded ones write nothing (they are strictly older screens of the same+ * terminal, so there is nothing in them to lose).*/-export function repaintResync(term: ResyncTarget, screen: string): void {+export function repaintResync(term: ResyncTarget, screen: string, alive?: () => boolean): void {+ const generation = (resyncGeneration.get(term) ?? 0) + 1+ resyncGeneration.set(term, generation)term.write('', () => {+ if (alive && !alive()) return+ if (resyncGeneration.get(term) !== generation) return // a newer capture supersedes this oneterm.reset()term.write(toXtermText(screen))term.write(RESYNC_NOTICE)