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
perf(terminal): park detached tmux clients for instant project-switch reattach
enes8a458474c956
diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.tsindex d3350a60f..15edb2f36 100644--- a/src/main/pty-manager.ts+++ b/src/main/pty-manager.ts@@ -244,6 +244,11 @@ interface Session {/** True when this node had an `accountId` but its config dir was gone at spawn, so we fell back* to the system account. `create()` surfaces it to the renderer (warning chip). */accountFallback?: boolean+ /** Parked: the renderer detached (node unmount / project switch) but the client process is kept+ * attached for PARK_KEEP_MS so a quick remount reuses it — no respawn, no attach round-trip.+ * Output is discarded while parked; `parkTimer` fires the real detach. */+ parked?: boolean+ parkTimer?: ReturnType<typeof setTimeout> | null}/** Sinks for a detached session whose output is served somewhere other than the renderer@@ -259,6 +264,13 @@ export interface DetachedSinks {const FLUSH_MS = 8const MAX_BUF_BYTES = 256 * 1024+// Keep-warm window after the renderer detaches (project switch / node unmount): the tmux client+// process stays attached and is reused if the node remounts within it, so reattach becomes a+// resize + `refresh-client` (tmux's own pixel-perfect full redraw) instead of a process spawn ++// attach round-trip per node. After the window the client is truly detached, bounding the idle+// cost (one ~1 MB tmux client + a drained pty fd per parked node).+const PARK_KEEP_MS = 5 * 60 * 1000+/*** Manages all live PTY processes and bridges them to the renderer over IPC.*@@ -363,6 +375,19 @@ export class PtyManager {webContentsId: number,options: PtyCreateOptions): Promise<PtyCreateResult> {+ // Keep-warm reuse: if this node detached moments ago (project switch), its client process is+ // still attached (parked). Rebind it to the new renderer, match the size, and have tmux+ // repaint the full screen — no spawn, no attach round-trip, no session-exists probe.+ if (options.persistKey) {+ for (const [sid, s] of this.sessions) {+ if (s.persistKey === options.persistKey && s.parked && !s.sshRemote) {+ this.unpark(s, webContentsId, options)+ return s.accountFallback+ ? { sessionId: sid, fresh: false, accountFallback: true }+ : { sessionId: sid, fresh: false }+ }+ }+ }// 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@@ -731,6 +756,7 @@ export class PtyManager {proc.onData((data) => this.queueData(sessionId, session, data))proc.onExit(({ exitCode }) => {+ if (session.parkTimer) clearTimeout(session.parkTimer) // died while parked (e.g. destroy)this.flush(sessionId, session) // deliver any buffered output before the exit signalif (session.onExit) {session.onExit(exitCode)@@ -746,6 +772,10 @@ export class PtyManager {/** Buffer a chunk; flush immediately past the byte cap, otherwise on a short timer. */private queueData(sessionId: string, session: Session, data: string): void {session.outputSinceSnapshot = true+ // Parked (renderer detached, kept warm): nobody is listening — drop the chunk. The pty must+ // keep draining so the tmux client isn't backpressured; the periodic scrollback snapshot+ // still captures the pane from the tmux server directly.+ if (session.parked) returnsession.buf.push(data)session.bufBytes += data.lengthif (session.bufBytes >= MAX_BUF_BYTES) {@@ -813,12 +843,76 @@ export class PtyManager {// Skipped when nothing arrived since the last periodic capture (pane content is unchanged).if (session.persistKey && session.outputSinceSnapshot)void this.snapshotScrollback(session.persistKey, session.sshRemote)+ // Keep-warm: a local tmux-backed renderer session parks (client kept attached, reused by a+ // remount within PARK_KEEP_MS — see create()) instead of detaching immediately. Remote (ssh),+ // detached-sink (relay host), and non-persistent sessions keep the immediate detach.+ if (session.persistKey && !session.sshRemote && !session.onData && this.tmuxPath) {+ this.park(sessionId, session)+ return+ }// releasePty (not proc.kill()): a paused pty never reads EOF, so kill() alone leaks the// master fd on every detach until the process runs out of descriptors (see pty-release.ts).releasePty(session.proc as ReleasablePty)this.sessions.delete(sessionId)}+ /** Park a detaching session: keep the tmux client attached for PARK_KEEP_MS, drop output on+ * the floor meanwhile, then truly detach if no remount reclaimed it. */+ private park(sessionId: string, session: Session): void {+ session.parked = true+ session.webContentsId = null+ // Drop anything buffered for the departed renderer, and make sure the pty keeps draining:+ // the renderer may have left flow paused at a high watermark, and a paused parked pty+ // would backpressure the tmux client forever.+ session.buf = []+ session.bufBytes = 0+ try {+ session.proc.resume()+ } catch {+ // already exited; onExit cleans up+ }+ session.parkTimer = setTimeout(() => {+ session.parkTimer = null+ if (!session.parked) return+ releasePty(session.proc as ReleasablePty)+ this.sessions.delete(sessionId)+ }, PARK_KEEP_MS)+ }++ /** Rebind a parked session to a (re)mounting renderer: cancel the detach timer, restore IPC+ * forwarding, match the requested size, and have tmux repaint the whole screen. */+ private unpark(session: Session, webContentsId: number, options: PtyCreateOptions): void {+ if (session.parkTimer) clearTimeout(session.parkTimer)+ session.parkTimer = null+ session.parked = false+ session.webContentsId = webContentsId+ if (session.proc.cols !== options.cols || session.proc.rows !== options.rows)+ session.proc.resize(Math.max(1, options.cols), Math.max(1, options.rows))+ // The new xterm is empty: ask tmux for a full client repaint (the same redraw an attach+ // would stream — pixel-perfect, unlike replaying a captured snapshot).+ if (session.persistKey) void this.refreshClient(session.persistKey)+ }++ /** Force a full tmux redraw of the (single, `-D`) client attached to a node's session. */+ private async refreshClient(persistKey: string): Promise<void> {+ if (!this.tmuxPath) return+ try {+ const { stdout } = await runAsync(this.tmuxPath, [+ '-L',+ TMUX_SOCKET,+ 'list-clients',+ '-t',+ sessionName(persistKey),+ '-F',+ '#{client_tty}'+ ])+ const tty = stdout.trim().split('\n')[0]+ if (tty) await runAsync(this.tmuxPath, ['-L', TMUX_SOCKET, 'refresh-client', '-t', tty])+ } catch {+ // session/client gone — the next create() spawns a fresh attach instead.+ }+ }+/*** Capture a session's output. `full` grabs the entire scrollback (`-S -`, for the* markdown view); otherwise the recent ~200 lines (AI naming, palette search).@@ -955,6 +1049,7 @@ export class PtyManager {const finals: Promise<unknown>[] = []for (const session of this.sessions.values()) {if (session.flushTimer) clearTimeout(session.flushTimer)+ if (session.parkTimer) clearTimeout(session.parkTimer)// Final scrollback snapshot on quit so a reboot can replay it. Skipped for sessions with// no output since the last periodic capture (unchanged pane content).if (session.persistKey && session.outputSinceSnapshot)diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex f0f4b54f7..862947ea1 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -312,6 +312,11 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNlet sessionId: string | null = nulllet disposed = false+ // Last cols/rows actually sent to the PTY (seeded at create): a resize IPC makes tmux redraw+ // the whole pane, so a same-size fit (e.g. the ResizeObserver's initial tick right after+ // mount) must not send one — on a bulk project load that redraw doubles per node.+ let sentCols = 0+ let sentRows = 0const cleanups: Array<() => void> = []// Remote nodes: surface a dropped relay connection (host gone / socket closed) so the@@ -351,17 +356,6 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN// 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(() => '')- // Paint the persisted snapshot the moment it's read (a file read resolves well before the- // tmux attach round-trip), so a project switch shows each terminal's last content instantly- // instead of a blank body. On a warm reattach the live tmux redraw REPLACES it (term.reset()- // on the first data chunk below); on a cold restore the replay logic reuses it as-is.- let previewShown = false- let liveStarted = false- void scrollbackPromise.then((snapshot) => {- if (disposed || liveStarted || !snapshot) return- term.write(snapshot)- previewShown = true- })void (async () => {// SSH-project terminal: the project's live ControlMaster controlPath is established by// Canvas's active-project effect. On a cold app load child effects run before that parent@@ -372,6 +366,8 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN? await resolveSshRemote(ssh, data.cwd as string | undefined): undefinedif (disposed) return+ sentCols = term.cols+ sentRows = term.rowstransport.create({cols: term.cols,@@ -391,8 +387,14 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNreturn}sessionId = sid- liveStarted = true // a late-resolving preview must not write over live outputif (fellBack) setAccountFallback(true)+ // Catch up a size change that landed while the spawn was in flight (resize() skips the+ // IPC until sessionId is set, and the observer won't re-fire without another change).+ if (term.cols !== sentCols || term.rows !== sentRows) {+ sentCols = term.cols+ 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@@ -404,9 +406,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNreturn}if (snapshot) {- // The instant preview above may have painted this snapshot already — keep it.- if (!previewShown) term.write(snapshot)- previewShown = false+ term.write(snapshot)term.write('\r\n\x1b[90m── session restored (process ended by a restart) ──\x1b[0m\r\n')}}@@ -419,13 +419,6 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNconst LOW_WATER = 1 << 18 // 256 KBcleanups.push(transport.onData(sid, (chunk) => {- // Warm reattach: the first live chunk is tmux's own full redraw — drop the static- // snapshot preview so the two don't stack (reset clears buffer + scrollback, which- // matches the pre-preview behavior of starting the attach from a blank terminal).- if (previewShown) {- previewShown = false- term.reset()- }pending += chunk.lengthif (!paused && pending > HIGH_WATER) {paused = true@@ -473,7 +466,11 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNconst resize = () => {try {fit.fit()- if (sessionId) transport.resize(sessionId, term.cols, term.rows)+ if (sessionId && (term.cols !== sentCols || term.rows !== sentRows)) {+ sentCols = term.cols+ sentRows = term.rows+ transport.resize(sessionId, term.cols, term.rows)+ }} catch {// fit can throw when the size is 0 (e.g. collapsed); ignore.}