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(session-host): cap the headless emulator's history at the renderer's 10k
review3157e6d874e2
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 4cbf8f94f..8c25fc263 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -10,6 +10,7 @@ import * as pty from 'node-pty'import { IPC } from '../shared/ipc'import { safeSessionProgram } from '../shared/node-exec'import { REF_MAX_LEN } from '../shared/presence'+import { xtermScrollback } from '../shared/scrollback'import {DEFAULT_SETTINGS,type PaneCursor,@@ -3895,8 +3896,8 @@ export class PtyManager {}/** The relay snapshot for a `scroll: 'local'` stream: everything the session host's emulator- * holds (bounded by `tmuxScrollback`, like a desktop warm attach's seed), not just the visible- * screen — the relay attach never gets the host's attach repaint, so without this the phone has+ * holds (bounded by `xtermScrollback(tmuxScrollback)`, at most 10k lines, like a desktop warm+ * attach's seed), not just the visible screen — the relay attach never gets the host's attach repaint, so without this the phone has* no history at all. A plain shell has nothing to capture. */private async relayLocalSnapshot(persistKey: string): Promise<string> {const live = this.liveSessionForPersistKey(persistKey)@@ -4780,7 +4781,9 @@ export class PtyManager {// or Git Bash/WSL spawn request is byte-identical to before....(hostLaunchDialect ? { launchDialect: hostLaunchDialect } : {})},- settings.tmuxScrollback+ // NOT the raw tmux history-limit: the host's headless xterm holds every line at full+ // width, and the renderer can never show more than its own cap. See shared/scrollback.+ xtermScrollback(settings.tmuxScrollback))) as unknown as pty.IPty} else {try {@@ -4835,7 +4838,7 @@ export class PtyManager {const session: Session = {proc,nativeWindowsPane: process.platform === 'win32' && !persisted- ? new NativeWindowsPane(proc, { ...options, scrollback: settings.tmuxScrollback })+ ? new NativeWindowsPane(proc, { ...options, scrollback: xtermScrollback(settings.tmuxScrollback) }): undefined,subscribers: spawnSub === null ? new Set<SubKey>() : new Set<SubKey>([spawnSub]),// A non-voting view (`sizeVote: false`) that got here — a hosted-relay viewer's warm tmuxdiff --git a/src/core/pty-session-host.test.ts b/src/core/pty-session-host.test.tsindex 2c371e4da..66a63ddb5 100644--- a/src/core/pty-session-host.test.ts+++ b/src/core/pty-session-host.test.ts@@ -241,6 +241,29 @@ describe('PtyManager session-host contracts', () => {expect(spawn.args).toEqual([])})+ it('caps the session-host emulator at the renderer scrollback cap, not tmux history-limit', async () => {+ const { PtyManager } = await import('./pty-manager')+ for (const [tmuxScrollback, expected] of [+ [50000, 10000],+ [2000, 2000],+ [500, 1000]+ ] as const) {+ backend.create.mockClear()+ const m = new PtyManager({ runtimePlatform: 'win32' })+ ;(m as unknown as { getSettings: () => unknown }).getSettings = () => ({+ ...DEFAULT_SETTINGS,+ tmuxScrollback+ })+ m.createDetached(+ { cols: 80, rows: 24, persistKey: `node-sb-${tmuxScrollback}` },+ { onData: () => {}, onExit: () => {} }+ )+ expect(backend.create).toHaveBeenCalledTimes(1)+ expect(backend.create.mock.calls[0][2]).toBe(expected)+ await m.killAll()+ }+ })+it('sends no launch dialect from a POSIX core, so its spawn request is unchanged', async () => {const { PtyManager } = await import('./pty-manager')for (const runtimePlatform of ['darwin', 'linux'] as const) {diff --git a/src/session-host/host.ts b/src/session-host/host.tsindex a129b6e48..2483e356e 100644--- a/src/session-host/host.ts+++ b/src/session-host/host.ts@@ -61,6 +61,7 @@ import { drainSessionHostTransport, writeSessionHostFrame } from './socket-flow'import { SessionHostSocketRequestQueue } from './socket-request-queue'import { trySessionHostHello } from './hello-probe'import { killHostSession } from './kill-session'+import { clampEmulatorScrollback } from '../shared/scrollback'/** How long a session-less host lingers before exiting — mirrors tmux's own server lifetime rule* ("the server exits when its last session dies"), plus a grace window so an app restart that@@ -525,6 +526,9 @@ async function main(): Promise<void> {req: Extract<SessionHostRequest, { cmd: 'attach' }>,socket: net.Socket): Promise<AttachResult> {+ // Clamped ONCE at the request boundary, before both the replacement-replay fingerprint check+ // and construction, so an older client's raw 50,000 still matches its own replay.+ const scrollback = clampEmulatorScrollback(req.scrollback)return generationCoordinator.run<AttachResult>(req.name, async (existing) => {if (ending.has(req.name)) {throw new Error(`session '${req.name}' is ending and cannot be attached`)@@ -536,7 +540,7 @@ async function main(): Promise<void> {`reserved replacement '${req.name}' cannot attach a different live generation`)}- if (!existing.matchesReplacementReplay(req.spawn, req.scrollback)) {+ if (!existing.matchesReplacementReplay(req.spawn, scrollback)) {throw new Error(`reserved replacement '${req.name}' replay changed its trusted launch plan`)@@ -598,7 +602,7 @@ async function main(): Promise<void> {if (reservation) replacementReservations.delete(req.name)let session: HostSessiontry {- session = new HostSession(req.name, req.spawn, req.scrollback, reservation?.token)+ session = new HostSession(req.name, req.spawn, scrollback, reservation?.token)} catch (error) {scheduleGraceExitIfEmpty()log(`spawn failed name=${req.name} category=profile-start-failed detail=${String(error)}`)diff --git a/src/session-host/protocol.ts b/src/session-host/protocol.tsindex 014fa032f..0c0700f78 100644--- a/src/session-host/protocol.ts+++ b/src/session-host/protocol.ts@@ -65,7 +65,9 @@ export type SessionHostRequest =name: stringspawn: SessionHostSpawnOptions/** Cap on both the emulator's live scrollback buffer and how much `capture`'s `full: true`- * returns — mirrors `settings.tmuxScrollback` / tmux's own `history-limit`. */+ * returns. Clients send `xtermScrollback(settings.tmuxScrollback)` (≤ 10k — the renderer's+ * own cap, NOT tmux's history-limit); the host clamps again (`clampEmulatorScrollback`) so+ * an older client's raw 50,000 cannot allocate history nobody can scroll to. */scrollback: number/** Capability established by a confirmed kill. Required to cold-create that reserved name;* other authenticated app clients cannot steal the replacement window. */diff --git a/src/session-host/terminal-emulator.test.ts b/src/session-host/terminal-emulator.test.tsindex 4758b5169..c5ad3b80f 100644--- a/src/session-host/terminal-emulator.test.ts+++ b/src/session-host/terminal-emulator.test.ts@@ -89,3 +89,35 @@ describe('captureVisible tail', () => {expect(cap.cursor).toEqual({ x: 0, y: 0 })})})++describe('TerminalEmulator scrollback cap (Windows session-host memory bound)', () => {+ function lines(from: number, to: number): string {+ let data = ''+ for (let i = from; i < to; i++) data += `line ${i}\r\n`+ return data+ }++ it('caps a raw 50,000-line request at the renderer cap, so history stays bounded', async () => {+ const rows = 4+ const e = new TerminalEmulator({ cols: 20, rows, scrollback: 50000 })+ emulators.push(e)+ const term = (e as unknown as { term: { options: { scrollback: number }; buffer: { normal: { length: number } } } }).term+ expect(term.options.scrollback).toBe(10000)++ await e.write(lines(0, 20000))+ expect(term.buffer.normal.length).toBeLessThanOrEqual(10000 + rows)++ // The warm-attach replay is bounded by the same cap: the oldest lines are gone.+ const screen = e.serialize()+ expect(screen.split('\r\n').length).toBeLessThanOrEqual(10000 + rows)+ const rowsText = text(screen).split('\r\n')+ expect(rowsText).not.toContain('line 0')+ expect(rowsText).toContain('line 19999')+ })++ it('keeps a request below the cap as asked', () => {+ const e = new TerminalEmulator({ cols: 20, rows: 4, scrollback: 3000 })+ emulators.push(e)+ expect((e as unknown as { term: { options: { scrollback: number } } }).term.options.scrollback).toBe(3000)+ })+})diff --git a/src/session-host/terminal-emulator.ts b/src/session-host/terminal-emulator.tsindex 2ddc4f645..92170e0b1 100644--- a/src/session-host/terminal-emulator.ts+++ b/src/session-host/terminal-emulator.ts@@ -1,5 +1,6 @@import { Terminal, type ITerminalAddon } from '@xterm/headless'import { SerializeAddon } from '@xterm/addon-serialize'+import { clampEmulatorScrollback } from '../shared/scrollback'// @xterm/addon-serialize's published types are written against @xterm/xterm's (browser) Terminal,// which has a superset of DOM-specific members @xterm/headless's Terminal lacks. The addon only@@ -33,7 +34,10 @@ export class TerminalEmulator {private readonly defaultScrollback: numberconstructor(opts: { cols: number; rows: number; scrollback: number }) {- this.defaultScrollback = Math.max(0, opts.scrollback)+ // Capped at the renderer's own xterm cap (`XTERM_SCROLLBACK_MAX`): xterm allocates every+ // buffered line at full width (cols × 12 B), and nothing past the renderer's cap is ever+ // shown. Clamped HERE as well as in core, because an older client still sends 50,000.+ this.defaultScrollback = clampEmulatorScrollback(opts.scrollback)this.term = new Terminal({cols: Math.max(1, opts.cols),rows: Math.max(1, opts.rows),