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(terminal): recover the WebGL renderer after sleep/wake context loss

enesfa7ba0bd7c4f
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 8d092f548..48e468c07 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -600,9 +600,11 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
try {
const addon = new WebglAddon()
// 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).
+ // renderer takes over, and tell the coordinator so its accounting drops this grant. The
+ // NODE never re-acquires from here (a per-node loop is the "Too many active WebGL
+ // contexts" storm this feature exists to stop) — the COORDINATOR schedules one delayed,
+ // budget-gated re-grant for a still-visible client (sleep/wake loses every context at
+ // once with no visibility change; see webgl-budget.ts contextLost).
addon.onContextLoss(() => {
try {
addon.dispose()
diff --git a/src/renderer/terminal/webgl-budget.test.ts b/src/renderer/terminal/webgl-budget.test.ts
index dae66a53d..f86943de7 100644
--- a/src/renderer/terminal/webgl-budget.test.ts
+++ b/src/renderer/terminal/webgl-budget.test.ts
@@ -4,6 +4,8 @@ import {
__resetWebglBudgetForTests,
WEBGL_ACQUIRE_DEBOUNCE_MS,
WEBGL_BUDGET,
+ WEBGL_LOSS_STREAK_MAX,
+ WEBGL_REACQUIRE_AFTER_LOSS_MS,
WEBGL_RELEASE_DELAY_MS,
type WebglClientHandle
} from './webgl-budget'
@@ -117,7 +119,7 @@ describe('webgl-budget coordinator', () => {
expect(a.rec.held).toBe(true)
})
- it('frees a slot when a context is lost from outside (no auto-re-grant)', () => {
+ it('frees a slot when a context is lost from outside (waiting newcomers are not auto-served)', () => {
const clients = Array.from({ length: WEBGL_BUDGET }, (_, i) => fakeClient(`c${i}`))
clients.forEach(grant)
@@ -129,7 +131,8 @@ describe('webgl-budget coordinator', () => {
// 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.
+ // The freed slot is NOT auto-handed to the waiting NEWCOMER — a transition must drive it.
+ // (The loser itself schedules a delayed retry; that is the next test's subject.)
expect(nc.rec.acquires).toBe(0)
// On the newcomer's next visibility transition it is now granted (a slot is free).
@@ -137,6 +140,56 @@ describe('webgl-budget coordinator', () => {
nc.handle.setVisible(true)
vi.advanceTimersByTime(WEBGL_ACQUIRE_DEBOUNCE_MS)
expect(nc.rec.held).toBe(true)
+
+ // The loser's own delayed retry then finds the budget full with every holder visible and
+ // declines — no second acquire, and nobody is evicted for it.
+ vi.advanceTimersByTime(WEBGL_REACQUIRE_AFTER_LOSS_MS)
+ expect(clients[0].rec.acquires).toBe(1)
+ expect(nc.rec.held).toBe(true)
+ })
+
+ it('a visible client whose context is lost externally re-acquires after the loss delay', () => {
+ // The sleep/wake shape: contexts die with NO visibility change; the client must come back
+ // on its own instead of sitting on the DOM renderer until the user pans away and back.
+ const a = fakeClient('a')
+ grant(a)
+ expect(a.rec.acquires).toBe(1)
+
+ a.handle.contextLost()
+ expect(a.rec.acquires).toBe(1) // not immediate — the GPU may still be settling
+ vi.advanceTimersByTime(WEBGL_REACQUIRE_AFTER_LOSS_MS)
+ expect(a.rec.acquires).toBe(2)
+ expect(a.rec.held).toBe(true)
+ })
+
+ it('a hidden client whose context is lost schedules no retry', () => {
+ const a = fakeClient('a')
+ grant(a)
+ a.handle.setVisible(false)
+ a.handle.contextLost()
+ vi.advanceTimersByTime(WEBGL_REACQUIRE_AFTER_LOSS_MS * 2)
+ expect(a.rec.acquires).toBe(1)
+ })
+
+ it('stops retrying after WEBGL_LOSS_STREAK_MAX consecutive losses; a visibility transition resets', () => {
+ const a = fakeClient('a')
+ grant(a)
+ // Each loss within the streak retries once…
+ for (let i = 0; i < WEBGL_LOSS_STREAK_MAX; i++) {
+ a.handle.contextLost()
+ vi.advanceTimersByTime(WEBGL_REACQUIRE_AFTER_LOSS_MS)
+ }
+ expect(a.rec.acquires).toBe(1 + WEBGL_LOSS_STREAK_MAX)
+ // …but the loss beyond the cap gives up (unstable GPU → stay on the DOM renderer).
+ a.handle.contextLost()
+ vi.advanceTimersByTime(WEBGL_REACQUIRE_AFTER_LOSS_MS * 2)
+ expect(a.rec.acquires).toBe(1 + WEBGL_LOSS_STREAK_MAX)
+
+ // Panning away and back (the pre-existing recovery) resets the streak and re-grants.
+ a.handle.setVisible(false)
+ a.handle.setVisible(true)
+ vi.advanceTimersByTime(WEBGL_ACQUIRE_DEBOUNCE_MS)
+ expect(a.rec.held).toBe(true)
})
it('dispose releases a granted context and cancels timers', () => {
diff --git a/src/renderer/terminal/webgl-budget.ts b/src/renderer/terminal/webgl-budget.ts
index 8c83362a8..bf6a7c960 100644
--- a/src/renderer/terminal/webgl-budget.ts
+++ b/src/renderer/terminal/webgl-budget.ts
@@ -30,8 +30,16 @@
* 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.
+ * `handle.contextLost()`: the grant is dropped from the accounting, and for a STILL-VISIBLE
+ * client ONE budget-gated re-grant attempt is scheduled (`WEBGL_REACQUIRE_AFTER_LOSS_MS`).
+ * Sleep/wake GPU resets lose EVERY context at once while nothing changes visibility — without
+ * the re-grant, a woken machine's terminals sat on the DOM renderer indefinitely (the
+ * "fallback feel": different cursor/scroll rendering) until the user happened to pan them out
+ * and back. This is NOT the per-node self-re-acquire loop the old "never re-grant" rule
+ * feared: the attempt goes through `tryGrant`, which never exceeds the budget and never
+ * reclaims a visible holder, so re-granting clients cannot evict each other; and repeated
+ * losses (`WEBGL_LOSS_STREAK_MAX`) stop the attempts until the next visibility transition —
+ * a genuinely unstable GPU degrades to the DOM renderer exactly as before.
*/
/** Ceiling on WebGL contexts we hold at once. Comfortably under Chromium's ~16-per-process cap. */
@@ -51,6 +59,15 @@ export const WEBGL_ACQUIRE_DEBOUNCE_MS = 150
*/
export const WEBGL_RELEASE_DELAY_MS = 2000
+/** Delay before a visible client whose context was lost EXTERNALLY (sleep/wake GPU reset) retries
+ * through the normal budget-gated grant path. Longer than the acquire debounce on purpose: right
+ * after a wake the GPU is still settling, and an immediate retry tends to lose again. */
+export const WEBGL_REACQUIRE_AFTER_LOSS_MS = 1000
+
+/** External losses in a row (without a visibility transition) after which the coordinator stops
+ * retrying and leaves the client on the DOM renderer — an unstable GPU must not be hammered. */
+export const WEBGL_LOSS_STREAK_MAX = 3
+
export interface WebglClientCallbacks {
/** Acquire the GPU context. Returns true on success, false if WebGL2 is unavailable / threw. */
acquire(): boolean
@@ -81,6 +98,8 @@ interface Client {
* SMALLEST value became hidden earliest (was visible least recently) → reclaimed first.
*/
hiddenAt: number
+ /** Consecutive EXTERNAL context losses without a visibility transition (see contextLost). */
+ lossStreak: number
}
const clients = new Map<string, Client>()
@@ -165,6 +184,9 @@ function tryGrant(c: Client): void {
function setVisible(c: Client, visible: boolean): void {
if (c.visible === visible) return
c.visible = visible
+ // A real visibility transition resets the loss streak: the give-up state after repeated
+ // 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.
cancelRelease(c)
@@ -227,7 +249,8 @@ export function registerWebglClient(id: string, callbacks: WebglClientCallbacks)
granted: false,
acquireTimer: null,
releaseTimer: null,
- hiddenAt: 0
+ hiddenAt: 0,
+ lossStreak: 0
}
clients.set(id, client)
@@ -239,10 +262,20 @@ export function registerWebglClient(id: string, callbacks: WebglClientCallbacks)
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.
+ // The browser (or our own dispose) already tore the context down; drop the accounting.
cancelRelease(c)
c.granted = false
+ // Sleep/wake GPU resets lose every context at once with no visibility change, so a
+ // still-visible client schedules ONE delayed, budget-gated re-grant attempt (see the
+ // header). A streak of losses means the GPU is unstable → stop until the user pans the
+ // node out and back (setVisible resets the streak).
+ c.lossStreak += 1
+ if (c.visible && c.lossStreak <= WEBGL_LOSS_STREAK_MAX && !c.acquireTimer) {
+ c.acquireTimer = setTimeout(() => {
+ c.acquireTimer = null
+ tryGrant(c)
+ }, WEBGL_REACQUIRE_AFTER_LOSS_MS)
+ }
},
dispose() {
const c = clients.get(id)