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): budget coordinator so we never overshoot the browser context cap

enesf1f5da788103
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 40ead62b7..647fbcc72 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -40,12 +40,11 @@ import {
takeRecycled,
terminalKeyAction,
toXtermText,
- webglVisibilityAction,
SHIFT_ENTER_SEQ,
- WEBGL_RELEASE_DELAY_MS,
xtermScrollback,
type SessionLife
} from '../terminal/terminal-config'
+import { registerWebglClient, type WebglClientHandle } from '../terminal/webgl-budget'
import { FindBar } from '../components/FindBar'
import { IconSearch, IconChat } from '../components/icons'
import { NodeTags } from '../components/NodeTags'
@@ -548,21 +547,22 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
// GPU renderer: xterm's default DOM renderer doesn't scale to many terminals streaming
// at once. Must load after open(). Browsers cap live WebGL contexts (~16), and a busy canvas
- // holds far more terminals than that, so a context is NOT acquired per mounted node — it is
- // scoped to VISIBILITY: an IntersectionObserver (below) acquires the addon when the node enters
- // the viewport and releases it when the node leaves (after a short delay). The user rarely SEES
- // more than ~16 terminals at once, so the cap stops being hit and the terminals actually being
- // watched always get the GPU renderer; the rest fall back to the DOM renderer.
+ // holds far more terminals than that, so a context is NOT acquired per mounted node. The
+ // module-level BUDGET COORDINATOR (`webgl-budget.ts`) owns the grant decision and all timing:
+ // this node reports viewport visibility (via the IntersectionObserver below), and the
+ // coordinator calls back into `acquireWebgl`/`releaseWebgl`, keeping the total contexts WE hold
+ // under `WEBGL_BUDGET` so the browser never has to force-evict (which is what flashed the dead
+ // "lost context" placeholder). The callbacks stay dumb and idempotent.
let webgl: WebglAddon | null = null
- const acquireWebgl = () => {
- if (webgl) return
+ let webglHandle: WebglClientHandle | null = null
+ const acquireWebgl = (): boolean => {
+ if (webgl) return true
try {
const addon = new WebglAddon()
- // Browser evicted us anyway (two > 16-visible terminals can still race the cap): dispose and
- // null the reference so the DOM renderer takes over. Do NOT re-acquire from here — two
- // terminals fighting over the cap would evict each other in an infinite loop (exactly the
- // "Too many active WebGL contexts" storm this feature exists to stop). Re-acquisition is left
- // to the next visibility transition, which is naturally rate-limited by the user's panning.
+ // The browser lost this context out from under us. Dispose + null the reference so the DOM
+ // renderer takes over, and tell the coordinator so its accounting drops this grant. Do NOT
+ // re-acquire from here — the next visibility transition / reclaim decides (re-acquiring in a
+ // loop is exactly the "Too many active WebGL contexts" storm this feature exists to stop).
addon.onContextLoss(() => {
try {
addon.dispose()
@@ -570,11 +570,15 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
// already disposed
}
if (webgl === addon) webgl = null
+ webglHandle?.contextLost()
})
term.loadAddon(addon)
webgl = addon
+ return true
} catch {
- // WebGL2 unavailable — DOM renderer remains active.
+ // WebGL2 unavailable — DOM renderer remains active. Returning false tells the coordinator
+ // not to count this as a held context (it must not burn a budget slot).
+ return false
}
}
const releaseWebgl = () => {
@@ -1076,21 +1080,16 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
})
observer.observe(container)
- // Viewport-scoped WebGL: acquire the GPU context when this node is visible, release it after a
- // delay when it leaves. IntersectionObserver measures against the rendered box, so React Flow's
- // pan/zoom CSS transform is accounted for natively — no coupling to the React Flow store, and it
- // works identically in the browser Server Edition. `rootMargin` acquires slightly before a
- // node panning into view fully enters. The observer's initial callback (queued shortly after
- // `observe()`) is what (re)acquires the context on mount/adopt — this replaces the old
- // unconditional `loadWebgl()` calls in both the parked and fresh paths above; the DOM renderer
- // covers the brief gap until it fires.
- let webglReleaseTimer: ReturnType<typeof setTimeout> | null = null
- const cancelWebglRelease = () => {
- if (webglReleaseTimer) {
- clearTimeout(webglReleaseTimer)
- webglReleaseTimer = null
- }
- }
+ // Viewport-scoped WebGL, coordinated by the module-level budget (`webgl-budget.ts`): the
+ // IntersectionObserver only REPORTS visibility to the coordinator, which owns the grant decision
+ // and all timing (acquire debounce, release delay, and LRU-hidden reclaim so we never exceed the
+ // budget). IntersectionObserver measures against the rendered box, so React Flow's pan/zoom CSS
+ // transform is accounted for natively — no coupling to the React Flow store, and it works
+ // identically in the browser Server Edition. `rootMargin` pre-announces a node panning into
+ // view. The observer's initial callback (queued shortly after `observe()`) is what reports
+ // visibility on mount/adopt — this replaces the old unconditional `loadWebgl()` calls in both
+ // the parked and fresh paths above; the DOM renderer covers the gap until a grant lands.
+ webglHandle = registerWebglClient(id, { acquire: acquireWebgl, release: releaseWebgl })
const visibilityObserver = new IntersectionObserver(
(entries) => {
// disconnect() does not flush already-QUEUED notifications (Blink delivers them after),
@@ -1098,24 +1097,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
// context onto a parked/disposed terminal — the very leak this feature exists to prevent.
if (disposed) return
const visible = entries[entries.length - 1]?.isIntersecting ?? false
- switch (webglVisibilityAction(visible, webgl !== null)) {
- case 'acquire':
- cancelWebglRelease()
- acquireWebgl()
- break
- case 'cancel-release':
- cancelWebglRelease()
- break
- case 'schedule-release':
- if (!webglReleaseTimer)
- webglReleaseTimer = setTimeout(() => {
- webglReleaseTimer = null
- releaseWebgl()
- }, WEBGL_RELEASE_DELAY_MS)
- break
- case 'none':
- break
- }
+ webglHandle?.setVisible(visible)
},
{ rootMargin: '256px' }
)
@@ -1125,7 +1107,6 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
disposed = true
observer.disconnect()
visibilityObserver.disconnect()
- cancelWebglRelease()
if (resizeTimer) clearTimeout(resizeTimer)
if (dwellRef.current) clearTimeout(dwellRef.current)
useAgentStatus.getState().setActive(id, false)
@@ -1144,10 +1125,11 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
fitRef.current = null
searchAddonRef.current = null
if (applyFitRef.current === applyFit) applyFitRef.current = null
- // Free the GPU context on unmount (park or teardown) either way — the park path must keep
- // releasing it as it always has (live WebGL contexts are capped ~16, and a parked terminal is
- // by definition off-screen).
- releaseWebgl()
+ // Free the GPU context on unmount (park or teardown) either way, and unregister from the
+ // budget coordinator (which releases any held grant + cancels its timers). The park path must
+ // keep releasing it as it always has (contexts are capped ~16, and a parked terminal is
+ // off-screen); a remount re-registers a fresh handle and the observer re-reports visibility.
+ webglHandle?.dispose()
// A respawn (worktree move: the ref was bumped before this cleanup ran) needs a FRESH
// session in the new cwd — never park it. A plain unmount with a live session parks:
// the xterm (element detached) and its PTY stay alive so a remount re-adopts them. A session
diff --git a/src/renderer/terminal/terminal-config.test.ts b/src/renderer/terminal/terminal-config.test.ts
index 117fadc63..5763b6119 100644
--- a/src/renderer/terminal/terminal-config.test.ts
+++ b/src/renderer/terminal/terminal-config.test.ts
@@ -20,7 +20,6 @@ import {
takeRecycled,
terminalKeyAction,
toXtermText,
- webglVisibilityAction,
xtermScrollback,
RESYNC_NOTICE,
SHIFT_ENTER_SEQ,
@@ -619,21 +618,3 @@ describe('repaintResync', () => {
expect(term.ops).toContain('write:TWO')
})
})
-
-describe('webglVisibilityAction', () => {
- it('visible + not held → acquire', () => {
- expect(webglVisibilityAction(true, false)).toBe('acquire')
- })
-
- it('visible + held → cancel-release (a pan swept back before the release timer fired)', () => {
- expect(webglVisibilityAction(true, true)).toBe('cancel-release')
- })
-
- it('hidden + held → schedule-release', () => {
- expect(webglVisibilityAction(false, true)).toBe('schedule-release')
- })
-
- it('hidden + not held → none', () => {
- expect(webglVisibilityAction(false, false)).toBe('none')
- })
-})
diff --git a/src/renderer/terminal/terminal-config.ts b/src/renderer/terminal/terminal-config.ts
index 69340fa8c..102640ab5 100644
--- a/src/renderer/terminal/terminal-config.ts
+++ b/src/renderer/terminal/terminal-config.ts
@@ -120,33 +120,6 @@ export function shouldApplyResync(screen: string | null | undefined): screen is
return typeof screen === 'string' && screen.length > 0
}
-/**
- * How long a terminal that scrolled out of the viewport keeps its WebGL context before releasing
- * it. WebGL contexts belong to terminals the user can actually SEE, not to every mounted node —
- * Chromium caps live contexts at ~16, and a busy canvas holds far more terminals than that, so an
- * IntersectionObserver acquires the context on entry and releases it on exit. The delay exists so a
- * pan that merely SWEEPS a node across the viewport does not churn contexts (acquire → immediately
- * release); a visibility=true event within the window cancels the pending release.
- */
-export const WEBGL_RELEASE_DELAY_MS = 2000
-
-/**
- * The visibility state machine behind the per-node WebGL context (the DOM glue — an
- * IntersectionObserver + a release timer — lives in `TerminalNode`, but the decision is pure so it
- * can be pinned by a test without a DOM):
- * - `acquire` — visible and we hold no context: load the WebGL addon.
- * - `cancel-release` — visible and we already hold one: cancel any pending release (a pan swept
- * back before the timer fired).
- * - `schedule-release` — not visible but we still hold a context: start the release timer.
- * - `none` — not visible and hold nothing: nothing to do.
- */
-export type WebglVisibilityAction = 'acquire' | 'cancel-release' | 'schedule-release' | 'none'
-
-export function webglVisibilityAction(visible: boolean, held: boolean): WebglVisibilityAction {
- if (visible) return held ? 'cancel-release' : 'acquire'
- return held ? 'schedule-release' : 'none'
-}
-
/** Hard cap on xterm's in-memory scrollback: the cost is per node and one canvas holds many. */
export const XTERM_SCROLLBACK_MAX = 10000
diff --git a/src/renderer/terminal/webgl-budget.test.ts b/src/renderer/terminal/webgl-budget.test.ts
new file mode 100644
index 000000000..6502657da
--- /dev/null
+++ b/src/renderer/terminal/webgl-budget.test.ts
@@ -0,0 +1,176 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ registerWebglClient,
+ __resetWebglBudgetForTests,
+ WEBGL_ACQUIRE_DEBOUNCE_MS,
+ WEBGL_BUDGET,
+ WEBGL_RELEASE_DELAY_MS,
+ type WebglClientHandle
+} from './webgl-budget'
+
+/** A fake client that records acquire/release calls and reports a configurable acquire result. */
+function fakeClient(id: string, opts: { acquireOk?: boolean } = {}) {
+ const rec = { acquires: 0, releases: 0, held: false }
+ const acquireOk = opts.acquireOk ?? true
+ const handle: WebglClientHandle = registerWebglClient(id, {
+ acquire() {
+ rec.acquires++
+ if (acquireOk) rec.held = true
+ return acquireOk
+ },
+ release() {
+ rec.releases++
+ rec.held = false
+ }
+ })
+ return { id, rec, handle }
+}
+
+/** Bring a client to a granted state: make it visible and let the debounce fire. */
+function grant(c: ReturnType<typeof fakeClient>) {
+ c.handle.setVisible(true)
+ vi.advanceTimersByTime(WEBGL_ACQUIRE_DEBOUNCE_MS)
+}
+
+describe('webgl-budget coordinator', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ __resetWebglBudgetForTests()
+ })
+ afterEach(() => {
+ __resetWebglBudgetForTests()
+ vi.useRealTimers()
+ })
+
+ it('grants a visible client (after debounce) when under budget', () => {
+ const a = fakeClient('a')
+ a.handle.setVisible(true)
+ // Not yet: still inside the debounce window.
+ vi.advanceTimersByTime(WEBGL_ACQUIRE_DEBOUNCE_MS - 1)
+ expect(a.rec.acquires).toBe(0)
+ vi.advanceTimersByTime(1)
+ expect(a.rec.acquires).toBe(1)
+ expect(a.rec.held).toBe(true)
+ })
+
+ it('does not acquire for a client visible for less than the debounce', () => {
+ const a = fakeClient('a')
+ a.handle.setVisible(true)
+ vi.advanceTimersByTime(WEBGL_ACQUIRE_DEBOUNCE_MS - 1)
+ a.handle.setVisible(false)
+ vi.advanceTimersByTime(WEBGL_ACQUIRE_DEBOUNCE_MS * 5)
+ expect(a.rec.acquires).toBe(0)
+ })
+
+ it('reclaims the least-recently-visible hidden holder when the budget is full', () => {
+ const clients = Array.from({ length: WEBGL_BUDGET }, (_, i) => fakeClient(`c${i}`))
+ clients.forEach(grant)
+ expect(clients.every((c) => c.rec.held)).toBe(true)
+
+ // Hide c0 first, then c1 — c0 is now the least-recently-visible hidden holder. Both keep their
+ // (warm) context for the release delay.
+ clients[0].handle.setVisible(false)
+ clients[1].handle.setVisible(false)
+ expect(clients[0].rec.held).toBe(true)
+ expect(clients[1].rec.held).toBe(true)
+
+ // A newcomer becomes visible while the budget is still full → reclaim c0 (the LRU hidden
+ // holder), bypassing its release delay, and grant the newcomer.
+ const nc = fakeClient('newcomer')
+ grant(nc)
+ expect(clients[0].rec.releases).toBe(1) // reclaimed on demand
+ expect(clients[1].rec.releases).toBe(0) // more recently visible → spared
+ expect(nc.rec.held).toBe(true)
+ })
+
+ it('refuses to grant when every holder is currently visible (never exceeds budget)', () => {
+ const clients = Array.from({ length: WEBGL_BUDGET }, (_, i) => fakeClient(`c${i}`))
+ clients.forEach(grant)
+ // All BUDGET holders are visible; a further visible client must NOT be granted (no eviction).
+ const extra = fakeClient('extra')
+ grant(extra)
+ expect(extra.rec.acquires).toBe(0)
+ expect(extra.rec.held).toBe(false)
+ expect(clients.every((c) => c.rec.held)).toBe(true)
+ })
+
+ it('releases a hidden holder after the release delay', () => {
+ const a = fakeClient('a')
+ grant(a)
+ a.handle.setVisible(false)
+ vi.advanceTimersByTime(WEBGL_RELEASE_DELAY_MS - 1)
+ expect(a.rec.releases).toBe(0)
+ vi.advanceTimersByTime(1)
+ expect(a.rec.releases).toBe(1)
+ expect(a.rec.held).toBe(false)
+ })
+
+ it('cancels the pending release when a hidden holder becomes visible again', () => {
+ const a = fakeClient('a')
+ grant(a)
+ a.handle.setVisible(false)
+ vi.advanceTimersByTime(WEBGL_RELEASE_DELAY_MS - 100)
+ a.handle.setVisible(true) // pan-back before the release fired
+ vi.advanceTimersByTime(WEBGL_RELEASE_DELAY_MS * 2)
+ expect(a.rec.releases).toBe(0)
+ expect(a.rec.acquires).toBe(1) // still held, not re-acquired
+ expect(a.rec.held).toBe(true)
+ })
+
+ it('frees a slot when a context is lost from outside (no auto-re-grant)', () => {
+ const clients = Array.from({ length: WEBGL_BUDGET }, (_, i) => fakeClient(`c${i}`))
+ clients.forEach(grant)
+
+ // A visible newcomer cannot be granted while full and all holders visible.
+ const nc = fakeClient('nc')
+ grant(nc)
+ expect(nc.rec.held).toBe(false)
+
+ // One holder's context is lost (browser eviction / our own dispose reported it).
+ clients[0].handle.contextLost()
+
+ // The freed slot is NOT auto-handed to the waiting newcomer — a transition must drive it.
+ expect(nc.rec.acquires).toBe(0)
+
+ // On the newcomer's next visibility transition it is now granted (a slot is free).
+ nc.handle.setVisible(false)
+ nc.handle.setVisible(true)
+ vi.advanceTimersByTime(WEBGL_ACQUIRE_DEBOUNCE_MS)
+ expect(nc.rec.held).toBe(true)
+ })
+
+ it('dispose releases a granted context and cancels timers', () => {
+ const a = fakeClient('a')
+ grant(a)
+ expect(a.rec.held).toBe(true)
+ a.handle.dispose()
+ expect(a.rec.releases).toBe(1)
+ expect(a.rec.held).toBe(false)
+
+ // A disposed client frees its slot for others.
+ const others = Array.from({ length: WEBGL_BUDGET }, (_, i) => fakeClient(`o${i}`))
+ others.forEach(grant)
+ expect(others.every((c) => c.rec.held)).toBe(true)
+ })
+
+ it('dispose cancels a pending acquire debounce (no acquire after unmount)', () => {
+ const a = fakeClient('a')
+ a.handle.setVisible(true)
+ a.handle.dispose()
+ vi.advanceTimersByTime(WEBGL_ACQUIRE_DEBOUNCE_MS * 5)
+ expect(a.rec.acquires).toBe(0)
+ })
+
+ it('an acquire that returns false does not burn a budget slot', () => {
+ // A client whose WebGL2 is unavailable: acquire returns false.
+ const bad = fakeClient('bad', { acquireOk: false })
+ grant(bad)
+ expect(bad.rec.acquires).toBe(1)
+ expect(bad.rec.held).toBe(false)
+
+ // The full budget is still available to real clients.
+ const clients = Array.from({ length: WEBGL_BUDGET }, (_, i) => fakeClient(`c${i}`))
+ clients.forEach(grant)
+ expect(clients.every((c) => c.rec.held)).toBe(true)
+ })
+})
diff --git a/src/renderer/terminal/webgl-budget.ts b/src/renderer/terminal/webgl-budget.ts
new file mode 100644
index 000000000..795e09680
--- /dev/null
+++ b/src/renderer/terminal/webgl-budget.ts
@@ -0,0 +1,262 @@
+/**
+ * Module-level WebGL context BUDGET coordinator.
+ *
+ * Chromium caps live WebGL contexts per process at ~16. When a page tries to exceed that cap the
+ * browser force-EVICTS an existing context to make room — and that victim is sometimes a context
+ * belonging to a terminal the user is currently looking at, which then paints as Chromium's
+ * "lost context" dead-canvas placeholder (a white box with a sad-face icon) until our own
+ * `onContextLoss` → dispose → DOM-fallback lands a beat later.
+ *
+ * The per-node IntersectionObserver decisions (acquire when visible, release after a delay when
+ * hidden) are each individually correct but globally UN-coordinated: a fast pan across a
+ * 30-terminal canvas, or zooming out past ~16 visible terminals, momentarily OVERSHOOTS the cap —
+ * nodes panned away from keep their context for the release delay while newly visible nodes each
+ * acquire immediately — so the browser force-evicts, and the dead placeholder flashes.
+ *
+ * This coordinator keeps the number of contexts WE hold at or under `WEBGL_BUDGET`, which sits
+ * comfortably below the browser cap. If we never exceed it ourselves, the browser never has to
+ * force-evict anyone, so the dead placeholder cannot appear. The coordinator owns ALL timing and
+ * the grant decision; the per-node `acquire`/`release` callbacks stay dumb and idempotent.
+ *
+ * Grant rules:
+ * - A client that becomes visible is granted only after a short ACQUIRE DEBOUNCE
+ * (`WEBGL_ACQUIRE_DEBOUNCE_MS`), so a fast pan sweeping a node across the viewport for a couple
+ * of frames never acquires. (`rootMargin` on the observer already pre-announces approach.)
+ * - If granting would exceed the budget, the coordinator immediately RECLAIMS from the
+ * least-recently-visible HIDDEN holder (bypassing that holder's release delay). If every holder
+ * is currently visible (zoomed way out), the newcomer is NOT granted and stays on the DOM
+ * renderer. Either way we never push past the budget, so the browser never force-evicts.
+ * - A client that becomes hidden keeps its context for `WEBGL_RELEASE_DELAY_MS` (warm for a
+ * pan-back) but is the first reclaim candidate during that window.
+ * - `acquire()` returning false (WebGL2 unavailable / threw) does not count against the budget.
+ * - A context lost from outside (the addon's own `onContextLoss`) is reported via
+ * `handle.contextLost()`; the coordinator simply drops that grant from its accounting and does
+ * NOT auto-re-grant — the next visibility transition or reclaim decides.
+ */
+
+/** Ceiling on WebGL contexts we hold at once. Comfortably under Chromium's ~16-per-process cap. */
+export const WEBGL_BUDGET = 12
+
+/**
+ * How long a client must stay continuously visible before it is granted a context. Absorbs fast
+ * pans that sweep a node across the viewport for only a frame or two (which must not acquire).
+ */
+export const WEBGL_ACQUIRE_DEBOUNCE_MS = 150
+
+/**
+ * How long a client that scrolled out of the viewport keeps its context before the coordinator
+ * releases it on its own. The context stays warm for a quick pan-back; a re-visible transition
+ * within the window cancels the pending release. A hidden holder is also the first candidate to be
+ * reclaimed on demand when a newly visible client needs a slot, bypassing this delay.
+ */
+export const WEBGL_RELEASE_DELAY_MS = 2000
+
+export interface WebglClientCallbacks {
+ /** Acquire the GPU context. Returns true on success, false if WebGL2 is unavailable / threw. */
+ acquire(): boolean
+ /** Release the GPU context. Must be idempotent (a no-op when nothing is held). */
+ release(): void
+}
+
+export interface WebglClientHandle {
+ /** Report this node's viewport visibility (driven by its IntersectionObserver). */
+ setVisible(visible: boolean): void
+ /** Report that the addon's own `onContextLoss` fired: drop this grant from the accounting. */
+ contextLost(): void
+ /** Node unmount: release any held context, cancel timers, and forget this client. */
+ dispose(): void
+}
+
+interface Client {
+ id: string
+ acquire: () => boolean
+ release: () => void
+ visible: boolean
+ /** Whether we believe this client currently holds a live context (counts against the budget). */
+ granted: boolean
+ acquireTimer: ReturnType<typeof setTimeout> | null
+ releaseTimer: ReturnType<typeof setTimeout> | null
+ /**
+ * Monotonic tick recorded each time the client becomes hidden. Among hidden holders, the
+ * SMALLEST value became hidden earliest (was visible least recently) → reclaimed first.
+ */
+ hiddenAt: number
+}
+
+const clients = new Map<string, Client>()
+
+/** Monotonic clock for LRU ordering — independent of wall-clock / fake timers. */
+let visibilityClock = 0
+
+function grantCount(): number {
+ let n = 0
+ for (const c of clients.values()) if (c.granted) n++
+ return n
+}
+
+function cancelAcquire(c: Client): void {
+ if (c.acquireTimer) {
+ clearTimeout(c.acquireTimer)
+ c.acquireTimer = null
+ }
+}
+
+function cancelRelease(c: Client): void {
+ if (c.releaseTimer) {
+ clearTimeout(c.releaseTimer)
+ c.releaseTimer = null
+ }
+}
+
+/** Release a client's context now, bypassing any pending release delay. */
+function reclaim(c: Client): void {
+ cancelRelease(c)
+ if (!c.granted) return
+ try {
+ c.release()
+ } catch {
+ // release is best-effort; drop the grant regardless.
+ }
+ c.granted = false
+}
+
+/** The least-recently-visible HIDDEN holder, or null if every holder is currently visible. */
+function lruHiddenHolder(): Client | null {
+ let best: Client | null = null
+ for (const c of clients.values()) {
+ if (!c.granted || c.visible) continue
+ if (!best || c.hiddenAt < best.hiddenAt) best = c
+ }
+ return best
+}
+
+function doGrant(c: Client): void {
+ let ok = false
+ try {
+ ok = c.acquire()
+ } catch {
+ // acquire threw — treat as unavailable; do not count against the budget.
+ ok = false
+ }
+ // A false / thrown acquire (WebGL2 unavailable) must NOT burn a slot: leave `granted` false.
+ if (ok) c.granted = true
+}
+
+/** Attempt to grant `c` a context, reclaiming a hidden holder's slot if the budget is full. */
+function tryGrant(c: Client): void {
+ cancelAcquire(c)
+ // Guard: the client may have gone hidden or been disposed between debounce start and fire.
+ if (!clients.has(c.id) || !c.visible || c.granted) return
+ if (grantCount() < WEBGL_BUDGET) {
+ doGrant(c)
+ return
+ }
+ // Full: reclaim the least-recently-visible hidden holder to free exactly one slot.
+ const victim = lruHiddenHolder()
+ if (!victim) {
+ // Every holder is currently visible (zoomed way out): do not push past the budget. The
+ // newcomer stays on the DOM renderer until a later visibility transition frees a slot.
+ return
+ }
+ reclaim(victim)
+ doGrant(c)
+}
+
+function setVisible(c: Client, visible: boolean): void {
+ if (c.visible === visible) return
+ c.visible = visible
+ if (visible) {
+ // Re-visible before the release fired: keep the warm context, cancel the pending release.
+ cancelRelease(c)
+ if (c.granted) return
+ // Debounce the acquire so a fast pan-through never grabs a context for a two-frame flash.
+ if (!c.acquireTimer) {
+ c.acquireTimer = setTimeout(() => {
+ c.acquireTimer = null
+ tryGrant(c)
+ }, WEBGL_ACQUIRE_DEBOUNCE_MS)
+ }
+ return
+ }
+ // Became hidden.
+ c.hiddenAt = ++visibilityClock
+ cancelAcquire(c)
+ if (c.granted && !c.releaseTimer) {
+ c.releaseTimer = setTimeout(() => {
+ c.releaseTimer = null
+ if (c.granted) {
+ try {
+ c.release()
+ } catch {
+ // best-effort
+ }
+ c.granted = false
+ }
+ }, WEBGL_RELEASE_DELAY_MS)
+ }
+}
+
+/**
+ * Register a terminal node as a WebGL client. The coordinator calls `acquire`/`release` to grant
+ * or reclaim the GPU context; the node drives `handle.setVisible` from its IntersectionObserver,
+ * reports external context loss via `handle.contextLost`, and calls `handle.dispose` on unmount.
+ */
+export function registerWebglClient(id: string, callbacks: WebglClientCallbacks): WebglClientHandle {
+ // A re-register under the same id (e.g. a remount that raced teardown) supersedes the old entry.
+ const existing = clients.get(id)
+ if (existing) {
+ cancelAcquire(existing)
+ cancelRelease(existing)
+ }
+ const client: Client = {
+ id,
+ acquire: callbacks.acquire,
+ release: callbacks.release,
+ visible: false,
+ granted: false,
+ acquireTimer: null,
+ releaseTimer: null,
+ hiddenAt: 0
+ }
+ clients.set(id, client)
+
+ return {
+ setVisible(visible: boolean) {
+ const c = clients.get(id)
+ if (c === client) setVisible(c, visible)
+ },
+ contextLost() {
+ const c = clients.get(id)
+ if (c !== client) return
+ // The browser (or our own dispose) already tore the context down; just drop the accounting.
+ // Do NOT auto-re-grant — the next visibility transition or reclaim decides.
+ cancelRelease(c)
+ c.granted = false
+ },
+ dispose() {
+ const c = clients.get(id)
+ if (c !== client) return
+ cancelAcquire(c)
+ cancelRelease(c)
+ if (c.granted) {
+ try {
+ c.release()
+ } catch {
+ // best-effort
+ }
+ c.granted = false
+ }
+ clients.delete(id)
+ }
+ }
+}
+
+/** Test-only: clear all coordinator state between cases. */
+export function __resetWebglBudgetForTests(): void {
+ for (const c of clients.values()) {
+ cancelAcquire(c)
+ cancelRelease(c)
+ }
+ clients.clear()
+ visibilityClock = 0
+}