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(terminal): a park during hydration no longer kills the session; no duplicated line at the seam

enesff1a22514255
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 9bd7dd07b..35d6b1861 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -21,7 +21,9 @@ import { parseOsc52 } from '../terminal/osc52'
import {
attachReplay,
createDataGate,
+ disposalAction,
isCopyShortcut,
+ stripTrailingNewline,
toXtermText,
xtermScrollback
} from '../terminal/terminal-config'
@@ -494,10 +496,26 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
sshRemote
})
.then(async ({ sessionId: sid, fresh, accountFallback: fellBack }) => {
- if (disposed) {
+ // Disposal while the spawn/seed was in flight is NOT necessarily a teardown: an unmount
+ // with a live session PARKS it (same xterm, same PTY client, same `cleanups` array), and
+ // killing it here would leave the node permanently dead once it is re-adopted. Only a real
+ // unmount/delete (nothing parked for this session) kills. Here `sessionId` was still null
+ // when the cleanup ran, so it could not have parked — but the same helper keeps both
+ // early-returns honest.
+ const onDisposed = (): boolean => {
+ const action = disposalAction({
+ disposed,
+ sessionId: sid,
+ parkedSessionId: parkedTerminals.get(id)?.sessionId
+ })
+ if (action !== 'teardown') return false
+ offData?.()
transport.kill(sid)
- return
+ return true
}
+ // Assigned below, once the data listener exists; before that there is nothing to detach.
+ let offData: (() => void) | undefined
+ if (onDisposed()) return
sessionId = sid
if (fellBack) setAccountFallback(true)
// Catch up a size change that landed while the spawn was in flight (resize() skips the
@@ -530,7 +548,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
// queues those chunks until the seed is written, then drains them in order. Queued bytes
// still count towards `pending`, so a flood during the gap pauses the source.
const gate = createDataGate(writeChunk)
- const offData = transport.onData(sid, (chunk) => {
+ offData = transport.onData(sid, (chunk) => {
pending += chunk.length
if (!paused && pending > HIGH_WATER) {
paused = true
@@ -543,48 +561,55 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
// persisted snapshot (the tmux session died with the machine), a warm reattach pulls
// tmux's own scrollback. Parked terminals get neither — their buffer is still correct
// and seeding it would duplicate content.
- const replay = attachReplay({
- parked: !!parked,
- fresh,
- hasInitialCommand: !!data.initialCommand
- })
- if (replay === 'cold-snapshot') {
- const snapshot = await scrollbackPromise
- if (disposed) {
- offData()
- transport.kill(sid)
- return
- }
- if (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))
- term.write('\r\n\x1b[90m── session restored (process ended by a restart) ──\x1b[0m\r\n')
- }
- } else if (replay === 'warm-history') {
- // Warm reattach: tmux redraws only the VISIBLE screen, so everything above it would be
- // missing from this fresh xterm. `captureHistory` includes the visible screen too —
- // tmux's redraw (\x1b[H\x1b[2J) erases exactly those lines in place, so it overwrites
- // the tail of what we write here instead of leaving a gap. This is the session's REAL
- // history, not a restore boundary — it gets no separator line.
- // Requested only now (not prefetched alongside the spawn): for an SSH node the remote
- // tmux is only reachable once `create()` has registered the session's ssh target — an
- // earlier call would silently fall through to the LOCAL tmux and return ''.
- const history = await window.nodeTerminal.pty.captureHistory(id).catch(() => '')
- if (disposed) {
- offData()
- transport.kill(sid)
- return
- }
- if (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')
- term.write(toXtermText(history))
+ // The gate MUST be opened whatever happens in here (`finally`): the data listener already
+ // exists, so a throw between it and `gate.open()` would queue chunks forever — the source
+ // pauses at the high-water mark and the terminal freezes silently and permanently. The
+ // only case that leaves it shut is a real teardown, where the xterm is disposed anyway.
+ let toreDown = false
+ try {
+ const replay = attachReplay({
+ parked: !!parked,
+ fresh,
+ hasInitialCommand: !!data.initialCommand
+ })
+ if (replay === 'cold-snapshot') {
+ const snapshot = await scrollbackPromise
+ if ((toreDown = onDisposed())) return
+ if (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))
+ term.write('\r\n\x1b[90m── session restored (process ended by a restart) ──\x1b[0m\r\n')
+ }
+ } else if (replay === 'warm-history') {
+ // Warm reattach: tmux redraws only the VISIBLE screen, so everything above it would be
+ // missing from this fresh xterm. `captureHistory` includes the visible screen too —
+ // tmux's redraw (\x1b[H\x1b[2J) erases exactly those lines in place, so it overwrites
+ // the tail of what we write here instead of leaving a gap. This is the session's REAL
+ // history, not a restore boundary — it gets no separator line.
+ // Requested only now (not prefetched alongside the spawn): for an SSH node the remote
+ // tmux is only reachable once `create()` has registered the session's ssh target — an
+ // earlier call would silently fall through to the LOCAL tmux and return ''.
+ const history = await window.nodeTerminal.pty.captureHistory(id).catch(() => '')
+ if ((toreDown = onDisposed())) return
+ if (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')
+ // capture-pane ends with a trailing newline: writing it would drop the cursor one
+ // 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)))
+ }
}
+ } catch (err) {
+ // Never let a seed failure freeze the terminal: the live stream matters more than the
+ // history. `finally` still opens the gate below.
+ console.error('[terminal] history seed failed', err)
+ } finally {
+ // Seed written — release the PTY output that arrived while it was in flight.
+ if (!toreDown) gate.open()
}
- // Seed written — release the PTY output that arrived while it was in flight.
- gate.open()
cleanups.push(
transport.onExit(sid, (code) => {
term.write(`\r\n\x1b[90m[process exited with code ${code}]\x1b[0m\r\n`)
diff --git a/src/renderer/terminal/terminal-config.test.ts b/src/renderer/terminal/terminal-config.test.ts
index c29c698f7..a43fc6f22 100644
--- a/src/renderer/terminal/terminal-config.test.ts
+++ b/src/renderer/terminal/terminal-config.test.ts
@@ -5,6 +5,8 @@ import {
isCopyShortcut,
attachReplay,
toXtermText,
+ stripTrailingNewline,
+ disposalAction,
createDataGate,
type CopyShortcutEvent
} from './terminal-config'
@@ -55,6 +57,57 @@ describe('toXtermText', () => {
})
})
+describe('stripTrailingNewline', () => {
+ it('drops exactly one trailing LF (tmux capture-pane ends with one)', () => {
+ expect(stripTrailingNewline('one\ntwo\n')).toBe('one\ntwo')
+ })
+
+ it('drops a trailing CRLF as a unit', () => {
+ expect(stripTrailingNewline('one\r\n')).toBe('one')
+ })
+
+ it('keeps blank lines that precede the final one (only ONE newline goes)', () => {
+ expect(stripTrailingNewline('one\n\n\n')).toBe('one\n\n')
+ })
+
+ it('leaves text without a trailing newline alone', () => {
+ expect(stripTrailingNewline('one\ntwo')).toBe('one\ntwo')
+ expect(stripTrailingNewline('')).toBe('')
+ })
+
+ it('composes with toXtermText so the seed leaves the cursor on the LAST captured row', () => {
+ // Writing the trailing newline would push the cursor one row down: xterm scrolls, the top row
+ // of the captured visible screen lands in scrollback, and tmux's redraw repaints it again —
+ // one duplicated line at the seam on every warm reattach.
+ expect(toXtermText(stripTrailingNewline('one\ntwo\n'))).toBe('one\r\ntwo')
+ })
+})
+
+describe('disposalAction', () => {
+ const parked = 'sess-1'
+
+ it('proceeds while the node is still mounted', () => {
+ expect(disposalAction({ disposed: false, sessionId: 'sess-1', parkedSessionId: undefined })).toBe('proceed')
+ })
+
+ it('continues the setup when the cleanup PARKED this very session', () => {
+ // Project switch during the hydration await: the park entry holds the same cleanups array and
+ // sessionId, so the session is alive and must be finished wiring — killing it here would leave
+ // a permanently dead node when the user switches back.
+ expect(disposalAction({ disposed: true, sessionId: 'sess-1', parkedSessionId: parked })).toBe('continue-parked')
+ })
+
+ it('tears down on a real unmount/delete (nothing parked)', () => {
+ expect(disposalAction({ disposed: true, sessionId: 'sess-1', parkedSessionId: undefined })).toBe('teardown')
+ expect(disposalAction({ disposed: true, sessionId: 'sess-1', parkedSessionId: null })).toBe('teardown')
+ })
+
+ it('tears down when the parked entry belongs to a different session', () => {
+ // Stale/other entry for this node id — this session is not the one being kept.
+ expect(disposalAction({ disposed: true, sessionId: 'sess-2', parkedSessionId: parked })).toBe('teardown')
+ })
+})
+
describe('createDataGate', () => {
it('queues chunks that arrive before the gate opens, then drains them in order', () => {
const written: string[] = []
diff --git a/src/renderer/terminal/terminal-config.ts b/src/renderer/terminal/terminal-config.ts
index 345355202..901b37202 100644
--- a/src/renderer/terminal/terminal-config.ts
+++ b/src/renderer/terminal/terminal-config.ts
@@ -49,6 +49,42 @@ export function toXtermText(text: string): string {
return text.replace(/\r?\n/g, '\r\n')
}
+/**
+ * Drop exactly ONE trailing newline from a tmux capture.
+ * `capture-pane -p -e -S -<n>` emits a trailing LF after its last line. Writing it would leave the
+ * cursor one row BELOW the last captured row: xterm scrolls, the topmost row of the captured
+ * visible screen is pushed into scrollback, and tmux's attach redraw (`\x1b[H\x1b[2J`) then
+ * repaints that same screen — so on every warm reattach the first visible row would appear twice.
+ * Strip on the RAW capture (LF-separated), before `toXtermText` turns the LFs into CRLFs.
+ */
+export function stripTrailingNewline(text: string): string {
+ return text.replace(/\r?\n$/, '')
+}
+
+/**
+ * What a spawn continuation must do when it finds the effect already cleaned up while an async
+ * seed (scrollback snapshot / tmux history) was in flight.
+ * - `proceed` — still mounted: carry on.
+ * - `continue-parked` — the cleanup PARKED this very session (the park entry holds the same live
+ * xterm, PTY client and `cleanups` array). Killing or unsubscribing here would leave the node
+ * permanently dead when it is re-adopted, so the setup must simply finish.
+ * - `teardown` — a real unmount/delete: nothing holds this session, so drop the data
+ * listener and kill the PTY client.
+ */
+export type DisposalAction = 'proceed' | 'continue-parked' | 'teardown'
+
+export function disposalAction(opts: {
+ /** The effect cleanup has run. */
+ disposed: boolean
+ /** The session this continuation is wiring up. */
+ sessionId: string
+ /** sessionId of the node's parked entry, if the cleanup parked one. */
+ parkedSessionId: string | null | undefined
+}): DisposalAction {
+ if (!opts.disposed) return 'proceed'
+ return opts.parkedSessionId === opts.sessionId ? 'continue-parked' : 'teardown'
+}
+
/** A gate that holds PTY chunks back until the emulator has been seeded. */
export interface DataGate {
/** Queue (while closed) or write straight through (once open). */