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): hold xterm's textarea, scroll-area and selection paths under the board
enes32951e258b76
diff --git a/src/renderer/terminal/board-render-pause.test.ts b/src/renderer/terminal/board-render-pause.test.tsindex 27a6ec0b8..3eb5aa604 100644--- a/src/renderer/terminal/board-render-pause.test.ts+++ b/src/renderer/terminal/board-render-pause.test.ts@@ -46,6 +46,47 @@ function fake(): { term: PausableTerminal; rs: FakeRenderService } {return { term: { _core: { _renderService: rs as never } }, rs }}+/**+ * The three xterm 5.5 paths that run beside the render service and ignore its pause, as structural+ * fakes with the methods on the PROTOTYPE (as in the real classes) and callers reaching them through+ * the instance, so an instance property shadows them:+ * - `CoreBrowserTerminal._syncTextArea` — every cursor move (`onCursorMove`);+ * - `Viewport.syncScrollArea` — every scroll (`_onScroll`), reading and writing layout;+ * - `RenderService.handleSelectionChanged` — every scroll (`SelectionService.refresh`), which the+ * DOM renderer answers with a FULL `renderRows`, paused or not.+ */+class FakeSelectingRenderService extends FakeRenderService {+ selections: Array<[unknown, unknown, unknown]> = []+ handleSelectionChanged(start: unknown, end: unknown, columnSelectMode: unknown): void {+ this.selections.push([start, end, columnSelectMode])+ }+}+class FakeViewport {+ syncs: Array<boolean | undefined> = []+ syncScrollArea(immediate?: boolean): void {+ this.syncs.push(immediate)+ }+}+class FakeCore {+ textareaSyncs = 0+ constructor(public _renderService: FakeSelectingRenderService, public viewport: FakeViewport) {}+ _syncTextArea(): void {+ this.textareaSyncs+++ }+ /** What xterm does on a streamed line: cursor move, scroll, selection refresh. */+ streamLine(): void {+ this._syncTextArea()+ this.viewport.syncScrollArea()+ this._renderService.handleSelectionChanged(undefined, undefined, false)+ }+}+function fakeCore(): { term: PausableTerminal; core: FakeCore; rs: FakeSelectingRenderService; vp: FakeViewport } {+ const rs = new FakeSelectingRenderService()+ const vp = new FakeViewport()+ const core = new FakeCore(rs, vp)+ return { term: { _core: core as never }, core, rs, vp }+}+describe('renderPaused', () => {it('pauses when covered, when off screen, and when both', () => {expect(renderPaused(false, true)).toBe(false)@@ -193,6 +234,117 @@ describe('installBoardRenderPause', () => {})})+describe('installBoardRenderPause — the paths beside the render service', () => {+ it('holds the textarea sync, the scroll-area sync and the selection redraw while covered', () => {+ const { term, core, rs, vp } = fakeCore()+ installBoardRenderPause(term, { covered: () => true })+ for (let i = 0; i < 50; i++) core.streamLine()+ expect(core.textareaSyncs).toBe(0)+ expect(vp.syncs).toEqual([])+ expect(rs.selections).toEqual([])+ })++ it('replays each held path ONCE on uncover — the scroll area immediately, the selection with its latest range', () => {+ const { term, core, rs, vp } = fakeCore()+ let covered = true+ const pause = installBoardRenderPause(term, { covered: () => covered })!+ for (let i = 0; i < 20; i++) core.streamLine()+ rs.handleSelectionChanged([0, 3], [10, 3], true)+ covered = false+ pause.sync()+ expect(core.textareaSyncs).toBe(1)+ expect(vp.syncs).toEqual([true])+ expect(rs.selections).toEqual([[[0, 3], [10, 3], true]])+ })++ it('replays nothing a covered period did not owe', () => {+ const { term, core, rs, vp } = fakeCore()+ let covered = true+ const pause = installBoardRenderPause(term, { covered: () => covered })!+ covered = false+ pause.sync()+ expect(core.textareaSyncs).toBe(0)+ expect(vp.syncs).toEqual([])+ expect(rs.selections).toEqual([])+ })++ it('passes every path straight through while nothing covers it, off screen included (xterm’s own behaviour)', () => {+ const { term, core, rs, vp } = fakeCore()+ installBoardRenderPause(term, { covered: () => false })+ core.streamLine()+ rs.observe(false)+ core.streamLine()+ expect(core.textareaSyncs).toBe(2)+ expect(vp.syncs).toEqual([undefined, undefined])+ expect(rs.selections).toHaveLength(2)+ })++ it('an observer delivery that finds the board gone flushes what was held', () => {+ const { term, core, vp } = fakeCore()+ let covered = true+ installBoardRenderPause(term, { covered: () => covered })+ core.streamLine()+ covered = false+ core._renderService.observe(true)+ expect(core.textareaSyncs).toBe(1)+ expect(vp.syncs).toEqual([true])+ })++ it('dispose restores the prototype methods; a covered dispose replays what it owed, deferred', () => {+ const { term, core, rs, vp } = fakeCore()+ const pause = installBoardRenderPause(term, { covered: () => true })!+ core.streamLine()+ expect(core.textareaSyncs).toBe(0)+ expect(vp.syncs).toEqual([])+ pause.dispose()+ expect(Object.prototype.hasOwnProperty.call(core, '_syncTextArea')).toBe(false)+ expect(Object.prototype.hasOwnProperty.call(vp, 'syncScrollArea')).toBe(false)+ expect(Object.prototype.hasOwnProperty.call(rs, 'handleSelectionChanged')).toBe(false)+ expect(core.textareaSyncs).toBe(1)+ // A park disposes into a DETACHED element: the scroll area is synced on the next frame rather+ // than forcing a layout of a node that is not in the document.+ expect(vp.syncs).toEqual([undefined])+ expect(rs.selections).toHaveLength(1)+ core.streamLine()+ expect(core.textareaSyncs).toBe(2)+ })++ it('a second install (park re-adopt) does not stack holds', () => {+ const { term, core } = fakeCore()+ installBoardRenderPause(term, { covered: () => true })+ const second = installBoardRenderPause(term, { covered: () => false })!+ core.streamLine()+ // A stacked hold from the first (covered) install would still swallow this.+ expect(core.textareaSyncs).toBe(1)+ second.dispose()+ expect(Object.prototype.hasOwnProperty.call(core, '_syncTextArea')).toBe(false)+ })++ it('a replay that throws never escapes sync or dispose (they run in React effect cleanups)', () => {+ const { term, core, vp } = fakeCore()+ vp.syncScrollArea = () => {+ throw new Error('viewport already disposed')+ }+ let covered = true+ const pause = installBoardRenderPause(term, { covered: () => covered })!+ core.streamLine()+ covered = false+ expect(() => pause.sync()).not.toThrow()+ expect(core.textareaSyncs).toBe(1) // one failed replay does not cost the others+ covered = true+ pause.sync()+ core.streamLine()+ expect(() => pause.dispose()).not.toThrow()+ })++ it('a core without the three methods still gets the render pause', () => {+ const { term, rs } = fake()+ const pause = installBoardRenderPause(term, { covered: () => true })+ expect(pause).not.toBeNull()+ expect(rs._isPaused).toBe(true)+ })+})+/*** The node's wiring, run with a fake terminal: TerminalNode's lifecycle run ATTACHES (and its* cleanup releases), and the board-flag and focus-mode effects only SYNC the slot. A slot thatdiff --git a/src/renderer/terminal/board-render-pause.ts b/src/renderer/terminal/board-render-pause.tsindex 818186f2b..bfe3b6656 100644--- a/src/renderer/terminal/board-render-pause.ts+++ b/src/renderer/terminal/board-render-pause.ts@@ -44,11 +44,86 @@ export interface IntersectionVerdict {/** The private RenderService surface this module touches. */export interface PausableRenderService {_handleIntersectionChange(entry: IntersectionVerdict): void+ /** Selection redraw request — see "THE PATHS BESIDE THE RENDER SERVICE" below. */+ handleSelectionChanged?(...args: unknown[]): void}/** Minimal xterm shape, so the unit test needs no DOM and no real Terminal. */export interface PausableTerminal {- _core?: { _renderService?: Partial<PausableRenderService> }+ _core?: {+ _renderService?: Partial<PausableRenderService>+ /** CoreBrowserTerminal: repositions the hidden input textarea on every cursor move. */+ _syncTextArea?: () => void+ /** The DOM Viewport: scroll-area height + scrollTop, synced on every scroll. */+ viewport?: { syncScrollArea?: (immediate?: boolean) => void }+ }+}++/*+ * THE PATHS BESIDE THE RENDER SERVICE. Pausing the render service stops xterm DRAWING, but three+ * per-output paths in xterm 5.5 run beside it and never ask whether it is paused. MEASURED (Server+ * Edition in headless Chrome, 20 terminals each printing a status line 10×/s and a full line every+ * second, board open, Liquid Glass on, every CSS animation held, 15 s windows): with the render+ * pause alone, GPU 9.3 % + renderer 17.8 %, main thread 14.4 % busy, ~950 forced layouts. With the+ * three paths below also held: GPU 0.4 % + renderer 3.1 %, main thread 1.5 %, zero layouts — what+ * is left is the parser, which must run. All three are per terminal per output, so this is the+ * board cost that grows with the number of busy sessions.+ * - `CoreBrowserTerminal._syncTextArea` (every cursor move): writes the hidden textarea's+ * position, i.e. a style/layout pass per frame for something nobody can see.+ * - `Viewport.syncScrollArea` (every scroll): reads offsetHeight, writes the scroll area's height,+ * reads and writes scrollTop — forced layouts (our viewport-scroll-sync wraps `_innerRefresh`+ * with two more scrollTop reads).+ * - `RenderService.handleSelectionChanged` (every scroll, via `SelectionService.refresh`): calls+ * the renderer directly. The DOM renderer answers with a FULL `renderRows`, paused or not, so+ * every terminal without a WebGL context repainted its whole screen behind the board on every+ * line — almost all of the GPU figure above.+ * Each is held the same way the intersection handler is: an instance property shadows the+ * prototype method (callers reach all three through `this.`), a held call is recorded, and the+ * uncover replays it ONCE — the scroll area immediately, so the first frame after the board is+ * already scrolled to the right place; the selection with its LATEST range, because RenderService+ * keeps that range only through this call and the resume repaint reads it. A covered dispose (a+ * park) replays too, the scroll area deferred to the next frame because the element is about to be+ * detached. A core without a method simply has nothing held for it. Only the BOARD holds them: a+ * terminal that is merely off screen keeps xterm's stock behaviour.+ */+interface HeldPath {+ /** Replay the held call once, if one is owed. `args` overrides the recorded ones. */+ flush(args?: unknown[]): void+ /** Put the original method back (own property or prototype, as it was). */+ restore(): void+}++function holdWhile(target: object | undefined, name: string, held: () => boolean): HeldPath | null {+ const obj = target as Record<string, unknown> | undefined+ if (!obj || typeof obj[name] !== 'function') return null+ const hadOwn = Object.prototype.hasOwnProperty.call(obj, name)+ const ownBefore = obj[name]+ const original = (ownBefore as (...a: unknown[]) => unknown).bind(obj)+ let owed: unknown[] | null = null+ obj[name] = (...args: unknown[]): unknown => {+ if (held()) {+ owed = args+ return undefined+ }+ return original(...args)+ }+ return {+ flush(args) {+ if (!owed) return+ const recorded = owed+ owed = null+ try {+ original(...(args ?? recorded))+ } catch {+ // A catch-up, never worth throwing for: a dispose can run after xterm tore its own+ // services down, and an exception here would escape a React effect cleanup.+ }+ },+ restore() {+ if (hadOwn) obj[name] = ownBefore+ else delete obj[name]+ }+ }}/**@@ -120,6 +195,20 @@ export function installBoardRenderPause(const apply = (): void => original(verdict(!renderPaused(covered, geometric)))+ // The paths beside the render service (see the block above `holdWhile`): held exactly while+ // covered, never merely while off screen.+ const isHeld = (): boolean => !disposed && covered+ const selection = holdWhile(rs, 'handleSelectionChanged', isHeld)+ const scrollArea = holdWhile(term._core?.viewport, 'syncScrollArea', isHeld)+ const textarea = holdWhile(term._core, '_syncTextArea', isHeld)+ /** Replay what the covered period owed: `immediate` syncs the scroll area now (uncover), else on+ * the next frame (a park's dispose into an element about to be detached). */+ const flushHeld = (immediate: boolean): void => {+ selection?.flush()+ scrollArea?.flush(immediate ? [true] : [])+ textarea?.flush()+ }+const controller: BoardRenderPause = {sync(): void {if (disposed) return@@ -127,6 +216,7 @@ export function installBoardRenderPause(if (now === covered) returncovered = nowapply()+ if (!covered) flushHeld(true)if (!covered && geometric) opts.onUncover?.()},dispose(): void {@@ -134,6 +224,9 @@ export function installBoardRenderPause(disposed = trueif (hadOwn) rs._handleIntersectionChange = ownBeforeelse delete (rs as Partial<Wrapped>)._handleIntersectionChange+ selection?.restore()+ scrollArea?.restore()+ textarea?.restore()if (rs[INSTALLED] === controller) delete rs[INSTALLED]// Hand xterm back the geometry it would have had all along. A no-op when nothing was// covered; when something was, it is xterm's own resume (flush + refresh).@@ -142,7 +235,10 @@ export function installBoardRenderPause(// observer reports changes only at a rendering step) would come back on screen with// `_isPaused` stuck true and nothing left to clear it. The cost is a single refresh into a// detached element, and the WebGL dispose that follows does its own full refresh anyway.- if (covered) original(verdict(geometric))+ if (covered) {+ original(verdict(geometric))+ flushHeld(false)+ }}}@@ -152,7 +248,11 @@ export function installBoardRenderPause(// The board can have opened between syncs (a node mounted under it, an observer delivery// racing the view switch), so the observer path re-reads rather than trusting the cache.covered = opts.covered()- if (!covered) return original(entry)+ if (!covered) {+ original(entry)+ flushHeld(true)+ return+ }original(verdict(false))}rs[INSTALLED] = controllerdiff --git a/src/renderer/terminal/board-render-pause.xterm.test.ts b/src/renderer/terminal/board-render-pause.xterm.test.tsnew file mode 100644index 000000000..84d300bd2--- /dev/null+++ b/src/renderer/terminal/board-render-pause.xterm.test.ts@@ -0,0 +1,87 @@+// @vitest-environment jsdom+// The board pause against a REAL xterm 5.5: the unit tests drive structural fakes, which cannot tell+// us whether xterm still has these private methods at these places, or still reaches them through+// `this.` (an instance property shadows only a call made that way). An xterm upgrade that renames+// one of them makes the hold a silent no-op; this file is what fails instead.+import { afterEach, describe, expect, it, vi } from 'vitest'+import { Terminal } from '@xterm/xterm'+import { installBoardRenderPause } from './board-render-pause'++let host: HTMLDivElement | undefined+afterEach(() => host?.remove())++interface CoreLike {+ _syncTextArea(): void+ viewport: { syncScrollArea(immediate?: boolean): void }+ _renderService: { handleSelectionChanged(...args: unknown[]): void }+}++function open(): { term: Terminal; core: CoreLike } {+ ;(window as unknown as { matchMedia?: unknown }).matchMedia ??= () => ({+ matches: false,+ addListener() {},+ removeListener() {},+ addEventListener() {},+ removeEventListener() {}+ })+ host = document.createElement('div')+ document.body.appendChild(host)+ const term = new Terminal({ cols: 40, rows: 5 })+ term.open(host)+ return { term, core: (term as unknown as { _core: CoreLike })._core }+}++const write = (term: Terminal, data: string): Promise<void> => new Promise((r) => term.write(data, r))+/** SelectionService.refresh defers its redraw to an animation frame. */+const frames = (n: number): Promise<void> =>+ new Promise((r) => {+ const step = (left: number): void => (left === 0 ? r() : void requestAnimationFrame(() => step(left - 1)))+ step(n)+ })++/** A stream that moves the cursor and scrolls the buffer, like an agent's output. */+const STREAM = Array.from({ length: 30 }, (_, i) => `line ${i}\r\n`).join('')++function spies(core: CoreLike): Record<'textarea' | 'scrollArea' | 'selection', ReturnType<typeof vi.fn>> {+ return {+ textarea: vi.spyOn(core, '_syncTextArea') as never,+ scrollArea: vi.spyOn(core.viewport, 'syncScrollArea') as never,+ selection: vi.spyOn(core._renderService, 'handleSelectionChanged') as never+ }+}++describe('board render pause — real xterm 5.5', () => {+ it('control: an uncovered terminal reaches all three paths while streaming', async () => {+ const { term, core } = open()+ const s = spies(core)+ const pause = installBoardRenderPause(term as never, { covered: () => false })!+ await write(term, STREAM)+ await frames(2)+ expect(s.textarea).toHaveBeenCalled()+ expect(s.scrollArea).toHaveBeenCalled()+ expect(s.selection).toHaveBeenCalled()+ pause.dispose()+ term.dispose()+ })++ it('a covered terminal reaches none of them while streaming, and each exactly once on uncover', async () => {+ const { term, core } = open()+ const s = spies(core)+ let covered = true+ const pause = installBoardRenderPause(term as never, { covered: () => covered })!+ await write(term, STREAM)+ await frames(2)+ expect(s.textarea).not.toHaveBeenCalled()+ expect(s.scrollArea).not.toHaveBeenCalled()+ expect(s.selection).not.toHaveBeenCalled()++ covered = false+ pause.sync()+ expect(s.textarea).toHaveBeenCalledTimes(1)+ expect(s.scrollArea).toHaveBeenCalledTimes(1)+ expect(s.scrollArea).toHaveBeenCalledWith(true)+ expect(s.selection).toHaveBeenCalledTimes(1)+ pause.dispose()+ term.dispose()+ })+})