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): co-attach joiner re-enters the alternate screen
enes8379470fbc3e
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8c001ad3a..9adb0217e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1180,7 +1180,18 @@ seed** — the cases are:(gated on `persistKey`, on BOTH the screen and resize branches) and the renderer writes`CO_ATTACH_MOUSE_SEQ` into the fresh xterm (both `ModalTerminal` and `TerminalNode`). tmux isalways `mouse on`, so this matches its invariant client state; the enable is idempotent. Was the- "can't scroll the kanban card-modal terminal until you press a key" bug.+ "can't scroll the kanban card-modal terminal until you press a key" bug. **A co-attach joiner+ ALSO misses tmux's attach-time `\e[?1049h`**, and a renderer reload is a joiner too (it re-joins+ the SAME still-alive tmux client via `join()`, so tmux never re-attaches it). `join()` therefore+ sets `coAttachAltScreen` for tmux-backed sessions only — gated on `tmuxBacked && !sessionHost`,+ never plain-shell/session-host, whose normal-buffer scrollback is their only history — and the+ renderer writes `CO_ATTACH_ALT_SCREEN_SEQ` **BEFORE** painting (entering the alternate buffer+ clears the display, so writing it after would erase the paint; TerminalNode skips it once a+ resync has superseded the seed, since that repaint may already be on screen). Without it a+ renderer reload left every terminal on the normal buffer, piling up to 10k lines of scrollback+ and forcing a layout per output frame — measured 16.1% vs 7.3% CPU for one terminal at+ 20 lines/s, 313 vs 1 forced layouts per 20 s. Note `repaintResync`'s `term.reset()` also drops a+ terminal back to the normal buffer; that is not addressed here.xterm's own `scrollback` (`xtermScrollback(settings.tmuxScrollback)`, floored at 1000, capped at`XTERM_SCROLLBACK_MAX` = 10000) is kept for the sessions tmux does *not* back (a plain shell whendiff --git a/src/core/pty-coattach.test.ts b/src/core/pty-coattach.test.tsindex a1bb890fa..ff36b8fa4 100644--- a/src/core/pty-coattach.test.ts+++ b/src/core/pty-coattach.test.ts@@ -1266,6 +1266,7 @@ describe('a tmux-backed joiner is told to enable mouse tracking', () => {fresh: booleanscreen?: stringcoAttachMouse?: boolean+ coAttachAltScreen?: boolean}>it('sets coAttachMouse on a joiner whose grid EQUALS the pty (the screen-painted branch)', async () => {@@ -1308,6 +1309,49 @@ describe('a tmux-backed joiner is told to enable mouse tracking', () => {expect(b.fresh).toBe(false) // it did join the live session…expect(b.coAttachMouse).toBeUndefined() // …but a plain shell has no tmux mouse to turn on})++ // A joiner also missed tmux's attach-time `\e[?1049h`, so its xterm stays on the NORMAL buffer+ // (scrollback piles up; every output frame forces a layout). `coAttachAltScreen` tells it to+ // enter the alternate buffer — tmux-backed only: a plain shell's normal-buffer scrollback is the+ // only history it has.+ it('sets coAttachAltScreen on a tmux-backed joiner whose grid EQUALS the pty (the screen-painted branch)', async () => {+ const m = await tmuxManager()+ vi.spyOn(m, 'captureForResync').mockResolvedValue('current screen')+ await create(ALICE, 80, 24)++ const b = await create(BOB, 80, 24)+ expect(b.screen).toBe('current screen')+ expect(b.coAttachAltScreen).toBe(true)+ })++ it('sets coAttachAltScreen on a joiner that SHRINKS the pty too', async () => {+ const m = await tmuxManager()+ const capture = vi.spyOn(m, 'captureForResync').mockResolvedValue('current screen')+ await create(ALICE, 120, 40)++ const b = await create(BOB, 80, 24)+ expect(capture).not.toHaveBeenCalled()+ expect(b.screen).toBeUndefined()+ expect(b.coAttachAltScreen).toBe(true)+ })++ it('never sets coAttachAltScreen on the SOLO spawn', async () => {+ await tmuxManager()+ const a = await create(ALICE, 80, 24)+ expect(a.coAttachAltScreen).toBeUndefined()+ })++ it('does NOT set coAttachAltScreen on a plain-shell join (its scrollback is the only history)', async () => {+ const { PtyManager } = await import('./pty-manager')+ const m = new PtyManager()+ m.registerIpc()+ vi.spyOn(m, 'captureForResync').mockResolvedValue('current screen')+ await create(ALICE, 80, 24)++ const b = await create(BOB, 80, 24)+ expect(b.fresh).toBe(false)+ expect(b.coAttachAltScreen).toBeUndefined()+ })})describe('tmuxAttachFlags', () => {diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex caa9b6f1b..8a90c81b4 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -2139,12 +2139,23 @@ export class PtyManager {// our tmux always runs `mouse on`, so enabling these unconditionally matches its client state.// Rides `base` so it reaches the renderer on BOTH the resized and screen-painted branches.const coAttachMouse = existing.persistKey ? true : undefined+ // Alt-screen: tmux-backed ONLY, and `tmuxBacked` alone is not that gate — a session-host session+ // is also recorded tmuxBacked (and carries a persistKey), and switching it (or a plain shell) to+ // the alternate buffer would hide its only scrollback. See PtyCreateResult.coAttachAltScreen.+ const coAttachAltScreen = existing.tmuxBacked && !existing.sessionHost ? true : undefined// Same source, different question (and different consumer): a joiner needs to know whether the// session it landed on survives losing a client, because its own unmount may park it.const persistent = !!existing.persistKeyconst base: PtyCreateResult = existing.accountFallback- ? { sessionId: existingId, fresh: false, accountFallback: true, coAttachMouse, persistent }- : { sessionId: existingId, fresh: false, coAttachMouse, persistent }+ ? {+ sessionId: existingId,+ fresh: false,+ accountFallback: true,+ coAttachMouse,+ coAttachAltScreen,+ persistent+ }+ : { sessionId: existingId, fresh: false, coAttachMouse, coAttachAltScreen, persistent }if (resized) return Promise.resolve(base) // tmux is redrawing this client — do not paint twice// An empty capture (plain shell — no tmux to capture; a tmux/ssh blip) is OMITTED, never sent// as '': the renderer must not reset a terminal for nothing. A plain-shell joiner thereforediff --git a/src/core/pty-session-host.test.ts b/src/core/pty-session-host.test.tsindex 0abcf8038..b2c8e4423 100644--- a/src/core/pty-session-host.test.ts+++ b/src/core/pty-session-host.test.ts@@ -624,6 +624,19 @@ describe('PtyManager session-host contracts', () => {expect(backend.create).toHaveBeenCalledTimes(1)})+ it('never tells a session-host joiner to enter the alternate screen (its scrollback is its history)', async () => {+ backend.create.mockReturnValue(fakeSessionHostPty())+ const m = await makeManager()+ m.registerIpc()+ const create = host.handlers[IPC.ptyCreate]+ const options = { cols: 80, rows: 24, persistKey: 'node-alt-screen' }++ await create(7, options)+ const joined = (await create(8, options)) as { fresh: boolean; coAttachAltScreen?: boolean }+ expect(joined.fresh).toBe(false) // it did join the live session…+ expect(joined.coAttachAltScreen).toBeUndefined() // …but there is no tmux alt screen to restore+ })+it('leaves the live generation joinable when the confirmed backend kill rejects', async () => {const active = fakeSessionHostPty()backend.create.mockReturnValue(active)diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsxindex 14c401494..e67e7df74 100644--- a/src/renderer/components/kanban/ModalTerminal.tsx+++ b/src/renderer/components/kanban/ModalTerminal.tsx@@ -43,7 +43,8 @@ import {applyLiveOptions,xtermOptionsFromSettings,SHIFT_ENTER_SEQ,- CO_ATTACH_MOUSE_SEQ+ CO_ATTACH_MOUSE_SEQ,+ CO_ATTACH_ALT_SCREEN_SEQ} from '../../terminal/terminal-config'import { useXtermVisualSettings } from '../../terminal/useXtermVisualSettings'import {@@ -382,6 +383,9 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch, covere// never write into a disposed xterm or observe a null host ref (mirrors TerminalNode's// post-await onDisposed check).if (dead) return+ // Same as TerminalNode: a joiner (which the modal always is) must enter the alternate+ // buffer BEFORE the paint — see PtyCreateResult.coAttachAltScreen.+ if (res.coAttachAltScreen) term.write(CO_ATTACH_ALT_SCREEN_SEQ)const paint = seedPaint({replay: attachReplay({ parked: false, fresh: res.fresh, hasInitialCommand: false }),superseded: false,diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 90447a31d..8e9897c3d 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -74,6 +74,7 @@ import {xtermOptionsFromSettings,SHIFT_ENTER_SEQ,CO_ATTACH_MOUSE_SEQ,+ CO_ATTACH_ALT_SCREEN_SEQ,type SessionLife} from '../terminal/terminal-config'import { useXtermVisualSettings } from '../terminal/useXtermVisualSettings'@@ -3176,6 +3177,7 @@ export function TerminalNode({screen,cursor,coAttachMouse,+ coAttachAltScreen,persistent,sessionHost,unavailable@@ -3399,6 +3401,11 @@ export function TerminalNode({term.write('\r\n\x1b[90m── session restored (process ended by a restart) ──\x1b[0m\r\n')}} else if (replay === 'warm-attach') {+ // A joiner's xterm never saw tmux's attach-time `\e[?1049h` (PtyCreateResult+ // .coAttachAltScreen). Before the paint: entering the alt buffer clears the display.+ // Not once a resync has superseded the seed: its repaint (`term.reset()` + the capture)+ // may already have landed, and entering the alt buffer now would blank it.+ if (coAttachAltScreen && !superseded) term.write(CO_ATTACH_ALT_SCREEN_SEQ)// tmux is attached to this client and paints it: the visible screen on attach, its own// history under the wheel. So there is nothing to hydrate — EXCEPT for a CO-ATTACH// JOINER, whose `screen` was captured inside `create()`: tmux only repaints on SIGWINCH,diff --git a/src/renderer/terminal/co-attach-alt-screen.test.ts b/src/renderer/terminal/co-attach-alt-screen.test.tsnew file mode 100644index 000000000..035c8a0bc--- /dev/null+++ b/src/renderer/terminal/co-attach-alt-screen.test.ts@@ -0,0 +1,26 @@+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { join } from 'node:path'+import { CO_ATTACH_ALT_SCREEN_SEQ } from './terminal-config'++const src = (rel: string) =>+ readFileSync(join(__dirname, '..', rel), 'utf8').replace(/\r\n/g, '\n')++describe('co-attach joiner alternate screen', () => {+ it('is the DECSET 1049 enable', () => {+ expect(CO_ATTACH_ALT_SCREEN_SEQ).toBe('\x1b[?1049h')+ })++ // Entering the alternate buffer CLEARS the display: the sequence must be written before the+ // captured screen is painted, or it erases the paint.+ for (const file of ['nodes/TerminalNode.tsx', 'components/kanban/ModalTerminal.tsx']) {+ it(`${file} writes it before painting the joiner screen`, () => {+ const s = src(file)+ const alt = s.indexOf('term.write(CO_ATTACH_ALT_SCREEN_SEQ)')+ const paint = s.indexOf('toXtermText(stripTrailingNewline(')+ expect(alt).toBeGreaterThan(-1)+ expect(paint).toBeGreaterThan(-1)+ expect(alt).toBeLessThan(paint)+ })+ }+})diff --git a/src/renderer/terminal/terminal-config.ts b/src/renderer/terminal/terminal-config.tsindex 4b517058f..86043ac95 100644--- a/src/renderer/terminal/terminal-config.ts+++ b/src/renderer/terminal/terminal-config.ts@@ -554,6 +554,11 @@ export const RESYNC_NOTICE = '\r\n\x1b[90m── reconnected — earlier output*/export const CO_ATTACH_MOUSE_SEQ = '\x1b[?1000h\x1b[?1002h\x1b[?1006h'+/** Written into a TMUX-BACKED joiner's fresh xterm BEFORE its screen is painted — see+ * `PtyCreateResult.coAttachAltScreen`. Must precede the paint: entering the alternate buffer+ * clears the display. */+export const CO_ATTACH_ALT_SCREEN_SEQ = '\x1b[?1049h'+/*** The capture generation of the LAST repaint issued for a terminal, so a deferred repaint can tell* that a newer capture has superseded it (see `repaintResync`). Weak, and keyed by the xterm itself:diff --git a/src/shared/types.ts b/src/shared/types.tsindex d63bfe02c..5cd158a13 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -271,6 +271,17 @@ export interface PtyCreateResult {* Absent for a plain-shell join (no tmux ⇒ no tmux mouse) and for the solo spawn path.*/coAttachMouse?: boolean+ /**+ * A TMUX-BACKED joiner must switch its fresh xterm to the ALTERNATE buffer before painting.+ * tmux emits `\e[?1049h` to a client only at that client's own attach; a joiner (a renderer+ * reload re-joins the same still-alive tmux client, and the kanban card modal is always a+ * joiner) never sees it, so its xterm stayed on the NORMAL buffer: up to 10k lines of tmux's+ * scrolled output piled up there and every output frame forced a layout (xterm's viewport+ * resync) — measured 16.1% vs 7.3% total CPU for one terminal streaming 20 lines/s.+ * Absent for plain-shell and session-host sessions: there the pty IS the shell and its+ * normal-buffer scrollback is the only history it has.+ */+ coAttachAltScreen?: boolean/*** This session is TMUX-BACKED (local or remote) — it survives losing this client, so killing our* pty client only detaches us and everything running in the session keeps going.