Skip to content

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.

fix(webgl): the gesture latch — renderer swaps never run mid-pan/zoom, and drain as a trickle

enesdf9b8239d481
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index ca52174b2..e10101dd6 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -30,7 +30,7 @@ import {
import { solveFitPadding } from './fit-view'
import { SshReconnector } from '../lib/sshReconnect'
import { terminalKey } from '../terminal/terminal-config'
-import { setWebglZoom } from '../terminal/webgl-budget'
+import { setWebglGesture, setWebglZoom, WEBGL_GESTURE_SETTLE_MS } from '../terminal/webgl-budget'
import { StickyNode } from '../nodes/StickyNode'
import { GroupNode, setWorktreeActionHandler } from '../nodes/GroupNode'
import { LazyEditorNode, LazyDiffNode } from '../nodes/lazyMonacoNodes'
@@ -4951,10 +4951,22 @@ export function Canvas() {
}, [nodes, markDirty])
const zoomRafRef = useRef<number | null>(null)
+ const gestureSettleRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const onMove = useCallback(
(_e: unknown, vp: Viewport) => {
viewportRef.current = vp
markDirty()
+ // Latch the WebGL gesture flag for the whole pan/zoom, releasing it a beat after the last
+ // viewport event: renderer swaps (heavyweight, non-atomic) may only run at rest — a swap
+ // executed mid-gesture is both the jank and the black-terminal window (see webgl-budget's
+ // gesture latch). Latched HERE, not in the rAF, so no swap can slip in before the first
+ // coalesced frame.
+ setWebglGesture(true)
+ if (gestureSettleRef.current) clearTimeout(gestureSettleRef.current)
+ gestureSettleRef.current = setTimeout(() => {
+ gestureSettleRef.current = null
+ setWebglGesture(false)
+ }, WEBGL_GESTURE_SETTLE_MS)
// Coalesce the zoom-% readout to one update per frame so a zoom gesture doesn't
// re-render the whole Canvas on every intermediate viewport event.
if (zoomRafRef.current == null) {
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 5901fd91f..1d13824ce 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -728,8 +728,14 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
respawnNonce: ((n.data.respawnNonce as number | undefined) ?? 0) + 1
}))
}
+ // Has this terminal EVER gone through a renderer swap? Every stuck-blank strand needs one —
+ // a node that has only ever run the DOM renderer is covered by xterm's own pause/unpause
+ // bookkeeping, so the transition heals below skip it (a full DOM repaint per node entering
+ // the viewport during a pan is real jank, paid for nothing on a never-swapped node).
+ let everSwapped = false
const acquireWebgl = (): boolean => {
if (webgl) return true
+ everSwapped = true
let addon: WebglAddon | null = null
try {
const a = new WebglAddon()
@@ -1456,7 +1462,9 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
// One-shot per transition (not per frame), so a zoom-out burst costs one repaint per node.
// The invariant check first: a stray black canvas left by a broken swap while hidden
// would otherwise cover everything the repaint draws (no-op when a webgl grant is live).
- if (visible && !wasVisible) {
+ // Gated on everSwapped: a node that never swapped renderers has nothing to heal, and
+ // paying a full repaint per node entering the viewport is what made panning janky.
+ if (visible && !wasVisible && everSwapped) {
verifyCleanDomState('visible')
fullRepaint()
}
diff --git a/src/renderer/terminal/webgl-budget.test.ts b/src/renderer/terminal/webgl-budget.test.ts
index 52d6b6e18..87e91f722 100644
--- a/src/renderer/terminal/webgl-budget.test.ts
+++ b/src/renderer/terminal/webgl-budget.test.ts
@@ -6,10 +6,13 @@ import {
loseWebglContexts,
setWebglBudget,
setWebglEnabled,
+ setWebglGesture,
setWebglZoom,
WEBGL_ACQUIRE_DEBOUNCE_MS,
+ WEBGL_DRAIN_MS,
WEBGL_RESUME_AT_ZOOM,
WEBGL_SUSPEND_BELOW_ZOOM,
+ WEBGL_SWAPS_PER_DRAIN,
WEBGL_BUDGET,
WEBGL_LOSS_STREAK_MAX,
WEBGL_REACQUIRE_AFTER_LOSS_MS,
@@ -379,6 +382,79 @@ describe('webgl-budget coordinator', () => {
expect(a.rec.held).toBe(true)
})
})
+
+ describe('gesture latch (no swaps mid-gesture, staggered drain at rest)', () => {
+ it('defers grants while a gesture runs and executes them at rest', () => {
+ setWebglGesture(true)
+ const a = fakeClient('a')
+ a.handle.setVisible(true)
+ vi.advanceTimersByTime(WEBGL_ACQUIRE_DEBOUNCE_MS * 3)
+ expect(a.rec.acquires).toBe(0) // parked, not granted mid-gesture
+ setWebglGesture(false)
+ expect(a.rec.held).toBe(true) // drained at rest
+ })
+
+ it('defers the hidden-release while a gesture runs; a re-visible client keeps its context', () => {
+ const a = fakeClient('a')
+ grant(a)
+ a.handle.setVisible(false)
+ setWebglGesture(true)
+ vi.advanceTimersByTime(WEBGL_RELEASE_DELAY_MS + 1)
+ expect(a.rec.held).toBe(true) // release parked, not executed mid-gesture
+ // Pans back before the gesture ends: the owed release is forgiven, context stays warm.
+ a.handle.setVisible(true)
+ setWebglGesture(false)
+ vi.advanceTimersByTime(WEBGL_DRAIN_MS * 3)
+ expect(a.rec.held).toBe(true)
+ expect(a.rec.releases).toBe(0)
+ })
+
+ it('executes a deferred release at rest when the client stayed hidden', () => {
+ const a = fakeClient('a')
+ grant(a)
+ a.handle.setVisible(false)
+ setWebglGesture(true)
+ vi.advanceTimersByTime(WEBGL_RELEASE_DELAY_MS + 1)
+ expect(a.rec.held).toBe(true)
+ setWebglGesture(false)
+ expect(a.rec.held).toBe(false)
+ })
+
+ it('drains a mass release as a trickle, WEBGL_SWAPS_PER_DRAIN per tick', () => {
+ const clients = ['a', 'b', 'c', 'd', 'e'].map((id) => fakeClient(id))
+ clients.forEach(grant)
+ expect(clients.every((c) => c.rec.held)).toBe(true)
+ // Zoom-out below the threshold mid-gesture: nothing releases until rest…
+ setWebglGesture(true)
+ setWebglZoom(WEBGL_SUSPEND_BELOW_ZOOM - 0.01)
+ expect(clients.every((c) => c.rec.held)).toBe(true)
+ // …then the drain releases them a batch per tick, never all in one frame.
+ setWebglGesture(false)
+ const heldAfterFirstBatch = clients.filter((c) => c.rec.held).length
+ expect(heldAfterFirstBatch).toBe(clients.length - WEBGL_SWAPS_PER_DRAIN)
+ vi.advanceTimersByTime(WEBGL_DRAIN_MS)
+ expect(clients.filter((c) => c.rec.held).length).toBe(
+ Math.max(0, clients.length - 2 * WEBGL_SWAPS_PER_DRAIN)
+ )
+ vi.advanceTimersByTime(WEBGL_DRAIN_MS * 3)
+ expect(clients.every((c) => !c.rec.held)).toBe(true)
+ })
+
+ it('a gesture starting mid-drain pauses the trickle until the next rest', () => {
+ const clients = ['a', 'b', 'c', 'd', 'e', 'f'].map((id) => fakeClient(id))
+ clients.forEach(grant)
+ setWebglGesture(true)
+ setWebglZoom(WEBGL_SUSPEND_BELOW_ZOOM - 0.01)
+ setWebglGesture(false) // first batch drains
+ const afterFirst = clients.filter((c) => c.rec.held).length
+ setWebglGesture(true) // user grabs the canvas again
+ vi.advanceTimersByTime(WEBGL_DRAIN_MS * 5)
+ expect(clients.filter((c) => c.rec.held).length).toBe(afterFirst) // paused
+ setWebglGesture(false)
+ vi.advanceTimersByTime(WEBGL_DRAIN_MS * 5)
+ expect(clients.every((c) => !c.rec.held)).toBe(true)
+ })
+ })
})
describe('loseWebglContexts', () => {
diff --git a/src/renderer/terminal/webgl-budget.ts b/src/renderer/terminal/webgl-budget.ts
index 9cea5e14c..3fd5267ee 100644
--- a/src/renderer/terminal/webgl-budget.ts
+++ b/src/renderer/terminal/webgl-budget.ts
@@ -116,9 +116,10 @@ let zoomSuspended = false
/**
* Report the canvas zoom (React Flow viewport scale). Cheap and idempotent — call it from the
* zoom/pan handler; state only changes when a hysteresis boundary is crossed. Crossing DOWN
- * reclaims every held context immediately (each client falls back to the DOM renderer, which
- * repaints via its release heal); crossing UP re-attempts a budget-gated grant for every
- * visible client, exactly like the master toggle's ON path.
+ * marks every held context release-OWED and drains (rest-time, staggered — see the gesture
+ * latch below; a zoom crossing happens mid-gesture by definition, and a one-frame mass release
+ * was itself a swap storm); crossing UP forgives owed releases still held (kept warm through
+ * the dip) and re-attempts budget-gated grants for visible clients.
*/
export function setWebglZoom(zoom: number): void {
if (!Number.isFinite(zoom)) return
@@ -128,12 +129,89 @@ export function setWebglZoom(zoom: number): void {
if (zoomSuspended) {
for (const c of clients.values()) {
cancelAcquire(c)
- reclaim(c)
+ cancelRelease(c)
+ if (c.granted) {
+ c.releaseOwed = true
+ owed.add(c)
+ }
}
+ drain()
return
}
if (!enabled) return
- for (const c of clients.values()) if (c.visible) tryGrant(c)
+ for (const c of clients.values()) {
+ // A dip below the threshold that came back before the drain got to this client: keep the
+ // context — releasing and re-granting it back-to-back is the churn this design forbids.
+ if (c.granted && c.releaseOwed) c.releaseOwed = false
+ if (c.visible && !c.granted) tryGrant(c) // defers itself while a gesture is running
+ }
+}
+
+/**
+ * THE GESTURE LATCH — the load-bearing rule of this coordinator: renderer swaps NEVER run
+ * while the user is panning/zooming.
+ *
+ * A WebGL grant/release is a heavyweight, NON-ATOMIC renderer swap (shader compile + atlas
+ * build + full repaint on grant; renderer teardown/rebuild on release). The old design executed
+ * them the moment visibility flipped — which is precisely MID-GESTURE, in bursts (a zoom-out
+ * makes dozens of nodes visible in one frame; the zoom threshold used to mass-release in one
+ * frame). Those bursts both janked the gesture (main thread stalls while compositing is already
+ * under load) and created the GPU-pressure window in which swaps die midway and strand
+ * terminals black (see TerminalNode's swap safety net).
+ *
+ * While the latch is on, every would-be swap is parked in `owed`; when the canvas comes to
+ * REST the drain executes them a few per tick (`WEBGL_SWAPS_PER_DRAIN` / `WEBGL_DRAIN_MS`), so
+ * even a huge rebalance is a calm trickle. Contexts a gesture would have taken away keep
+ * painting until rest — nothing visible is ever swapped out from under the user mid-motion.
+ */
+let gestureActive = false
+
+/** Deferred swap work: clients whose grant attempt or owed release waits for rest. */
+const owed = new Set<Client>()
+let drainTimer: ReturnType<typeof setTimeout> | null = null
+
+/** Max renderer swaps executed per drain tick — a rebalance is a trickle, never a burst. */
+export const WEBGL_SWAPS_PER_DRAIN = 2
+/** Gap between drain ticks while deferred work remains. */
+export const WEBGL_DRAIN_MS = 100
+/** How long after the last pan/zoom event the canvas counts as at rest (caller-side). */
+export const WEBGL_GESTURE_SETTLE_MS = 250
+
+/** Report whether a pan/zoom gesture is in progress. Idempotent; rest triggers the drain. */
+export function setWebglGesture(active: boolean): void {
+ if (gestureActive === active) return
+ gestureActive = active
+ if (!active) drain()
+}
+
+/** Execute deferred swaps, a few per tick, self-rescheduling while work remains. */
+function drain(): void {
+ if (drainTimer) {
+ clearTimeout(drainTimer)
+ drainTimer = null
+ }
+ if (gestureActive) return
+ let ops = 0
+ for (const c of Array.from(owed)) {
+ if (ops >= WEBGL_SWAPS_PER_DRAIN) break
+ owed.delete(c)
+ if (!clients.has(c.id)) continue
+ if (c.releaseOwed) {
+ c.releaseOwed = false
+ // Only release if the reason still holds — a client that came back (visible again, zoom
+ // resumed) keeps its warm context instead of paying a release+re-grant round trip.
+ if (c.granted && (zoomSuspended || !c.visible || !enabled)) {
+ reclaim(c)
+ ops++
+ }
+ continue
+ }
+ if (!c.granted && c.visible) {
+ tryGrant(c)
+ if (c.granted) ops++
+ }
+ }
+ if (owed.size && !drainTimer) drainTimer = setTimeout(drain, WEBGL_DRAIN_MS)
}
/**
@@ -224,6 +302,9 @@ interface Client {
hiddenAt: number
/** Consecutive EXTERNAL context losses without a visibility transition (see contextLost). */
lossStreak: number
+ /** A release is owed but deferred (gesture in progress / staggered drain). Cancelled if the
+ * reason lapses before the drain reaches it — the context is then simply kept warm. */
+ releaseOwed: boolean
}
const clients = new Map<string, Client>()
@@ -294,6 +375,12 @@ function tryGrant(c: Client): void {
if (!enabled) return
// Zoomed below the suspend threshold → never grant (see setWebglZoom).
if (zoomSuspended) return
+ // Mid-gesture → park the attempt; the rest-time drain re-runs it (see the gesture latch).
+ if (gestureActive) {
+ c.releaseOwed = false
+ owed.add(c)
+ return
+ }
if (grantCount() < budget) {
doGrant(c)
return
@@ -316,8 +403,10 @@ function setVisible(c: Client, visible: boolean): void {
// external losses lasts only until the user pans away and back (the pre-existing recovery).
c.lossStreak = 0
if (visible) {
- // Re-visible before the release fired: keep the warm context, cancel the pending release.
+ // Re-visible before the release fired: keep the warm context, cancel the pending release —
+ // including one already parked in the deferred-drain queue (releaseOwed).
cancelRelease(c)
+ c.releaseOwed = false
if (c.granted) return
// Debounce the acquire so a fast pan-through never grabs a context for a two-frame flash.
if (!c.acquireTimer) {
@@ -334,14 +423,19 @@ function setVisible(c: Client, visible: boolean): void {
if (c.granted && !c.releaseTimer) {
c.releaseTimer = setTimeout(() => {
c.releaseTimer = null
- if (c.granted) {
- try {
- c.release()
- } catch {
- // best-effort
- }
- c.granted = false
+ if (!c.granted) return
+ // Mid-gesture → park the release; a swap must never run while the user pans/zooms.
+ if (gestureActive) {
+ c.releaseOwed = true
+ owed.add(c)
+ return
}
+ try {
+ c.release()
+ } catch {
+ // best-effort
+ }
+ c.granted = false
}, WEBGL_RELEASE_DELAY_MS)
}
}
@@ -378,7 +472,8 @@ export function registerWebglClient(id: string, callbacks: WebglClientCallbacks)
acquireTimer: null,
releaseTimer: null,
hiddenAt: 0,
- lossStreak: 0
+ lossStreak: 0,
+ releaseOwed: false
}
clients.set(id, client)
@@ -410,6 +505,7 @@ export function registerWebglClient(id: string, callbacks: WebglClientCallbacks)
if (c !== client) return
cancelAcquire(c)
cancelRelease(c)
+ owed.delete(c)
if (c.granted) {
try {
c.release()
@@ -434,4 +530,10 @@ export function __resetWebglBudgetForTests(): void {
budget = WEBGL_BUDGET
enabled = true
zoomSuspended = false
+ gestureActive = false
+ owed.clear()
+ if (drainTimer) {
+ clearTimeout(drainTimer)
+ drainTimer = null
+ }
}