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.

feat(glyphgrid): survive a lost context — restore once, fall back if it happens again

enesdfe071d7f5b2
diff --git a/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md b/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md
index 48a9ca60b..5b2ed2274 100644
--- a/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md
+++ b/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md
@@ -495,12 +495,21 @@ Auto after you switched builds, that is why: re-select Shared and carry on.
## 5. Failure paths
-- [ ] **5.1 Forced context loss.** Force `WEBGL_lose_context` on the shared canvas: exactly ONE
- warning in the console, the rAF loop stops, EVERY terminal returns to readable DOM text, and
- nothing is blank. The mode stays failed for the rest of the session (by design — no retry
- loop), and the Settings row still reads Shared.
-- [ ] **5.2 Recover from a failure.** After 5.1, switch to Auto and back: terminals render normally
- on Auto. (A relaunch is what re-arms shared mode.)
+- [ ] **5.1 Forced context loss — the canvas comes BACK.** Force a loss on the shared canvas
+ (`document.querySelector('.glyphgrid-canvas').getContext('webgl2')
+ .getExtension('WEBGL_lose_context').loseContext()`). Expect: a brief blank canvas, then every
+ terminal repaints on the SHARED renderer with its text intact and its cursor where it was —
+ no reload, no re-registration, and terminals that were streaming keep streaming. The console
+ carries exactly TWO glyphgrid lines, one naming the loss and one naming the restore; the
+ Settings row still reads Shared and the mode is NOT failed. Note anything that comes back
+ wrong rather than blank (soft or garbled glyphs would mean the atlas page did not survive the
+ GPU event, which the restore assumes it does).
+- [ ] **5.2 A second loss inside a minute falls back permanently, as designed.** Immediately after
+ 5.1 (within 60 s — `RESTORE_COOLDOWN_MS`), force the loss again. Expect: NO second restore,
+ one warning naming the repeat loss, and every terminal back on readable DOM text with nothing
+ blank. The session stays failed until relaunch — that floor is deliberate, because handing a
+ failing GPU its context back over and over is how one failure becomes a flicker. Switching to
+ Auto and back still renders normally on Auto.
- [ ] **5.3 No WebGL2.** On a machine/profile without WebGL2 (or with it disabled in flags):
selecting Shared silently leaves every terminal on the DOM renderer — no error dialog, no
blank terminals.
@@ -570,9 +579,6 @@ Auto after you switched builds, that is why: re-select Shared and carry on.
- **L8 — The kanban card modal stays on xterm's DOM renderer, by design in v1.** The modal is a
second, co-attached view of the same tmux session living outside the canvas' coordinate space;
it has no grid, no camera and no z in the shared canvas. Board parity here is a Phase-2 question.
-- **L9 — A failure is permanent for the session.** A GL error or a lost context disables the shared
- renderer until the app is relaunched; there is no restore path in Phase 1b (deliberate — a retry
- loop on a bad driver is how you turn one failure into a flicker).
- **L14 — The atlas cell and the baseline latch to the FIRST terminal's usable measurement.** The
atlas is rasterized into xterm's own `dimensions.device.cell`, handed over by whichever terminal
builds the shared context first, and the baseline is derived from that same font at that moment.
diff --git a/src/renderer/canvas/SharedGlyphLayer.test.ts b/src/renderer/canvas/SharedGlyphLayer.test.ts
index 9d0def382..5e561ec51 100644
--- a/src/renderer/canvas/SharedGlyphLayer.test.ts
+++ b/src/renderer/canvas/SharedGlyphLayer.test.ts
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createFrameLoop, type FrameLoop, type FrameLoopHost } from '../glyphgrid/frame-driver'
import {
createBoardFrameGate,
+ createContextLossPolicy,
createCursorBlinkClock,
cursorBlinkTarget,
setCursorBlinkTarget,
@@ -32,6 +33,7 @@ import {
subscribeOpaqueSet,
syncAtlasPixelRatio,
useSharedGlyph,
+ RESTORE_COOLDOWN_MS,
type AtlasResetSource,
type CursorBlinkClock,
type CursorBlinkTarget,
@@ -1570,3 +1572,155 @@ describe('installAtlasResetLog', () => {
expect(warn).not.toHaveBeenCalled()
})
})
+
+describe('createContextLossPolicy', () => {
+ /**
+ * The whole policy is injected, so the once-only rule, the cooldown and both give-up branches
+ * are exercisable without a GPU, a canvas or a clock — the same split `createBoardFrameGate`
+ * and `createCursorBlinkClock` make.
+ */
+ function harness(): {
+ deps: Parameters<typeof createContextLossPolicy>[0]
+ at(ms: number): void
+ suspends(): number
+ revives(): number
+ failures(): { reason: string; err?: unknown }[]
+ /** Make the next `revive()` throw — a driver that will not rebuild. */
+ breakRevive(): void
+ } {
+ let clock = 0
+ let suspends = 0
+ let revives = 0
+ let broken = false
+ const failures: { reason: string; err?: unknown }[] = []
+ return {
+ deps: {
+ now: () => clock,
+ suspend: () => {
+ suspends++
+ },
+ revive: () => {
+ if (broken) throw new Error('programs would not rebuild')
+ revives++
+ },
+ fail: (reason, err) => {
+ failures.push({ reason, err })
+ }
+ },
+ at: (ms) => {
+ clock = ms
+ },
+ suspends: () => suspends,
+ revives: () => revives,
+ failures: () => failures,
+ breakRevive: () => {
+ broken = true
+ }
+ }
+ }
+
+ let warn: ReturnType<typeof vi.spyOn>
+ beforeEach(() => {
+ warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ })
+ afterEach(() => {
+ warn.mockRestore()
+ })
+
+ it('a first loss suspends and ASKS for a restore', () => {
+ // `preventDefault()` is the request for a `webglcontextrestored` event; Phase 1b never made it
+ // because it had nothing to restore into.
+ const h = harness()
+ const policy = createContextLossPolicy(h.deps)
+ expect(policy.onLost()).toBe(true)
+ expect(h.suspends()).toBe(1)
+ expect(h.failures()).toEqual([])
+ })
+
+ it('the restore rebuilds and says so on the console', () => {
+ // A SILENT restore is indistinguishable from a freeze to whoever is debugging one, which is
+ // why both branches of this policy warn.
+ const h = harness()
+ const policy = createContextLossPolicy(h.deps)
+ policy.onLost()
+ policy.onRestored()
+ expect(h.revives()).toBe(1)
+ expect(h.failures()).toEqual([])
+ expect(warn.mock.calls.map((c: unknown[]) => String(c[0])).join('\n')).toMatch(
+ /context restored/i
+ )
+ })
+
+ it('a SECOND loss inside the cooldown falls back permanently — no retry loop, ever', () => {
+ // The floor under the whole feature, and Phase 1b's behaviour kept as it: a GPU that keeps
+ // taking the context away must not be handed it back over and over, because that turns one
+ // failure into a flicker.
+ const h = harness()
+ const policy = createContextLossPolicy(h.deps)
+ policy.onLost()
+ policy.onRestored()
+ h.at(RESTORE_COOLDOWN_MS - 1)
+ expect(policy.onLost()).toBe(false) // not even asking for a restore this time
+ expect(h.suspends()).toBe(1) // …and no second suspend
+ expect(h.failures()).toHaveLength(1)
+ expect(h.failures()[0].reason).toMatch(/lost again/i)
+ // Terminal: nothing that arrives afterwards may restore anything.
+ policy.onRestored()
+ expect(h.revives()).toBe(1)
+ expect(policy.onLost()).toBe(false)
+ expect(h.failures()).toHaveLength(1)
+ })
+
+ it('a loss AFTER the cooldown is restored again — one restore per context', () => {
+ // The rule is "once per CONTEXT", not "once per session": a machine that sleeps twice in an
+ // afternoon gets its renderer back both times.
+ const h = harness()
+ const policy = createContextLossPolicy(h.deps)
+ policy.onLost()
+ policy.onRestored()
+ h.at(RESTORE_COOLDOWN_MS + 1)
+ expect(policy.onLost()).toBe(true)
+ policy.onRestored()
+ expect(h.revives()).toBe(2)
+ expect(h.failures()).toEqual([])
+ })
+
+ it('a restore that THROWS falls back permanently, carrying the error', () => {
+ // A half-rebuilt context draws nothing, and a canvas of transparent node bodies drawing
+ // nothing looks exactly like a freeze.
+ const h = harness()
+ const policy = createContextLossPolicy(h.deps)
+ policy.onLost()
+ h.breakRevive()
+ policy.onRestored()
+ expect(h.failures()).toHaveLength(1)
+ expect(h.failures()[0].reason).toMatch(/restore threw/i)
+ expect(h.failures()[0].err).toBeInstanceOf(Error)
+ // And it is over: a later restore event cannot re-enter the rebuild.
+ policy.onRestored()
+ expect(h.revives()).toBe(0)
+ })
+
+ it('a restore we never asked for is ignored', () => {
+ // The browser can hand a context back on its own after we have given up. Rebuilding there
+ // would double-create every grid's GPU buffer and leak the first set.
+ const h = harness()
+ const policy = createContextLossPolicy(h.deps)
+ policy.onRestored()
+ expect(h.revives()).toBe(0)
+ expect(h.failures()).toEqual([])
+ })
+
+ it('a duplicate loss for the SAME outage is not a second failure', () => {
+ // Two `webglcontextlost` events before any restore is one outage, not a GPU that failed twice
+ // — suspending again would be harmless but failing the session would not.
+ const h = harness()
+ const policy = createContextLossPolicy(h.deps)
+ policy.onLost()
+ expect(policy.onLost()).toBe(true)
+ expect(h.suspends()).toBe(1)
+ expect(h.failures()).toEqual([])
+ policy.onRestored()
+ expect(h.revives()).toBe(1)
+ })
+})
diff --git a/src/renderer/canvas/SharedGlyphLayer.tsx b/src/renderer/canvas/SharedGlyphLayer.tsx
index a83d04d99..55fba6d7b 100644
--- a/src/renderer/canvas/SharedGlyphLayer.tsx
+++ b/src/renderer/canvas/SharedGlyphLayer.tsx
@@ -11,10 +11,14 @@
* singleton, not component state: it must survive `<SharedGlyphLayer/>` remounting, and it is
* created LAZILY — a user who never turns the experimental mode on must never cost a GPU
* context, which is why `getSharedGlyphContext()` returns null while the mode is off.
- * 2. **The failure path.** `GlyphGridEngine.frame()` RETHROWS on a GL error by contract (it
- * restores its damage first), and a lost context is not recoverable in 1b. Both land on
- * `failSharedGlyph()`: warn once, tear the context down, and flip the store's `failed` — the
- * session-level "everyone back to the DOM renderer" signal that TerminalNode reads.
+ * 2. **The failure path, and the one recovery.** `GlyphGridEngine.frame()` RETHROWS on a GL error
+ * by contract (it restores its damage first), and that lands on `failSharedGlyph()`: warn once,
+ * tear the context down, and flip the store's `failed` — the session-level "everyone back to
+ * the DOM renderer" signal that TerminalNode reads. A LOST CONTEXT is no longer one of those: it
+ * arrives as an event rather than a throw, and it is restored ONCE per context
+ * (`createContextLossPolicy` → `engine.suspendGpu` / `reviveGpu`), because a GPU reset is what
+ * macOS does on sleep/wake and the shared renderer is meant to be the default. A second loss
+ * inside the cooldown, or a rebuild that throws, falls back through the same `failSharedGlyph`.
* 3. **The seams the rest of the integration reads**: `useSharedGlyph` (mode + generation +
* failure), `setNodeZOrder`/`nodeZFor`/`subscribeNodeZOrder` (paint order),
* `setOpaqueNodeIds`/`nodeIsOpaque`/`subscribeOpaqueSet` (which terminals must leave the shared
@@ -101,9 +105,10 @@ interface SharedGlyphState {
* failed. TerminalNode subscribes to exactly this number — the context it then asks for
* answers what to do next (a new engine, or null = back to the DOM renderer). */
generation: number
- /** Session-level "the shared renderer is off for good" — set by the rAF catch or a lost
- * context. Deliberately NOT auto-cleared: a GPU that just threw at us gets one chance per app
- * run, and a retry loop is how you turn a bad driver into a flicker. */
+ /** Session-level "the shared renderer is off for good" — set by the rAF catch, or by a context
+ * loss that the restore policy refused to answer (a second one inside `RESTORE_COOLDOWN_MS`, or
+ * a rebuild that threw). Deliberately NOT auto-cleared: a GPU that just threw at us gets one
+ * chance per app run, and a retry loop is how you turn a bad driver into a flicker. */
failed: boolean
setEnabled(on: boolean): void
bumpGeneration(): void
@@ -1380,6 +1385,117 @@ export function createCursorBlinkClock(deps: CursorBlinkClockDeps): CursorBlinkC
}
}
+// ---------------------------------------------------------------------------------------------
+// Context loss — restore ONCE per context, then fall back for good
+// ---------------------------------------------------------------------------------------------
+
+/**
+ * How soon after a restore a SECOND loss means "this GPU is not coming back".
+ *
+ * A minute, because the two cases it separates are that far apart. A sleep/wake or a driver reset
+ * takes the context away once and the machine then works for hours — that one is worth restoring,
+ * and it is the whole reason this path exists (a GPU reset is what macOS does on wake, and under
+ * Phase 1b it silently dropped every user to the DOM renderer until they relaunched). A GPU that is
+ * genuinely failing takes it away again almost immediately, and restoring THAT in a loop is how one
+ * failure becomes a flicker — the exact trade Phase 1b made by never restoring at all.
+ */
+export const RESTORE_COOLDOWN_MS = 60_000
+
+/** Everything the policy touches, injected — so the once-only rule and the cooldown are testable
+ * without a GPU, a canvas or a clock, exactly as `createBoardFrameGate`'s policy is. */
+export interface ContextLossDeps {
+ now(): number
+ /** Park everything that could draw and drop the engine's GPU objects. */
+ suspend(): void
+ /** Rebuild the GPU objects and resume. MAY THROW — a rebuild that fails is a permanent
+ * fallback, never a retry. */
+ revive(): void
+ /** The permanent fallback (`failSharedGlyph`). */
+ fail(reason: string, err?: unknown): void
+}
+
+export interface ContextLossPolicy {
+ /** Handle `webglcontextlost`. Returns whether the caller should `preventDefault()` the event —
+ * i.e. whether we are asking the browser for a restore at all. */
+ onLost(): boolean
+ /** Handle `webglcontextrestored`. */
+ onRestored(): void
+}
+
+/**
+ * The context-loss policy: **restore ONCE per context, never in a loop.**
+ *
+ * `preventDefault()` on `webglcontextlost` is what asks the browser to fire
+ * `webglcontextrestored`, so it is called only when we intend to use the restore. Phase 1b
+ * deliberately did not call it: there was nothing to restore into, and a session that lost its
+ * context stayed on the DOM renderer until relaunch. That is a fine trade for an experimental mode
+ * and an unacceptable one for the DEFAULT, because a GPU reset — sleep/wake, a driver hiccup —
+ * would silently take every user's shared renderer away with no message.
+ *
+ * Three rules, and the second and third are the floor Phase 1b's behaviour becomes:
+ * 1. A first loss suspends and asks for a restore; the restore rebuilds and resumes.
+ * 2. A second loss WITHIN `RESTORE_COOLDOWN_MS` of that restore falls back permanently. The
+ * restore is not retried, the event is not prevented, and the session goes back to the DOM
+ * renderer through the usual funnel.
+ * 3. A restore that THROWS falls back permanently too — a half-rebuilt context draws nothing, and
+ * a canvas of transparent node bodies drawing nothing is indistinguishable from a freeze.
+ *
+ * Both outcomes are announced on the console, and that is a requirement rather than a courtesy: a
+ * silent restore looks exactly like a frozen canvas to whoever is debugging one, and a silent
+ * fallback looks exactly like a soft-text bug.
+ */
+export function createContextLossPolicy(deps: ContextLossDeps): ContextLossPolicy {
+ /** When the last successful restore landed, or null while this context has never been restored. */
+ let restoredAt: number | null = null
+ /** Have we suspended and asked for a restore that has not arrived yet? */
+ let awaiting = false
+ /** Terminal: the session has fallen back, and no further event may do anything. */
+ let done = false
+ return {
+ onLost(): boolean {
+ if (done) return false
+ // A second `webglcontextlost` for the SAME outage (a duplicate event, a loss racing our own
+ // teardown) is not a second failure — we are already suspended and already waiting.
+ if (awaiting) return true
+ if (restoredAt !== null && deps.now() - restoredAt < RESTORE_COOLDOWN_MS) {
+ done = true
+ deps.fail(
+ `the WebGL context was lost again within ${Math.round(
+ RESTORE_COOLDOWN_MS / 1000
+ )}s of a restore — not restoring a second time`
+ )
+ return false
+ }
+ awaiting = true
+ console.warn(
+ '[glyphgrid] WebGL context lost — GPU objects dropped and frames parked; asking the browser to restore it'
+ )
+ deps.suspend()
+ return true
+ },
+ onRestored(): void {
+ // A restore we did not ask for (the browser handing one back after we have already given up)
+ // must not rebuild anything: the engine would double-create every grid's buffer, and the
+ // session has already been told it is on the DOM renderer.
+ if (done || !awaiting) return
+ awaiting = false
+ try {
+ deps.revive()
+ } catch (err) {
+ done = true
+ deps.fail('rebuilding the GPU objects after a context restore threw', err)
+ return
+ }
+ // Recorded only on SUCCESS — the cooldown measures "how long did the restored context
+ // survive", and a failed rebuild never produced one to measure.
+ restoredAt = deps.now()
+ console.warn(
+ '[glyphgrid] WebGL context restored — GPU objects and every registered grid rebuilt; the canvas repaints in full'
+ )
+ }
+ }
+}
+
// ---------------------------------------------------------------------------------------------
// The component
// ---------------------------------------------------------------------------------------------
@@ -1442,111 +1558,170 @@ export function SharedGlyphLayer(): JSX.Element {
// monitor) leaves the CSS box identical while the backing store must change.
window.addEventListener('resize', pushViewport)
- // The frame loop PARKS when the canvas goes quiet — an always-registered rAF keeps Chromium's
- // whole frame pipeline ticking at the display's refresh rate to draw nothing. All the
- // scheduling and the park/heartbeat policy live in `createFrameLoop` (unit-tested there); this
- // effect only supplies the seams and the wake signals.
- //
- // The gate around it answers the case the park cannot: the kanban board covering the canvas.
- // It owns starting and stopping (including the "mounted while the board is already up" case),
- // which is why there is no `loop.start()` here — see `createBoardFrameGate`.
- const gate = createBoardFrameGate(boardCoversCanvas, () =>
- createFrameLoop({
- // The context can be torn down synchronously between a schedule and its callback (font
- // change, dpr change, mode switched off); the loop stops itself rather than rescheduling,
- // and the cleanup below is idempotent either way.
- alive: () => !ctx.disposed,
- frame: () => ctx.engine.frame(),
- // `frame()` rethrows by contract, having restored its own damage. There is no recovery in
- // 1b: the whole session goes back to the DOM renderer.
- onError: (err) => failSharedGlyph('frame threw', err),
- requestFrame: (cb) => requestAnimationFrame(cb),
- cancelFrame: (h) => cancelAnimationFrame(h),
- setTimer: (cb, ms) => window.setTimeout(cb, ms),
- clearTimer: (h) => window.clearTimeout(h)
+ /**
+ * EVERYTHING THAT CAN DRAW OR SCHEDULE, as one startable/stoppable unit.
+ *
+ * It is a unit because a lost context has to take ALL of it down at once and a restore has to
+ * bring exactly it back: the rAF chain, the heartbeat timer, the blink clock's interval, the
+ * damage subscription and the four store/window subscriptions that can wake or rebuild any of
+ * them. A single survivor is a frame submitted against GPU objects that no longer exist — which
+ * the driver's catch reads as a GPU failure and answers by burning the session that is in the
+ * middle of recovering. And a single thing started twice is two rAF chains on one canvas.
+ *
+ * The mount path and the restore path therefore run the same function, and the cleanup below
+ * and the suspend path run the same `stop()`.
+ */
+ const startRuntime = (): { stop(): void } => {
+ // The frame loop PARKS when the canvas goes quiet — an always-registered rAF keeps Chromium's
+ // whole frame pipeline ticking at the display's refresh rate to draw nothing. All the
+ // scheduling and the park/heartbeat policy live in `createFrameLoop` (unit-tested there); this
+ // only supplies the seams and the wake signals.
+ //
+ // The gate around it answers the case the park cannot: the kanban board covering the canvas.
+ // It owns starting and stopping (including the "mounted while the board is already up" case),
+ // which is why there is no `loop.start()` here — see `createBoardFrameGate`.
+ const gate = createBoardFrameGate(boardCoversCanvas, () =>
+ createFrameLoop({
+ // The context can be torn down synchronously between a schedule and its callback (font
+ // change, dpr change, mode switched off); the loop stops itself rather than rescheduling,
+ // and the cleanup below is idempotent either way.
+ alive: () => !ctx.disposed,
+ frame: () => ctx.engine.frame(),
+ // `frame()` rethrows by contract, having restored its own damage. A throw is a GL error
+ // rather than a lost context (that arrives as an EVENT, handled below), and there is no
+ // recovery from it: the whole session goes back to the DOM renderer.
+ onError: (err) => failSharedGlyph('frame threw', err),
+ requestFrame: (cb) => requestAnimationFrame(cb),
+ cancelFrame: (h) => cancelAnimationFrame(h),
+ setTimer: (cb, ms) => window.setTimeout(cb, ms),
+ clearTimer: (h) => window.clearTimeout(h)
+ })
+ )
+ // ONE blink clock for the whole canvas — not one per terminal — because at most one terminal
+ // has focus. It reaches the loop through `gate.loop()` for the same reason the damage
+ // subscription does, and its own repaints take `pulse()` rather than `wake()`; see
+ // `createCursorBlinkClock` for why that distinction is the whole task.
+ const clock = createCursorBlinkClock({
+ enabled: () => useSettings.getState().settings.cursorBlink,
+ covered: boardCoversCanvas,
+ target: cursorBlinkTarget,
+ loop: () => gate.loop(),
+ setInterval: (cb, ms) => window.setInterval(cb, ms),
+ clearInterval: (h) => window.clearInterval(h)
})
- )
- // ONE blink clock for the whole canvas — not one per terminal — because at most one terminal
- // has focus. It reaches the loop through `gate.loop()` for the same reason the damage
- // subscription does, and its own repaints take `pulse()` rather than `wake()`; see
- // `createCursorBlinkClock` for why that distinction is the whole task.
- const clock = createCursorBlinkClock({
- enabled: () => useSettings.getState().settings.cursorBlink,
- covered: boardCoversCanvas,
- target: cursorBlinkTarget,
- loop: () => gate.loop(),
- setInterval: (cb, ms) => window.setInterval(cb, ms),
- clearInterval: (h) => window.clearInterval(h)
- })
- // Mounted with a terminal already focused (a remount, a project switch back) must start the
- // clock, exactly as the gate reads the board flag at construction rather than assuming.
- clock.sync()
- // THE wake mechanism: the engine funnels every damage write through `markDirty`, which calls
- // out on the clean→dirty edge. A parked loop resumes on the very next damaging write. Reached
- // through `gate.loop()` and never captured — leaving the board builds a fresh loop, and a
- // subscription pinned to the stopped one would freeze the canvas for the rest of the session.
- //
- // Routed through the clock, which is the only thing that can tell the blink's own repaint from
- // everybody else's damage: its repaint is isolated in time and takes `pulse()` (one frame, still
- // parked), while ordinary damage keeps the `wake()` it has always had.
- const damage = ctx.engine.onDamage(() => clock.routeDamage())
- // The two gates that can move without the board moving: the blink SETTING and which terminal
- // holds focus. Both are change-gated inside `sync`.
- const unsubBlinkTarget = subscribeCursorBlinkTarget(() => clock.sync())
- const unsubBlinkSetting = useSettings.subscribe(() => clock.sync())
- // Belt and braces for the background-throttling case (Task 9): a park entered while the window
- // was occluded must not outlive the return, and a throttled/coalesced rAF can leave the loop
- // parked with damage pending. Both are cheap — `wake()` only schedules a frame that draws
- // nothing when there is nothing to draw, and it is inert while the board is up.
- const onVisible = (): void => {
- if (!document.hidden) gate.loop().wake()
- }
- const onFocus = (): void => gate.loop().wake()
- window.addEventListener('focus', onFocus)
- document.addEventListener('visibilitychange', onVisible)
- // Both stores, because either can move the board over this canvas: the view toggle, and a
- // switch to a project that is already on it. `sync` is change-gated, so the projects store's
- // chattier notifications (it is rewritten on every node serialization) cost a comparison.
- // The board is the blink clock's third gate as well (a stopped loop cannot draw the phase), so
- // the two are synced together — and the gate goes FIRST, so the clock reads the board through
- // an already-updated loop.
- const syncBoard = (): void => {
- gate.sync()
+ // Mounted with a terminal already focused (a remount, a project switch back, a restore that
+ // never took focus away) must start the clock, exactly as the gate reads the board flag at
+ // construction rather than assuming.
clock.sync()
+ // THE wake mechanism: the engine funnels every damage write through `markDirty`, which calls
+ // out on the clean→dirty edge. A parked loop resumes on the very next damaging write. Reached
+ // through `gate.loop()` and never captured — leaving the board builds a fresh loop, and a
+ // subscription pinned to the stopped one would freeze the canvas for the rest of the session.
+ //
+ // Routed through the clock, which is the only thing that can tell the blink's own repaint from
+ // everybody else's damage: its repaint is isolated in time and takes `pulse()` (one frame, still
+ // parked), while ordinary damage keeps the `wake()` it has always had.
+ const damage = ctx.engine.onDamage(() => clock.routeDamage())
+ // The two gates that can move without the board moving: the blink SETTING and which terminal
+ // holds focus. Both are change-gated inside `sync`.
+ const unsubBlinkTarget = subscribeCursorBlinkTarget(() => clock.sync())
+ const unsubBlinkSetting = useSettings.subscribe(() => clock.sync())
+ // Belt and braces for the background-throttling case (Task 9): a park entered while the window
+ // was occluded must not outlive the return, and a throttled/coalesced rAF can leave the loop
+ // parked with damage pending. Both are cheap — `wake()` only schedules a frame that draws
+ // nothing when there is nothing to draw, and it is inert while the board is up.
+ const onVisible = (): void => {
+ if (!document.hidden) gate.loop().wake()
+ }
+ const onFocus = (): void => gate.loop().wake()
+ window.addEventListener('focus', onFocus)
+ document.addEventListener('visibilitychange', onVisible)
+ // Both stores, because either can move the board over this canvas: the view toggle, and a
+ // switch to a project that is already on it. `sync` is change-gated, so the projects store's
+ // chattier notifications (it is rewritten on every node serialization) cost a comparison.
+ // The board is the blink clock's third gate as well (a stopped loop cannot draw the phase), so
+ // the two are synced together — and the gate goes FIRST, so the clock reads the board through
+ // an already-updated loop.
+ const syncBoard = (): void => {
+ gate.sync()
+ clock.sync()
+ }
+ const unsubView = useViewMode.subscribe(syncBoard)
+ const unsubProjects = useProjects.subscribe(syncBoard)
+ let stopped = false
+ return {
+ stop(): void {
+ // Idempotent: the suspend path and the effect cleanup can both reach the same runtime
+ // (a lost context that is immediately followed by an unmount), and every member below
+ // would be stopped twice otherwise.
+ if (stopped) return
+ stopped = true
+ // Everything the loop owns goes at once — the pending frame, the heartbeat TIMER and the
+ // damage subscription — plus the two store subscriptions that can hand it a new one. A
+ // surviving timer would keep calling `frame()` on a context this run has let go of, a
+ // surviving damage subscription would keep a dead loop reachable from the engine, and a
+ // surviving board subscription would BUILD a loop against a disposed context.
+ // `gate.stop()` is idempotent and also makes a `sync` still in flight inert, so the
+ // `ctx.disposed` and `failSharedGlyph` paths (which stop the loop themselves) land here
+ // safely too.
+ // The clock goes FIRST, and before `gate.stop()`: it hands the cursor back SHOWN, and
+ // that restoring repaint still wants a live loop to draw it.
+ clock.stop()
+ unsubBlinkTarget()
+ unsubBlinkSetting()
+ gate.stop()
+ unsubView()
+ unsubProjects()
+ damage.dispose()
+ window.removeEventListener('focus', onFocus)
+ document.removeEventListener('visibilitychange', onVisible)
+ }
+ }
}
- const unsubView = useViewMode.subscribe(syncBoard)
- const unsubProjects = useProjects.subscribe(syncBoard)
-
- // Phase 2 owns real context restoration; here a lost context is simply the end of the shared
- // renderer for this session. `preventDefault()` is deliberately NOT called — that is the
- // "please fire webglcontextrestored" request, and we have nothing to restore into.
- const onLost = (): void => failSharedGlyph('context lost')
+ let runtime = startRuntime()
+
+ /**
+ * A lost context is now SURVIVABLE — see `createContextLossPolicy` for the once-only rule and
+ * the cooldown that keeps it from becoming a retry loop.
+ *
+ * The two halves are ordered against each other on purpose. On the way DOWN the runtime stops
+ * before the engine drops its GPU objects, so no frame can be submitted in between; on the way
+ * UP the GPU objects are rebuilt before a fresh runtime exists to schedule anything, so the
+ * first frame of the new context has something to draw with. `reviveGpu` throws if the rebuild
+ * fails, and the policy answers that with the permanent fallback — the runtime stays stopped,
+ * which is the correct state for a session that is going back to the DOM renderer.
+ */
+ const policy = createContextLossPolicy({
+ now: () => Date.now(),
+ suspend: () => {
+ runtime.stop()
+ ctx.engine.suspendGpu()
+ },
+ revive: () => {
+ ctx.engine.reviveGpu()
+ runtime = startRuntime()
+ },
+ fail: (reason, err) => failSharedGlyph(reason, err)
+ })
+ // `preventDefault()` is the request for a `webglcontextrestored` event, so it is called only
+ // when the policy actually intends to use one. Phase 1b never called it at all.
+ const onLost = (e: Event): void => {
+ if (policy.onLost()) e.preventDefault()
+ }
+ const onRestored = (): void => policy.onRestored()
canvas.addEventListener('webglcontextlost', onLost)
+ canvas.addEventListener('webglcontextrestored', onRestored)
return () => {
- // Everything the loop owns goes at once — the pending frame, the heartbeat TIMER and the
- // damage subscription — plus the two store subscriptions that can hand it a new one. A
- // surviving timer would keep calling `frame()` on a context this effect run has let go of, a
- // surviving damage subscription would keep a dead loop reachable from the engine, and a
- // surviving board subscription would BUILD a loop against a disposed context. `gate.stop()`
- // is idempotent and also makes a `sync` still in flight inert, so the `ctx.disposed` and
- // `failSharedGlyph` paths (which stop the loop themselves) land here safely too.
- // The clock goes FIRST, and before `gate.stop()`: it hands the cursor back SHOWN, and that
- // restoring repaint still wants a live loop to draw it. Nothing may outlive the context —
- // this is also the teardown for the `ctx.disposed` and `failSharedGlyph` paths, both of which
- // re-run this effect.
- clock.stop()
- unsubBlinkTarget()
- unsubBlinkSetting()
- gate.stop()
- unsubView()
- unsubProjects()
- damage.dispose()
- window.removeEventListener('focus', onFocus)
- document.removeEventListener('visibilitychange', onVisible)
+ // Nothing may outlive the context — this is also the teardown for the `ctx.disposed` and
+ // `failSharedGlyph` paths, both of which re-run this effect. `runtime` is read (not captured)
+ // so a cleanup after a restore stops the CURRENT runtime rather than the one this effect run
+ // started with.
+ runtime.stop()
ro.disconnect()
window.removeEventListener('resize', pushViewport)
canvas.removeEventListener('webglcontextlost', onLost)
+ canvas.removeEventListener('webglcontextrestored', onRestored)
// The canvas leaves the DOM with the host div; the CONTEXT stays alive for the next mount
// (a project switch must not cost a context rebuild). Only `failSharedGlyph` and a font
// change dispose it.
diff --git a/src/renderer/glyphgrid/engine.test.ts b/src/renderer/glyphgrid/engine.test.ts
index 7e5df9050..d1e47ade3 100644
--- a/src/renderer/glyphgrid/engine.test.ts
+++ b/src/renderer/glyphgrid/engine.test.ts
@@ -9,27 +9,40 @@ type Created = [string, number, number]
/** [id, firstRow, rowCount] as passed to uploadRows — the row-range damage assertion. */
type Upload = [string, number, number]
-function fakeGL(): GlyphGL & {
+type FakeGL = GlyphGL & {
drawn: string[]
created: Created[]
disposed: string[]
uploads: Upload[]
uploaded: Uint32Array[]
params: GridDrawParams[]
-} {
+ /** How many times the context rebuilt its GPU objects (`restore`). */
+ restores: number
+ /** Make the next `restore()` throw — a driver that will not rebuild, which the caller must
+ * answer with a permanent fallback rather than with a retry. */
+ failRestore: boolean
+}
+
+function fakeGL(): FakeGL {
const drawn: string[] = []
const created: Created[] = []
const disposed: string[] = []
const uploads: Upload[] = []
const uploaded: Uint32Array[] = []
const params: GridDrawParams[] = []
- return {
+ const self: FakeGL = {
drawn,
created,
disposed,
uploads,
uploaded,
params,
+ restores: 0,
+ failRestore: false,
+ restore: (): void => {
+ if (self.failRestore) throw new Error('rebuild failed')
+ self.restores++
+ },
resize: vi.fn(),
// Recorded in `drawn` too: the atlas upload MUST land before beginFrame (which pushes the
// atlas uniforms), let alone before any drawGrid of the same frame — otherwise the shader
@@ -61,6 +74,7 @@ function fakeGL(): GlyphGL & {
endFrame: () => drawn.push('END'),
dispose: vi.fn()
}
+ return self
}
const atlas = () =>
@@ -882,3 +896,149 @@ describe('cursor params', () => {
expect(e.frame()).toBe(false)
})
})
+
+/**
+ * SUSPEND / REVIVE — surviving a lost GPU context.
+ *
+ * The whole design rests on one distinction: a lost context takes the GPU OBJECTS, never the
+ * REGISTRY. Each grid's spec, its CPU-side cells and its z survive, so the handles the terminal
+ * nodes hold stay valid across the entire cycle and nobody has to re-register. That is what makes
+ * a restore a repaint rather than a rebuild of the whole integration.
+ */
+describe('suspendGpu / reviveGpu', () => {
+ it('keeps its registry across a suspend/revive and repaints everything after', () => {
+ const gl = fakeGL()
+ const e = new GlyphGridEngine(gl, atlas())
+ e.setViewport(800, 600, 1)
+ e.setCamera({ x: 0, y: 0, zoom: 1 })
+ const h = e.register(spec('a', 0))
+ expect(e.frame()).toBe(true) // registration damage
+ expect(e.frame()).toBe(false) // settled
+
+ e.suspendGpu()
+ expect(gl.disposed).toContain('a')
+
+ e.reviveGpu()
+ // Created once at register, once at revive — the SAME id, i.e. the registry entry survived.
+ expect(gl.created.map((c) => c[0])).toEqual(['a', 'a'])
+ expect(gl.restores).toBe(1)
+ // Everything is dirty again: the fresh buffers are zeroed, so the first frame owes the GPU
+ // every row of every grid.
+ expect(e.frame()).toBe(true)
+ expect(gl.uploads.at(-1)).toEqual(['a', 0, 1])
+
+ // The handle the node holds is still the live one — a write through it still reaches the
+ // canvas, with no re-registration anywhere.
+ h.updateRow(0, rowOf(2))
+ expect(e.frame()).toBe(true)
+ })
+
+ it('submits NO frame while suspended, however much damage arrives', () => {
+ // The constraint the whole cycle stands on: between the loss and the restore there are no GPU
+ // objects, so a frame would draw against deleted buffers — and the driver's catch would read
+ // the throw as a GPU failure and burn the session that is in the middle of recovering.
+ const gl = fakeGL()
+ const e = new GlyphGridEngine(gl, atlas())
+ e.setViewport(800, 600, 1)
+ e.setCamera({ x: 0, y: 0, zoom: 1 })
+ const h = e.register(spec('a', 0))
+ e.frame()
+ e.suspendGpu()
+ const before = gl.drawn.length
+ h.updateRow(0, rowOf(2))
+ expect(e.frame()).toBe(false)
+ expect(gl.drawn.length).toBe(before)
+ })
+
+ it('does not wake the canvas on suspend — the loop is being parked, not started', () => {
+ // `markDirty` is the wake signal, and waking here would schedule a frame against the context
+ // that has just gone away.
+ const e = new GlyphGridEngine(fakeGL(), atlas())
+ e.setViewport(800, 600, 1)
+ e.setCamera({ x: 0, y: 0, zoom: 1 })
+ e.register(spec('a', 0))
+ e.frame()
+ const woke = vi.fn()
+ e.onDamage(woke)
+ e.suspendGpu()
+ expect(woke).not.toHaveBeenCalled()
+ })
+
+ it('replays the rows written while suspended — deferred, never lost', () => {
+ // The addons keep packing rows through the whole outage (nothing tells them the GPU went
+ // away), and those writes land in the CPU-side cells like any other. The revive owes the GPU
+ // all of them.
+ const gl = fakeGL()
+ const e = new GlyphGridEngine(gl, atlas())
+ e.setViewport(800, 600, 1)
+ e.setCamera({ x: 0, y: 0, zoom: 1 })
+ const h = e.register(spec('a', 0, 0, { rows: 2, plateH: 40 }))
+ e.frame()
+ e.suspendGpu()
+ const row = rowOf(2)
+ row[0] = 7
+ h.updateRow(1, row)
+ e.reviveGpu()
+ e.frame()
+ expect(gl.uploads.at(-1)).toEqual(['a', 0, 2])
+ expect(gl.uploaded.at(-1)?.at(CELL_STRIDE * 2)).toBe(7)
+ })
+
+ it('re-uploads the atlas after a revive — the texture died with the context', () => {
+ const gl = fakeGL()
+ const { atlas: loaded } = loadedAtlas()
+ const e = new GlyphGridEngine(gl, loaded)
+ e.setViewport(800, 600, 1)
+ e.setCamera({ x: 0, y: 0, zoom: 1 })
+ e.register(spec('a', 0))
+ e.frame()
+ expect(gl.drawn.filter((d) => d === 'ATLAS')).toHaveLength(1)
+ e.suspendGpu()
+ e.reviveGpu()
+ e.frame()
+ expect(gl.drawn.filter((d) => d === 'ATLAS')).toHaveLength(2)
+ })
+
+ it('a revive without a suspend changes nothing — a stray restore must not double-create', () => {
+ // `webglcontextrestored` can arrive for a context we never suspended (a browser that restores
+ // on its own after we have already given up). Rebuilding there would allocate a second buffer
+ // per grid and leak the first.
+ const gl = fakeGL()
+ const e = new GlyphGridEngine(gl, atlas())
+ e.setViewport(800, 600, 1)
+ e.setCamera({ x: 0, y: 0, zoom: 1 })
+ e.register(spec('a', 0))
+ e.frame()
+ e.reviveGpu()
+ expect(gl.created).toHaveLength(1)
+ expect(gl.restores).toBe(0)
+ })
+
+ it('a throwing restore leaves the engine suspended, so nothing draws against a dead context', () => {
+ // The caller answers a throw with the permanent fallback; the engine's job is only to stay
+ // safe if it does not — never to retry the rebuild itself.
+ const gl = fakeGL()
+ const e = new GlyphGridEngine(gl, atlas())
+ e.setViewport(800, 600, 1)
+ e.setCamera({ x: 0, y: 0, zoom: 1 })
+ e.register(spec('a', 0))
+ e.frame()
+ e.suspendGpu()
+ gl.failRestore = true
+ expect(() => e.reviveGpu()).toThrow()
+ // No grid was re-created, and the frame gate is still shut.
+ expect(gl.created).toHaveLength(1)
+ expect(e.frame()).toBe(false)
+ })
+
+ it('a second suspend is a no-op — the buffers are already gone', () => {
+ const gl = fakeGL()
+ const e = new GlyphGridEngine(gl, atlas())
+ e.setViewport(800, 600, 1)
+ e.setCamera({ x: 0, y: 0, zoom: 1 })
+ e.register(spec('a', 0))
+ e.suspendGpu()
+ e.suspendGpu()
+ expect(gl.disposed).toEqual(['a'])
+ })
+})
diff --git a/src/renderer/glyphgrid/engine.ts b/src/renderer/glyphgrid/engine.ts
index 32e7ecf66..c53aeb294 100644
--- a/src/renderer/glyphgrid/engine.ts
+++ b/src/renderer/glyphgrid/engine.ts
@@ -183,6 +183,9 @@ export class GlyphGridEngine {
private seq = 0
/** False until an atlas source has actually reached the GPU — see `atlasUploadPending`. */
private atlasUploaded = false
+ /** True between `suspendGpu` and `reviveGpu` — i.e. while the GL context has been lost and the
+ * GPU objects do not exist. The frame gate reads it; nothing else does. */
+ private gpuSuspended = false
constructor(
private gl: GlyphGL,
@@ -384,6 +387,72 @@ export class GlyphGridEngine {
this.markDirty()
}
+ /**
+ * Drop every GPU object but KEEP the registry: each grid's spec, its CPU-side cells and its z
+ * survive, so the same handles are valid after `reviveGpu` and no owner has to re-register.
+ * Nothing else may assume a grid's GPU buffer exists — the frame gate below is what enforces
+ * that, since a draw is the only thing that would touch one.
+ *
+ * This is the `webglcontextlost` half of the restore cycle, and it is the OPPOSITE of
+ * `disposeAll`: that one ends the grids (every handle goes inert, the registry empties), this one
+ * ends only the buffers. A lost context that ran `disposeAll` would leave every terminal on the
+ * canvas holding a dead handle, which is the Phase-1b behaviour this task exists to remove.
+ *
+ * **It deliberately does NOT `markDirty`.** Damage is the WAKE signal (see `markDirty`), and
+ * waking here would schedule a frame against the context that has just gone away. The revive
+ * dirties instead, which is the moment there is something to draw with again.
+ */
+ suspendGpu(): void {
+ if (this.gpuSuspended) return
+ this.gpuSuspended = true
+ // The buffers are already gone from the driver's side on a real loss, so these are no-ops
+ // there; they are what keeps the GL layer's own grid table honest, and they free properly if
+ // this is ever called against a live context.
+ for (const g of this.grids.values()) this.gl.disposeGrid(g.id)
+ }
+
+ /**
+ * Re-create the GPU objects for every registered grid and mark everything dirty — the
+ * `webglcontextrestored` half.
+ *
+ * ORDER: the GL layer rebuilds ITS objects first (programs, atlas texture — `restore`), because
+ * the per-grid buffers created below are allocated against them. If that throws, nothing here has
+ * changed and the engine stays suspended: the caller's answer is a permanent fallback, and this
+ * must never retry a rebuild on its own.
+ *
+ * NO REPACK IS NEEDED, which is the point of keeping the registry. The CPU side survived a GPU
+ * event untouched: each grid's `cells` still holds every lane the terminal ever wrote, and the
+ * atlas page still holds the rasterized glyphs those lanes name. So marking every row dirty and
+ * re-uploading the atlas reproduces the exact screen that was on the canvas, without asking a
+ * single addon for anything.
+ *
+ * A revive with no suspend is a NO-OP: `webglcontextrestored` can arrive for a context we never
+ * suspended (a browser restoring one we have already given up on), and rebuilding there would
+ * allocate a second buffer per grid and leak the first.
+ */
+ reviveGpu(): void {
+ if (!this.gpuSuspended) return
+ this.gl.restore()
+ for (const g of this.grids.values()) {
+ this.gl.createGrid(g.id, g.cols, g.rows)
+ // A fresh buffer is ZEROED, so every grid owes the GPU all of its rows — exactly the state
+ // `register` starts a brand-new grid in.
+ g.dirtyFrom = 0
+ g.dirtyTo = g.rows - 1
+ // Conservative, for the same reason `register` starts it true: no draw order has been
+ // computed against the new context yet, and guessing "hidden" would drop the damage of a
+ // grid nobody has culled.
+ g.lastVisible = true
+ }
+ // The texture died with the context. The atlas SOURCE (an OffscreenCanvas) did not, so this is
+ // one upload, not a re-rasterization.
+ this.atlasUploaded = false
+ // Cleared BEFORE the dirty: `markDirty` notifies the wake subscribers, and they must find an
+ // engine that can actually draw the frame they are about to schedule.
+ this.gpuSuspended = false
+ this.markDirty()
+ }
+
setCamera(cam: Camera): void {
if (cam.x === this.camera.x && cam.y === this.camera.y && cam.zoom === this.camera.zoom) return
this.camera = { ...cam }
@@ -468,6 +537,13 @@ export class GlyphGridEngine {
* re-upload rows that did.
*/
frame(): boolean {
+ // THE FRAME GATE OF THE RESTORE CYCLE. Between a `suspendGpu` and its `reviveGpu` there are no
+ // GPU objects, so a submission would throw against deleted buffers — and the driver's catch
+ // reads a throw as a GPU failure and burns the session that is in the middle of recovering.
+ // The layer parks its loop on the loss as well; this is the floor under that, for the frame
+ // already scheduled when the context went away. Damage accumulated meanwhile is not lost — the
+ // dirty flag and the per-grid ranges are untouched, and the revive re-dirties everything.
+ if (this.gpuSuspended) return false
const uploadAtlas = this.atlasUploadPending()
if (!this.dirty && !uploadAtlas) return false
this.dirty = false
diff --git a/src/renderer/glyphgrid/gl-webgl2.ts b/src/renderer/glyphgrid/gl-webgl2.ts
index 2cddff9ea..a2aff0cf9 100644
--- a/src/renderer/glyphgrid/gl-webgl2.ts
+++ b/src/renderer/glyphgrid/gl-webgl2.ts
@@ -236,13 +236,28 @@ void main() {
export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {
const gl = canvas.getContext('webgl2', { alpha: true, antialias: false, depth: false })
if (!gl) return null
- const program = buildProgram(gl, VERT, FRAG)
- if (!program) return null
+ /**
+ * EVERY GPU OBJECT BELOW IS `let`, NOT `const`, BECAUSE A LOST CONTEXT TAKES ALL OF THEM.
+ *
+ * `webglcontextrestored` hands back the SAME `WebGL2RenderingContext` object with every program,
+ * texture, buffer and uniform location it held deleted — so the whole set is rebuilt by
+ * `restore()` (see `buildGpuObjects`) and re-assigned here. The closures below read these
+ * bindings on every call rather than capturing a value, which is what makes a rebuild invisible
+ * to them.
+ */
+ let program: WebGLProgram | null = null
+ let cursorProgram: WebGLProgram | null = null
+ let plateProgram: WebGLProgram | null = null
+ let atlasTex: WebGLTexture | null = null
+ let aCellLoc = 0
// Locations are stable for the life of a linked program, and getUniformLocation /
// getAttribLocation are synchronous driver queries — memoize so the per-frame, per-grid call
- // sites below stay a plain map lookup instead of a GL round trip.
+ // sites below stay a plain map lookup instead of a GL round trip. CLEARED on a rebuild: a
+ // location belongs to the program it was queried from, and a stale one addresses nothing on the
+ // program that replaced it.
const uniforms = new Map<string, WebGLUniformLocation | null>()
const u = (name: string): WebGLUniformLocation | null => {
+ if (!program) return null
let loc = uniforms.get(name)
if (loc === undefined) {
loc = gl.getUniformLocation(program, name)
@@ -250,10 +265,6 @@ export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {
}
return loc
}
- const aCellLoc = gl.getAttribLocation(program, 'aCell')
- /** The overlay program, and null when it failed to build. Null is a DEGRADE, not a failure: the
- * cells still draw, and the terminal loses only a non-block cursor — never its text. */
- const cursorProgram = buildProgram(gl, CURSOR_VERT, CURSOR_FRAG)
const cursorUniforms = new Map<string, WebGLUniformLocation | null>()
const cu = (name: string): WebGLUniformLocation | null => {
if (!cursorProgram) return null
@@ -265,14 +276,8 @@ export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {
return loc
}
/** Scratch for the overlay's rect uniforms — one allocation for the life of the context rather
- * than one per cursor per frame. */
+ * than one per cursor per frame. Pure CPU memory, so a context loss does not touch it. */
const cursorRectData = new Float32Array(MAX_CURSOR_RECTS * 4)
- /** The plate program, and null when it failed to build. Null is NOT the cursor's kind of
- * degrade: without a plate a terminal has no opaque ground at all, and the node body is
- * transparent in shared mode — the canvas dot grid would show straight through every terminal,
- * and overlapping terminals would stop occluding each other. So the null path falls back to the
- * scissored `clear` this program replaced (square corners, i.e. L4) rather than to nothing. */
- const plateProgram = buildProgram(gl, PLATE_VERT, PLATE_FRAG)
const plateUniforms = new Map<string, WebGLUniformLocation | null>()
const pu = (name: string): WebGLUniformLocation | null => {
if (!plateProgram) return null
@@ -286,7 +291,6 @@ export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {
/** One GPU buffer PER GRID, so a change costs only the rows that changed (bufferSubData)
* instead of re-uploading every visible grid's whole cell array into one shared buffer. */
const grids = new Map<string, { buf: WebGLBuffer; cols: number; rows: number }>()
- const atlasTex = gl.createTexture()
let atlasCols = 1
let atlasCellUv: [number, number] = [0, 0]
let atlasStrideUv: [number, number] = [0, 0]
@@ -364,8 +368,6 @@ export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {
}
}
- gl.useProgram(program)
- gl.enable(gl.BLEND)
/**
* Straight (non-premultiplied) source colours over a PREMULTIPLIED drawing buffer — which is
* what `getContext('webgl2', {alpha: true})` gives, since `premultipliedAlpha` defaults to true
@@ -394,7 +396,56 @@ export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {
* fully opaque there, and only the colour half of that residual is left (see `raster.ts` — the
* non-premultiplied UPLOAD is what still double-attenuates the rim's brightness).
*/
- gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
+ const applyBlend = (): void => {
+ gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
+ }
+
+ /**
+ * Build (or REBUILD) every GPU object and every piece of context-wide GL state this layer owns.
+ *
+ * Called once at construction and again by `restore()` after a context loss. Returns false when
+ * the CELL program will not build — the one object with no degrade, since without it a terminal
+ * has no text at all. The two other programs may each come back null and are handled where they
+ * are used (see `cursorProgram` / `plateProgram` below).
+ *
+ * Everything reset here is state a context loss takes with it. The filter cache is the trap: it
+ * records what was last pushed to the TEXTURE, and the texture is new — leaving it would make
+ * `applyAtlasMinFilter` skip its first call and hand the sampler a mip-filtered texture with no
+ * mip chain, which samples black. The viewport is the other one: `engine.setViewport` is
+ * change-gated, so nothing re-pushes the size after a restore and the default viewport of a fresh
+ * drawing buffer would be whatever the canvas element happens to be.
+ */
+ const buildGpuObjects = (): boolean => {
+ program = buildProgram(gl, VERT, FRAG)
+ uniforms.clear()
+ cursorUniforms.clear()
+ plateUniforms.clear()
+ if (!program) return false
+ aCellLoc = gl.getAttribLocation(program, 'aCell')
+ /** The overlay program, and null when it failed to build. Null is a DEGRADE, not a failure: the
+ * cells still draw, and the terminal loses only a non-block cursor — never its text. */
+ cursorProgram = buildProgram(gl, CURSOR_VERT, CURSOR_FRAG)
+ /** The plate program, and null when it failed to build. Null is NOT the cursor's kind of
+ * degrade: without a plate a terminal has no opaque ground at all, and the node body is
+ * transparent in shared mode — the canvas dot grid would show straight through every terminal,
+ * and overlapping terminals would stop occluding each other. So the null path falls back to the
+ * scissored `clear` this program replaced (square corners, i.e. L4) rather than to nothing. */
+ plateProgram = buildProgram(gl, PLATE_VERT, PLATE_FRAG)
+ atlasTex = gl.createTexture()
+ // "Never set" — see `atlasMinFilter`. The fresh texture carries GL's defaults, whatever the
+ // old one was left holding.
+ atlasMinFilter = 0
+ atlasMagFilter = 0
+ gl.useProgram(program)
+ gl.viewport(0, 0, deviceW, deviceH)
+ gl.enable(gl.BLEND)
+ applyBlend()
+ return true
+ }
+
+ // The first build. A failure here is the same "no shared renderer on this machine" answer as a
+ // missing WebGL2 context, and the caller stays on the DOM renderer.
+ if (!buildGpuObjects()) return null
/**
* The occlusion plate: an opaque quad over the grid's PLATE rect — the node body's full world
@@ -686,11 +737,26 @@ export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {
endFrame() {
/* single-pass for now; flush point reserved for Phase 1 layering */
},
+ restore() {
+ // NOTHING IS DELETED FIRST, and that is not an oversight: the context that owned these
+ // objects took them with it, so `deleteProgram`/`deleteBuffer` here would be calls against
+ // names that no longer exist. The grid TABLE is emptied instead, because it is CPU-side
+ // bookkeeping that outlived the buffers it points at — leaving it would make the engine's
+ // very next `createGrid` (which frees a live buffer before reallocating, the resize path)
+ // try to delete one of those dead names.
+ grids.clear()
+ if (!buildGpuObjects())
+ // Throwing rather than returning a flag: the interface says so, and the caller's only
+ // correct answer is the permanent fallback. A context whose cell program will not compile
+ // draws nothing, which on a canvas of transparent node bodies is indistinguishable from a
+ // freeze.
+ throw new Error('glyphgrid: the GL programs would not rebuild after a context restore')
+ },
dispose() {
for (const grid of grids.values()) gl.deleteBuffer(grid.buf)
grids.clear()
gl.deleteTexture(atlasTex)
- gl.deleteProgram(program)
+ if (program) gl.deleteProgram(program)
if (cursorProgram) gl.deleteProgram(cursorProgram)
if (plateProgram) gl.deleteProgram(plateProgram)
}
diff --git a/src/renderer/glyphgrid/gl.ts b/src/renderer/glyphgrid/gl.ts
index 059528b51..5d0c31489 100644
--- a/src/renderer/glyphgrid/gl.ts
+++ b/src/renderer/glyphgrid/gl.ts
@@ -116,5 +116,22 @@ export interface GlyphGL {
* algorithm), so a grid drawn later covers all three. */
drawGrid(g: GridDrawParams): void
endFrame(): void
+ /**
+ * Rebuild every GPU object this layer owns, after the drawing context was LOST and the browser
+ * gave it back (`webglcontextrestored`). Programs, the atlas texture and every piece of cached
+ * GL state die with a context; the objects that replace them are new, so nothing may be reused
+ * across the boundary — locations, filter caches and the current program included.
+ *
+ * It does NOT recreate the per-grid buffers: only the engine knows which grids exist and how
+ * large they are, so it re-creates them itself right after this returns (`reviveGpu`). What this
+ * does promise is that the grid table is EMPTY afterwards, so those `createGrid` calls allocate
+ * rather than trying to free buffers that the lost context already took.
+ *
+ * **Throws when the rebuild fails** (a driver that will not compile the cell program against the
+ * fresh context). That is deliberately the same shape as `createWebgl2GL` returning null — the
+ * caller's only correct answer is a permanent fallback to the DOM renderer, and a half-built
+ * context that silently draws nothing would be indistinguishable from a frozen canvas.
+ */
+ restore(): void
dispose(): void
}