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): rebuild the renderer when the browser restores a WebGL context

enes3beb0421c879
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 1963e4be7..b7593cb97 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -1702,14 +1702,53 @@ export function TerminalNode({
})
term.loadAddon(a)
webgl = a
- // A force-evicted context the browser later RESTORES (GPU memory pressure, sleep/wake)
- // goes through the addon's webglcontextrestored handler — re-init + redraw with no error
- // handling, and the redraw is swallowable (see fullRepaint). The addon exposes no
- // onContextRestored and the event does not bubble, so listen on its canvas directly and
- // repaint a beat after its handler ran. The listener dies with the addon's canvas.
- term.element
- ?.querySelector<HTMLCanvasElement>('.xterm-screen canvas')
- ?.addEventListener('webglcontextrestored', fullRepaint)
+ // THE RESTORE PATH — rebuild, never trust the addon's in-place recovery.
+ //
+ // When the GPU process resets (returning from a GPU-heavy app; sleep/wake; memory
+ // pressure) the browser loses EVERY context on the page and then restores them. That
+ // restore never reaches `onContextLoss`: the addon arms a 3s timer on
+ // `webglcontextlost` and CANCELS it when the restore lands, so the coordinator is never
+ // told and the terminal's recovery is entirely the addon's own handler — which
+ // re-initializes GL state while the previous context's objects are disposed against the
+ // NEW context. That is not a theory: forcing a page-wide lose+restore in the harness
+ // reproduces the field console exactly (`webglcontextrestored` per terminal, then a
+ // storm of `INVALID_OPERATION: delete: object does not belong to this context`), and in
+ // the field it left terminals painting their backgrounds with NO GLYPHS — a live
+ // rectangle renderer over a broken glyph atlas, which no repaint of ours can heal
+ // (`term.refresh` re-runs the same broken renderer).
+ //
+ // So a restore is treated as what it materially is — this context is gone: drop the
+ // addon (xterm falls back to its DOM renderer synchronously, text visible), sweep the
+ // stray canvas, and report the loss so the COORDINATOR re-grants a FRESH addon with a
+ // fresh atlas on its usual path — budget-gated, delayed by
+ // `WEBGL_REACQUIRE_AFTER_LOSS_MS`, and abandoned after `WEBGL_LOSS_STREAK_MAX` losses so
+ // an unstable GPU degrades to the DOM renderer instead of being hammered. The listener
+ // dies with the addon's canvas.
+ // …on the ADDON's canvas, which is not the first one in `.xterm-screen`: xterm appends its
+ // own `.xterm-link-layer` (a 2d canvas) ahead of it, so the obvious
+ // `querySelector('.xterm-screen canvas')` resolves to the LINK LAYER — a canvas that can
+ // never fire a WebGL event. That is what the listener this replaces was bound to, so the
+ // restore hook has never once run in the field; verified in the harness by enumerating
+ // the screen's canvases (index 0 `.xterm-link-layer`, no webgl2 context; index 1
+ // class-less, webgl2).
+ const addonCanvas = term.element
+ ? Array.from(term.element.querySelectorAll<HTMLCanvasElement>('.xterm-screen canvas')).find(
+ (c) => !c.classList.contains('xterm-link-layer')
+ )
+ : undefined
+ addonCanvas?.addEventListener('webglcontextrestored', () => {
+ if (webgl !== a) return
+ try {
+ a.dispose()
+ } catch {
+ // the addon's own restore handler may have left it half-built — the sweep below is
+ // what actually guarantees the terminal is back on a renderer that paints.
+ }
+ webgl = null
+ verifyCleanDomState('context-restored')
+ fullRepaint()
+ webglHandle?.contextLost()
+ })
// A fresh addon starts from an EMPTY model; the swap's own refresh is the exact one
// that gets swallowed when this grant races a park/pause. Repaint unconditionally.
fullRepaint()
diff --git a/src/renderer/terminal/webgl-budget.test.ts b/src/renderer/terminal/webgl-budget.test.ts
index acb3068e4..daa23c4a0 100644
--- a/src/renderer/terminal/webgl-budget.test.ts
+++ b/src/renderer/terminal/webgl-budget.test.ts
@@ -209,6 +209,47 @@ describe('webgl-budget coordinator', () => {
expect(a.rec.held).toBe(true)
})
+ it('a page-wide loss re-grants as a TRICKLE, not a burst (the GPU-reset shape)', () => {
+ // A GPU process reset loses every context at once, so every visible client reports the loss
+ // and their retries all come due together. The re-grants go through the drain, so the
+ // rebuilds spread out at WEBGL_SWAPS_PER_DRAIN per tick instead of landing in one frame.
+ // (`contextLost` drops the accounting only — the caller has already disposed the dead addon,
+ // which is why the acquire COUNT, not `held`, is what says a rebuild happened.)
+ const clients = ['a', 'b', 'c', 'd', 'e'].map((id) => fakeClient(id))
+ clients.forEach(grant)
+ expect(clients.every((c) => c.rec.acquires === 1)).toBe(true)
+
+ clients.forEach((c) => c.handle.contextLost())
+ const rebuilt = () => clients.filter((c) => c.rec.acquires === 2).length
+
+ // Every retry comes due in the same frame; the queue caps what that frame may execute.
+ vi.advanceTimersByTime(WEBGL_REACQUIRE_AFTER_LOSS_MS)
+ const firstFrame = rebuilt()
+ expect(firstFrame).toBeGreaterThan(0)
+ expect(firstFrame).toBeLessThanOrEqual(WEBGL_SWAPS_PER_DRAIN)
+ expect(firstFrame).toBeLessThan(clients.length) // the burst is what this prevents
+
+ // …and each tick after it moves at most a batch further.
+ const secondFrame = (vi.advanceTimersByTime(WEBGL_DRAIN_MS), rebuilt())
+ expect(secondFrame).toBeGreaterThan(firstFrame)
+ expect(secondFrame - firstFrame).toBeLessThanOrEqual(WEBGL_SWAPS_PER_DRAIN)
+
+ // …until every terminal is back on the GPU.
+ vi.advanceTimersByTime(WEBGL_DRAIN_MS * 5)
+ expect(rebuilt()).toBe(clients.length)
+ })
+
+ it('a post-loss re-grant waits for the canvas to come to rest (no rebuild mid-gesture)', () => {
+ const a = fakeClient('a')
+ grant(a)
+ a.handle.contextLost()
+ setWebglGesture(true)
+ vi.advanceTimersByTime(WEBGL_REACQUIRE_AFTER_LOSS_MS + WEBGL_DRAIN_MS * 5)
+ expect(a.rec.acquires).toBe(1) // parked, not rebuilt under the user's hand
+ setWebglGesture(false)
+ expect(a.rec.acquires).toBe(2)
+ })
+
it('a hidden client whose context is lost schedules no retry', () => {
const a = fakeClient('a')
grant(a)
diff --git a/src/renderer/terminal/webgl-budget.ts b/src/renderer/terminal/webgl-budget.ts
index f2356e31f..9811687c3 100644
--- a/src/renderer/terminal/webgl-budget.ts
+++ b/src/renderer/terminal/webgl-budget.ts
@@ -145,11 +145,18 @@ export function setWebglGesture(active: boolean): void {
/** Execute deferred swaps, a few per tick, self-rescheduling while work remains. */
function drain(): void {
- if (drainTimer) {
- clearTimeout(drainTimer)
- drainTimer = null
+ if (gestureActive) {
+ if (drainTimer) {
+ clearTimeout(drainTimer)
+ drainTimer = null
+ }
+ return
}
- if (gestureActive) return
+ // A cycle is already running: new work joins the queue and rides its next tick. Without this
+ // the per-tick budget would really be per-CALLER, and the burst that matters arrives one
+ // client at a time — a GPU process reset gives every client its own retry timer, so each
+ // would otherwise find an idle drain and spend the whole budget on itself.
+ if (drainTimer) return
let ops = 0
for (const c of Array.from(owed)) {
if (ops >= WEBGL_SWAPS_PER_DRAIN) break
@@ -170,7 +177,13 @@ function drain(): void {
if (c.granted) ops++
}
}
- if (owed.size && !drainTimer) drainTimer = setTimeout(drain, WEBGL_DRAIN_MS)
+ // Armed UNCONDITIONALLY — even on an empty queue — because it is what rate-limits the next
+ // CALLER (see above). The tick clears the handle first (it is itself a drain() call and the
+ // guard above would stop it) and only re-runs when work remains.
+ drainTimer = setTimeout(() => {
+ drainTimer = null
+ if (owed.size) drain()
+ }, WEBGL_DRAIN_MS)
}
/**
@@ -442,7 +455,14 @@ export function registerWebglClient(id: string, callbacks: WebglClientCallbacks)
if (c.visible && c.lossStreak <= WEBGL_LOSS_STREAK_MAX && !c.acquireTimer) {
c.acquireTimer = setTimeout(() => {
c.acquireTimer = null
- tryGrant(c)
+ // QUEUED, not granted inline: a GPU process reset loses every context on the page at
+ // once, so every visible client schedules this retry and they all come due together —
+ // a dozen renderer rebuilds in one frame, which is the swap burst the drain exists to
+ // spread out (and it parks the work while a gesture runs). A lone client is
+ // unaffected: the drain executes an idle queue immediately.
+ c.releaseOwed = false
+ owed.add(c)
+ drain()
}, WEBGL_REACQUIRE_AFTER_LOSS_MS)
}
},