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): hydrate xterm scrollback from tmux history on warm reattach

enes45236ac3e74c
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 3ff3a4a52..dad94373b 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -170,7 +170,7 @@ function buildRealApi(client: RpcClient): Pick<NodeTerminalApi, 'pty' | 'workspa
readScrollback: (persistKey) =>
client.request(IPC.ptyReadScrollback, persistKey) as Promise<string>,
captureHistory: (persistKey: string) =>
- client.request(IPC.ptyCaptureHistory, persistKey).catch(() => '') as Promise<string>,
+ client.request(IPC.ptyCaptureHistory, persistKey) as Promise<string>,
sendText: (persistKey, text) =>
client.request(IPC.ptySendText, persistKey, text) as Promise<boolean>,
// No server handler — the session-name poll degrades to no adopted name.
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index e2fe36068..5aead216d 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -18,7 +18,7 @@ import { RemoteTransport } from '../terminal/remote-transport'
import type { TerminalTransport } from '../terminal/transport'
import { patchTerminalScale } from '../terminal/scale-fix'
import { parseOsc52 } from '../terminal/osc52'
-import { isCopyShortcut, xtermScrollback } from '../terminal/terminal-config'
+import { attachReplay, isCopyShortcut, toXtermText, xtermScrollback } from '../terminal/terminal-config'
import { FindBar } from '../components/FindBar'
import { IconSearch, IconChat } from '../components/icons'
import { NodeTags } from '../components/NodeTags'
@@ -501,11 +501,16 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
sentRows = term.rows
transport.resize(sid, term.cols, term.rows)
}
- // Cold restart: the tmux session (and anything that was running in it) is gone — replay
- // the last persisted scrollback so the user sees where they left off. Warm reattach
- // (`fresh` false) skips this: tmux redraws the live screen itself, so replaying would
- // duplicate it. Skipped on the very first open too (`fresh` true but initialCommand set).
- if (fresh && !data.initialCommand) {
+ // Seed the (fresh) emulator with the history it can't see: a cold restart replays the
+ // persisted snapshot (the tmux session died with the machine), a warm reattach pulls
+ // tmux's own scrollback above the visible screen. 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) {
transport.kill(sid)
@@ -515,6 +520,25 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
term.write(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` excludes that visible screen (`-E -1`),
+ // so hydrating cannot duplicate the redraw. 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) {
+ 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))
+ }
}
// Flow control: track xterm's unprocessed write backlog (bytes handed to
// term.write but not yet parsed). Past a high watermark we pause the source so
diff --git a/src/renderer/terminal/terminal-config.test.ts b/src/renderer/terminal/terminal-config.test.ts
index 2e819833a..69a61411a 100644
--- a/src/renderer/terminal/terminal-config.test.ts
+++ b/src/renderer/terminal/terminal-config.test.ts
@@ -1,5 +1,12 @@
import { describe, it, expect } from 'vitest'
-import { xtermScrollback, XTERM_SCROLLBACK_MAX, isCopyShortcut, type CopyShortcutEvent } from './terminal-config'
+import {
+ xtermScrollback,
+ XTERM_SCROLLBACK_MAX,
+ isCopyShortcut,
+ attachReplay,
+ toXtermText,
+ type CopyShortcutEvent
+} from './terminal-config'
const ev = (p: Partial<CopyShortcutEvent>): CopyShortcutEvent => ({
type: 'keydown',
@@ -12,6 +19,41 @@ const ev = (p: Partial<CopyShortcutEvent>): CopyShortcutEvent => ({
...p
})
+describe('attachReplay', () => {
+ it('replays the persisted snapshot on a cold start (tmux session gone)', () => {
+ expect(attachReplay({ parked: false, fresh: true, hasInitialCommand: false })).toBe('cold-snapshot')
+ })
+
+ it('hydrates from tmux history on a warm reattach (fresh xterm, live session)', () => {
+ expect(attachReplay({ parked: false, fresh: false, hasInitialCommand: false })).toBe('warm-history')
+ })
+
+ it('seeds nothing on a brand-new node (fresh session + launch command)', () => {
+ expect(attachReplay({ parked: false, fresh: true, hasInitialCommand: true })).toBe('none')
+ })
+
+ it('seeds nothing for a parked terminal — its buffer is already correct', () => {
+ // Both fresh values: an adopted xterm must never be seeded, or the content would double.
+ expect(attachReplay({ parked: true, fresh: false, hasInitialCommand: false })).toBe('none')
+ expect(attachReplay({ parked: true, fresh: true, hasInitialCommand: false })).toBe('none')
+ expect(attachReplay({ parked: true, fresh: true, hasInitialCommand: true })).toBe('none')
+ })
+})
+
+describe('toXtermText', () => {
+ it('turns tmux capture-pane LFs into CRLFs (xterm runs with convertEol off)', () => {
+ expect(toXtermText('one\ntwo\n')).toBe('one\r\ntwo\r\n')
+ })
+
+ it('leaves existing CRLFs alone', () => {
+ expect(toXtermText('one\r\ntwo')).toBe('one\r\ntwo')
+ })
+
+ it('keeps escape sequences untouched', () => {
+ expect(toXtermText('\x1b[31mred\x1b[0m\n')).toBe('\x1b[31mred\x1b[0m\r\n')
+ })
+})
+
describe('xtermScrollback', () => {
it('follows the tmux scrollback setting below the cap', () => {
expect(xtermScrollback(2000)).toBe(2000)
diff --git a/src/renderer/terminal/terminal-config.ts b/src/renderer/terminal/terminal-config.ts
index a1ea5b392..d9991d452 100644
--- a/src/renderer/terminal/terminal-config.ts
+++ b/src/renderer/terminal/terminal-config.ts
@@ -15,6 +15,40 @@ export function xtermScrollback(tmuxScrollback: number): number {
return Math.min(tmuxScrollback, XTERM_SCROLLBACK_MAX)
}
+/**
+ * What a freshly-created xterm has to be seeded with when its session resolves:
+ * - `cold-snapshot` — the tmux session is gone (first open after a reboot): replay the persisted
+ * scrollback snapshot, with a "session restored" separator.
+ * - `warm-history` — the tmux session is still alive but this xterm is new (app restart): tmux
+ * only redraws the VISIBLE screen, so pull everything above it from tmux's own history.
+ * - `none` — nothing to seed: a parked terminal keeps its buffer (seeding would duplicate
+ * it), and a brand-new node with an `initialCommand` has no history to restore.
+ */
+export type AttachReplay = 'cold-snapshot' | 'warm-history' | 'none'
+
+/** Which seeding (if any) applies to a terminal that just attached. */
+export function attachReplay(opts: {
+ /** The xterm instance was adopted from the park cache — its buffer is already correct. */
+ parked: boolean
+ /** The tmux session did not exist and was created by this attach. */
+ fresh: boolean
+ /** The node carries a one-shot launch command, i.e. it is being opened for the first time. */
+ hasInitialCommand: boolean
+}): AttachReplay {
+ if (opts.parked) return 'none'
+ if (!opts.fresh) return 'warm-history'
+ return opts.hasInitialCommand ? 'none' : 'cold-snapshot'
+}
+
+/**
+ * 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
+ * output would render as a staircase. Lone LFs become CRLF; existing CRLFs are left alone.
+ */
+export function toXtermText(text: string): string {
+ return text.replace(/\r?\n/g, '\r\n')
+}
+
/** The subset of a KeyboardEvent the copy-shortcut decision looks at. */
export interface CopyShortcutEvent {
type: string