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
feat(terminal): cold-restore terminals after a machine reboot
enes26798c4c955b
diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.tsindex a69ca881e..4b68f19ce 100644--- a/src/main/pty-manager.ts+++ b/src/main/pty-manager.ts@@ -6,9 +6,20 @@ import { promisify } from 'util'import { app, ipcMain, webContents } from 'electron'import * as pty from 'node-pty'import { IPC } from '../shared/ipc'-import { DEFAULT_SETTINGS, type PtyCreateOptions, type Settings } from '../shared/types'+import {+ DEFAULT_SETTINGS,+ type PtyCreateOptions,+ type PtyCreateResult,+ type Settings+} from '../shared/types'import { hookServer } from './agents/hook-server'import { TMUX_SOCKET, sessionName } from './tmux-naming'+import { writeScrollback, readScrollback, deleteScrollback } from './scrollback-store'++// How often we snapshot a live tmux session's scrollback to disk, so a machine reboot (which+// kills the tmux server) can still replay recent output on cold restart. A final snapshot also+// runs on detach; the interval covers an ungraceful power loss between detaches.+const SCROLLBACK_SNAPSHOT_MS = 15_000// Async exec for tmux side-calls (capture / send-keys / kill-session) so they never block// the main event loop — a synchronous capture-pane of a large scrollback would stall every@@ -99,6 +110,10 @@ interface Session {buf: string[]bufBytes: numberflushTimer: ReturnType<typeof setTimeout> | null+ /** Node id this session persists under (when tmux-backed) — used for scrollback snapshots. */+ persistKey?: string+ /** Periodic scrollback-to-disk snapshot timer (tmux-backed sessions only). */+ snapshotTimer: ReturnType<typeof setInterval> | null}/** Sinks for a detached session whose output is served somewhere other than the renderer@@ -161,8 +176,9 @@ export class PtyManager {}registerIpc(): void {- ipcMain.handle(IPC.ptyCreate, (event, options: PtyCreateOptions) =>- this.create(event.sender.id, options)+ ipcMain.handle(+ IPC.ptyCreate,+ (event, options: PtyCreateOptions): PtyCreateResult => this.create(event.sender.id, options))ipcMain.on(IPC.ptyWrite, (_event, sessionId: string, data: string) =>this.write(sessionId, data)@@ -175,13 +191,37 @@ export class PtyManager {)ipcMain.on(IPC.ptyKill, (_event, sessionId: string) => this.kill(sessionId))ipcMain.on(IPC.ptyDestroy, (_event, persistKey: string) => this.destroySession(persistKey))+ ipcMain.handle(IPC.ptyReadScrollback, (_event, persistKey: string) =>+ readScrollback(persistKey)+ )ipcMain.handle(IPC.ptySendText, (_event, persistKey: string, text: string) =>this.sendText(persistKey, text))}- private create(webContentsId: number, options: PtyCreateOptions): string {- return this.spawnSession(options, webContentsId, undefined)+ private create(webContentsId: number, options: PtyCreateOptions): PtyCreateResult {+ // A tmux-backed session is "fresh" (cold start) when no live session exists to reattach to+ // — i.e. first open, or after a machine reboot killed the tmux server. Plain (non-tmux)+ // sessions are always fresh: they have no cross-restart continuity. The renderer uses this+ // to decide whether to replay the persisted scrollback and re-launch a resumable agent.+ const tmuxBacked =+ !!this.tmuxPath && this.getSettings().tmuxEnabled && !!options.persistKey+ const fresh = tmuxBacked ? !this.tmuxSessionExists(options.persistKey as string) : true+ const sessionId = this.spawnSession(options, webContentsId, undefined)+ return { sessionId, fresh }+ }++ /** Whether a tmux session for this node id currently exists (server alive + session present). */+ private tmuxSessionExists(persistKey: string): boolean {+ if (!this.tmuxPath) return false+ try {+ execFileSync(this.tmuxPath, ['-L', TMUX_SOCKET, 'has-session', '-t', sessionName(persistKey)], {+ stdio: 'ignore'+ })+ return true+ } catch {+ return false+ }}/**@@ -314,6 +354,9 @@ export class PtyManager {env})+ // tmux-backed sessions snapshot their scrollback to disk periodically so a machine reboot+ // (which kills the tmux server) can still replay recent output on cold restart.+ const tmuxBacked = !!(this.tmuxPath && settings.tmuxEnabled && options.persistKey)const session: Session = {proc,webContentsId,@@ -321,13 +364,22 @@ export class PtyManager {onExit: sinks?.onExit,buf: [],bufBytes: 0,- flushTimer: null+ flushTimer: null,+ persistKey: tmuxBacked ? options.persistKey : undefined,+ snapshotTimer: null+ }+ if (tmuxBacked && options.persistKey) {+ const key = options.persistKey+ session.snapshotTimer = setInterval(() => {+ void this.snapshotScrollback(key)+ }, SCROLLBACK_SNAPSHOT_MS)}this.sessions.set(sessionId, session)proc.onData((data) => this.queueData(sessionId, session, data))proc.onExit(({ exitCode }) => {+ if (session.snapshotTimer) clearInterval(session.snapshotTimer)this.flush(sessionId, session) // deliver any buffered output before the exit signalif (session.onExit) {session.onExit(exitCode)@@ -404,6 +456,10 @@ export class PtyManager {const session = this.sessions.get(sessionId)if (!session) returnif (session.flushTimer) clearTimeout(session.flushTimer)+ if (session.snapshotTimer) clearInterval(session.snapshotTimer)+ // Final snapshot on detach (node unmount / app quit) so the very latest scrollback survives+ // a reboot. The tmux session itself keeps running, so this only races a same-instant capture.+ if (session.persistKey) void this.snapshotScrollback(session.persistKey)session.proc.kill()this.sessions.delete(sessionId)}@@ -426,6 +482,24 @@ export class PtyManager {}}+ /**+ * Snapshot a node's recent scrollback (with colors, `-e`) to disk for cold-restart replay.+ * Best-effort: a missing session / unavailable tmux just leaves the prior snapshot in place.+ */+ private async snapshotScrollback(persistKey: string): Promise<void> {+ if (!this.tmuxPath) return+ try {+ const { stdout } = await runAsync(+ this.tmuxPath,+ ['-L', TMUX_SOCKET, 'capture-pane', '-p', '-e', '-t', sessionName(persistKey), '-S', '-1500'],+ { encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 }+ )+ if (stdout) writeScrollback(persistKey, stdout)+ } catch {+ // session gone / tmux unavailable — keep the last good snapshot+ }+ }+/*** Send literal text followed by Enter into a node's tmux session (e.g. a slash command).* Works whether or not a client is attached. Returns false if tmux is unavailable or the@@ -446,6 +520,8 @@ export class PtyManager {/** Permanently end a node's persistent tmux session (called when the user closes it). */async destroySession(persistKey: string): Promise<void> {+ // The node is gone for good — drop its cold-restore snapshot too.+ deleteScrollback(persistKey)if (!this.tmuxPath) returntry {await runAsync(this.tmuxPath, ['-L', TMUX_SOCKET, 'kill-session', '-t', sessionName(persistKey)])@@ -461,6 +537,10 @@ export class PtyManager {killAll(): void {for (const session of this.sessions.values()) {if (session.flushTimer) clearTimeout(session.flushTimer)+ if (session.snapshotTimer) clearInterval(session.snapshotTimer)+ // Best-effort final scrollback snapshot on quit so a reboot can replay it. Fire-and-forget:+ // the tmux server (and the snapshot capture against it) outlives this process.+ if (session.persistKey) void this.snapshotScrollback(session.persistKey)session.proc.kill()}this.sessions.clear()diff --git a/src/main/scrollback-store.ts b/src/main/scrollback-store.tsnew file mode 100644index 000000000..208ed5c22--- /dev/null+++ b/src/main/scrollback-store.ts@@ -0,0 +1,64 @@+import fs from 'fs'+import path from 'path'+import { createHash } from 'crypto'+import { app } from 'electron'++// On a machine reboot the tmux server dies, so the live scrollback is lost. We persist a+// byte-capped snapshot of each terminal's recent output to disk while it's running and replay+// it into xterm on a cold restart, so the user sees where they left off (REF-style cold+// restore). Warm reattach (app restart, tmux alive) ignores the snapshot — tmux redraws.++const DIR_NAME = 'terminal-scrollback'+// Trailing bytes we keep / replay. Enough for a few screens of context without bloating disk+// or stalling the renderer on replay.+const MAX_BYTES = 256 * 1024++function dir(): string {+ return path.join(app.getPath('userData'), DIR_NAME)+}++// persistKey is a node id (uuid-ish) but may contain arbitrary characters; hash it to a safe,+// fixed-length filename.+function snapshotPath(persistKey: string): string {+ const hash = createHash('sha256').update(persistKey).digest('hex').slice(0, 32)+ return path.join(dir(), `${hash}.bin`)+}++/** Keep only the trailing `MAX_BYTES`, not splitting a UTF-8 sequence at the cut point. */+function trailing(data: string): Buffer {+ const bytes = Buffer.from(data, 'utf-8')+ if (bytes.length <= MAX_BYTES) return bytes+ let start = bytes.length - MAX_BYTES+ // advance past any continuation bytes (0b10xxxxxx) so we start on a code-point boundary+ while (start < bytes.length && (bytes[start] & 0xc0) === 0x80) start+++ return bytes.subarray(start)+}++export function writeScrollback(persistKey: string, data: string): void {+ if (!data) return+ try {+ fs.mkdirSync(dir(), { recursive: true })+ const file = snapshotPath(persistKey)+ const tmp = `${file}.tmp`+ fs.writeFileSync(tmp, trailing(data))+ fs.renameSync(tmp, file)+ } catch {+ // best-effort: a failed snapshot just means no cold-restore replay for this node+ }+}++export function readScrollback(persistKey: string): string {+ try {+ return fs.readFileSync(snapshotPath(persistKey), 'utf-8')+ } catch {+ return ''+ }+}++export function deleteScrollback(persistKey: string): void {+ try {+ fs.rmSync(snapshotPath(persistKey), { force: true })+ } catch {+ // ignore+ }+}diff --git a/src/preload/index.ts b/src/preload/index.tsindex 273c0ef5c..4bbf53253 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -51,6 +51,7 @@ const api: NodeTerminalApi = {generateGroupName: (memberKeys, cwd) =>ipcRenderer.invoke(IPC.ptyGenerateGroupName, memberKeys, cwd),capture: (persistKey, full) => ipcRenderer.invoke(IPC.ptyCapture, persistKey, full),+ readScrollback: (persistKey) => ipcRenderer.invoke(IPC.ptyReadScrollback, persistKey),sendText: (persistKey, text) => ipcRenderer.invoke(IPC.ptySendText, persistKey, text),onData: (sessionId, listener) => {const channel = IPC.ptyData(sessionId)diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex f90988986..dc5efea7a 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -27,7 +27,7 @@ import { useSettings } from '../state/settings'import { useAgentStatus } from '../state/agentStatus'import { useAgentNodes } from '../state/agentNodes'import { COLLAPSED_HEIGHT, NODE_COLORS, type CanvasNode } from '../state/workspace'-import { hasHooks, canRecur, canContextLink, hasUsage, canChat, agentConfig, type AgentId } from '@shared/agents/config'+import { hasHooks, canRecur, canContextLink, hasUsage, canChat, canResume, resumeCommand, agentConfig, type AgentId } from '@shared/agents/config'import { buildSshArgs, type SshConnection } from '@shared/ssh'/** Backslash-escape shell-special characters, like a native terminal does on file drop. */@@ -234,6 +234,10 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN}const ssh = data.ssh as SshConnection | undefined+ // Prefetch the persisted scrollback in parallel with the spawn so it's ready to replay the+ // instant the session resolves (a cold restart after a reboot recreates the tmux session+ // empty — see the `fresh` handling below). Cheap no-op ('') when there's no snapshot.+ const scrollbackPromise = window.nodeTerminal.pty.readScrollback(id).catch(() => '')transport.create({cols: term.cols,@@ -244,12 +248,27 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNpersistKey: id,agentId: data.agentId})- .then((sid) => {+ .then(async ({ sessionId: sid, fresh }) => {if (disposed) {transport.kill(sid)return}sessionId = sid+ // 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) {+ const snapshot = await scrollbackPromise+ if (disposed) {+ transport.kill(sid)+ return+ }+ if (snapshot) {+ term.write(snapshot)+ term.write('\r\n\x1b[90m── session restored (process ended by a restart) ──\x1b[0m\r\n')+ }+ }// 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// a flood can't grow this buffer without bound; we resume once it drains.@@ -279,10 +298,18 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN}))cleanups.push(term.onData((input) => transport.write(sid, input)).dispose)- // Run a one-shot command on first open (e.g. "gh auth login"), then forget it.+ // Run a one-shot command on first open (e.g. "gh auth login" or the agent CLI), then+ // forget it.if (data.initialCommand) {transport.write(sid, `${data.initialCommand}\n`)updateNodeData(id, { initialCommand: undefined })+ } else if (fresh && agentId && canResume(agentId)) {+ // Cold restart of an agent node: the live agent is gone, so re-launch it. Resume the+ // prior conversation by its session id (known from hooks) when we have one; otherwise+ // start the agent fresh. Plain terminals get nothing here — just the restored shell.+ const priorId = useAgentStatus.getState().byId[id]?.sessionId+ const cmd = (priorId && resumeCommand(agentId, priorId)) || agentConfig(agentId)?.launchCmd+ if (cmd) transport.write(sid, `${cmd}\n`)}})diff --git a/src/renderer/terminal/local-transport.ts b/src/renderer/terminal/local-transport.tsindex 2224487fe..8f1dfe105 100644--- a/src/renderer/terminal/local-transport.ts+++ b/src/renderer/terminal/local-transport.ts@@ -1,4 +1,4 @@-import type { PtyCreateOptions } from '@shared/types'+import type { PtyCreateOptions, PtyCreateResult } from '@shared/types'import type { TerminalTransport } from './transport'/**@@ -11,7 +11,7 @@ export class LocalTransport implements TerminalTransport {return window.nodeTerminal.pty}- create(options: PtyCreateOptions): Promise<string> {+ create(options: PtyCreateOptions): Promise<PtyCreateResult> {return this.pty.create(options)}diff --git a/src/renderer/terminal/remote-transport.ts b/src/renderer/terminal/remote-transport.tsindex 2dec5b99b..4087a783d 100644--- a/src/renderer/terminal/remote-transport.ts+++ b/src/renderer/terminal/remote-transport.ts@@ -1,4 +1,4 @@-import type { PtyCreateOptions } from '@shared/types'+import type { PtyCreateOptions, PtyCreateResult } from '@shared/types'import type { TerminalTransport } from './transport'/**@@ -20,8 +20,11 @@ export class RemoteTransport implements TerminalTransport {return window.nodeTerminal.remoteClient}- create(options: PtyCreateOptions): Promise<string> {- return this.client.create(this.connectionId, options)+ async create(options: PtyCreateOptions): Promise<PtyCreateResult> {+ const sessionId = await this.client.create(this.connectionId, options)+ // Cold-restore (scrollback replay / agent resume) is the host's responsibility; a mirroring+ // client must never re-launch or replay, so it always reports a warm (non-fresh) attach.+ return { sessionId, fresh: false }}write(sessionId: string, data: string): void {diff --git a/src/renderer/terminal/transport.ts b/src/renderer/terminal/transport.tsindex dad01a6ec..e3409f0a5 100644--- a/src/renderer/terminal/transport.ts+++ b/src/renderer/terminal/transport.ts@@ -1,4 +1,4 @@-import type { PtyCreateOptions } from '@shared/types'+import type { PtyCreateOptions, PtyCreateResult } from '@shared/types'/*** Abstraction over the terminal session layer.@@ -9,7 +9,7 @@ import type { PtyCreateOptions } from '@shared/types'* the same interface, so remote access can be added without changing the UI.*/export interface TerminalTransport {- create(options: PtyCreateOptions): Promise<string>+ create(options: PtyCreateOptions): Promise<PtyCreateResult>write(sessionId: string, data: string): voidresize(sessionId: string, cols: number, rows: number): void/** Flow control: pause (false) / resume (true) the source when the terminal is backed up. */diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.tsindex bbda06fb9..2a6067a5c 100644--- a/src/shared/agents/config.ts+++ b/src/shared/agents/config.ts@@ -71,3 +71,29 @@ export const canTransferFrom = (id: AgentId): boolean => includes(TRANSFER_SOURC// Returns the builtin config for an id, or undefined for custom/unknown agents.export const agentConfig = (id: AgentId): AgentConfig | undefined =>(AGENT_CONFIG as Record<string, AgentConfig>)[id]++// Session ids are interpolated into a shell command line (written into the live shell on a+// cold restart), so accept only the safe charset agents actually use (UUIDs etc.) — never a+// flag-like or metacharacter-bearing value.+const SAFE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/++/**+ * The command that resumes a resumable agent's prior conversation by its provider session id.+ * Used on a cold restart (machine reboot) where the tmux session — and the live agent — are+ * gone, so the conversation must be reconstructed via the agent CLI's own `--resume`.+ * Returns null for non-resumable/custom agents or an unsafe/empty session id.+ */+export function resumeCommand(id: AgentId, sessionId: string): string | null {+ if (!canResume(id)) return null+ const sid = sessionId.trim()+ if (!sid || !SAFE_SESSION_ID.test(sid)) return null+ switch (id) {+ case 'codex':+ return `codex resume ${sid}`+ case 'claude':+ case 'gemini':+ return `${id} --resume ${sid}`+ default:+ return null+ }+}diff --git a/src/shared/agents/resume.test.ts b/src/shared/agents/resume.test.tsnew file mode 100644index 000000000..8f6da72f7--- /dev/null+++ b/src/shared/agents/resume.test.ts@@ -0,0 +1,32 @@+import { describe, it, expect } from 'vitest'+import { resumeCommand } from './config'++describe('resumeCommand', () => {+ it('builds claude resume', () => {+ expect(resumeCommand('claude', 'abc-123')).toBe('claude --resume abc-123')+ })++ it('builds codex resume (subcommand form)', () => {+ expect(resumeCommand('codex', 'abc-123')).toBe('codex resume abc-123')+ })++ it('builds gemini resume', () => {+ expect(resumeCommand('gemini', 'abc-123')).toBe('gemini --resume abc-123')+ })++ it('returns null for a non-resumable / custom agent', () => {+ expect(resumeCommand('custom:xyz', 'abc-123')).toBeNull()+ })++ it('returns null when the session id is missing or empty', () => {+ expect(resumeCommand('claude', '')).toBeNull()+ expect(resumeCommand('claude', ' ')).toBeNull()+ })++ it('rejects an unsafe session id (shell metacharacters / flag-like)', () => {+ expect(resumeCommand('claude', '-rf /')).toBeNull()+ expect(resumeCommand('claude', 'a; rm -rf /')).toBeNull()+ expect(resumeCommand('claude', 'a$(whoami)')).toBeNull()+ expect(resumeCommand('claude', 'a b')).toBeNull()+ })+})diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 3b0e11cba..e1b3ad39a 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -10,6 +10,7 @@ export const IPC = {ptyGenerateName: 'pty:generate-name',ptyGenerateGroupName: 'pty:generate-group-name',ptyCapture: 'pty:capture',+ ptyReadScrollback: 'pty:read-scrollback',ptySendText: 'pty:send-text',claudeReadTranscript: 'claude:read-transcript',chatReadTranscript: 'chat:read-transcript',diff --git a/src/shared/types.ts b/src/shared/types.tsindex 9b3163dc1..93c42e05c 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -24,6 +24,17 @@ export interface PtyCreateOptions {agentId?: AgentId}+/**+ * Result of creating a PTY session. `fresh` distinguishes a tmux session that had to be+ * created anew (cold start — e.g. after a machine reboot killed the tmux server) from a+ * reattach to a still-running session (warm — e.g. an app restart). The renderer uses it to+ * replay the persisted scrollback and re-launch a resumable agent only on a cold start.+ */+export interface PtyCreateResult {+ sessionId: string+ fresh: boolean+}+// 'subagent' and 'loop' are render-only (ephemeral hook-driven viz) and never persisted.export type NodeKind = 'terminal' | 'sticky' | 'group' | 'editor' | 'diff' | 'subagent' | 'loop' | 'dino'@@ -132,8 +143,9 @@ export const EMPTY_WORKSPACE: Workspace = {// ---- Contract for the API exposed to the renderer via preload ----export interface PtyApi {- /** Starts a new PTY session, returns its sessionId. */- create(options: PtyCreateOptions): Promise<string>+ /** Starts a new PTY session; returns its sessionId and whether the session was freshly+ * created (cold start) vs reattached to a still-running tmux session (warm). */+ create(options: PtyCreateOptions): Promise<PtyCreateResult>/** Sends user input to the PTY. */write(sessionId: string, data: string): void/** Updates the PTY when the terminal is resized. */@@ -150,6 +162,8 @@ export interface PtyApi {generateGroupName(memberKeys: string[], cwd: string): Promise<GitResult>/** Capture a terminal session's output as text. `full` grabs the entire scrollback. */capture(persistKey: string, full?: boolean): Promise<string>+ /** Read the persisted scrollback snapshot for a node (for cold-restart replay). '' if none. */+ readScrollback(persistKey: string): Promise<string>/** Send literal text + Enter into a session (e.g. a slash command). Returns false if unavailable. */sendText(persistKey: string, text: string): Promise<boolean>/** Listens for PTY output. Returns an unsubscribe function. */