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(glyphgrid): notice when the atlas page dies with the GPU

enes4a93c13d1205
diff --git a/src/renderer/canvas/SharedGlyphLayer.tsx b/src/renderer/canvas/SharedGlyphLayer.tsx
index 30b3cac7d..cd9ff808c 100644
--- a/src/renderer/canvas/SharedGlyphLayer.tsx
+++ b/src/renderer/canvas/SharedGlyphLayer.tsx
@@ -19,6 +19,12 @@
* (`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`.
+ * **A GPU reset has a SECOND half**: it also blanks the OffscreenCanvas the atlas rasterizes
+ * into, and that one cannot be restored — its pixels are gone while `GlyphAtlas.slots` still
+ * claims every key is cached, which is the "every terminal went blank at once" report. It is
+ * answered by the same policy object driving `rebuildSharedContext` instead of a revive
+ * (`createContext`'s `atlasLoss`), and by a pixel check on the revive path for the silent case
+ * that fires no event at all (`reviveGpuOrRebuild`, `ATLAS_SENTINEL_RGBA`).
* 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
@@ -46,7 +52,7 @@ import { setBlankCellProbe } from '../glyphgrid/feed'
import { createFrameLoop, type FrameLoop } from '../glyphgrid/frame-driver'
import type { GlyphGL } from '../glyphgrid/gl'
import { createWebgl2GL } from '../glyphgrid/gl-webgl2'
-import { createCanvasRasterizer } from '../glyphgrid/raster'
+import { createCanvasRasterizer, type AtlasPageHealth } from '../glyphgrid/raster'
import { useProjects } from '../state/projects'
import { useSettings } from '../state/settings'
import { useViewMode, viewFor } from '../state/viewMode'
@@ -651,6 +657,14 @@ export interface SharedGlyphContext {
interface LiveContext extends SharedGlyphContext {
canvas: HTMLCanvasElement
gl: GlyphGL
+ /** The atlas PAGE, held for its health surface alone (`sourceIntact` on the revive path). The
+ * atlas itself never exposes it — see `ATLAS_SENTINEL_RGBA` for why the page has to be asked. */
+ raster: AtlasPageHealth
+ /** The page's own contextlost/contextrestored subscription, and the policy behind it. Both die
+ * with the context: a listener on a page we have thrown away would rebuild a context that no
+ * longer exists, and the policy's watchdog would fail a session that has already recovered. */
+ sourceLoss: { dispose(): void }
+ atlasLoss: ContextLossPolicy
/** The console reset gauge's subscription, held so teardown can drop it: the atlas dies with the
* context, but a subscription left on a rebuilt-and-then-disposed one would keep a closure alive
* per font change. */
@@ -925,11 +939,49 @@ function createContext(cell: DeviceCell): LiveContext | null {
installBlankCellProbe()
const engine = new GlyphGridEngine(gl, atlas)
engine.setCamera(lastCamera)
+ /**
+ * The ATLAS PAGE's own loss policy — the 2D half of a GPU reset, which until now had none.
+ *
+ * It is the SAME policy object the WebGL side uses, and the four rules transfer intact: restore
+ * once, give up on a second loss inside the cooldown, give up if the rebuild throws, give up on a
+ * bounded watchdog rather than waiting forever. Two details differ and both are spelled here
+ * rather than in the policy, because they are properties of the 2D context and not of the rule:
+ *
+ * - `onLost()`'s BOOLEAN IS MEANINGLESS HERE and is deliberately dropped. It means "call
+ * preventDefault()", which on a WebGL canvas is how you ASK for a restore and on a 2D canvas is
+ * how you REFUSE automatic restoration — the exact opposite. `onSourceLoss` never cancels.
+ * - REVIVE IS A REBUILD, not a restore. A lost 2D page cannot be restored: its pixels are gone
+ * while `GlyphAtlas.slots` still claims every key is present, so the only correct answer is to
+ * throw the whole context away and let every terminal re-rasterize what it needs against a
+ * fresh page. That is precisely `rebuildSharedContext`, the funnel a font change already uses,
+ * and it begins a new cell epoch for the same reason a font change does.
+ *
+ * SUSPEND IS A NO-OP, and that is the useful behaviour rather than a gap: the GL texture still
+ * holds the LAST GOOD upload of the page, so leaving the canvas exactly as it is shows the user
+ * their text — frozen — for the fraction of a second until the restore lands. Parking frames would
+ * show the same thing; re-uploading, which is what the un-fixed code did, shows nothing at all.
+ */
+ const atlasLoss = createContextLossPolicy({
+ now: () => Date.now(),
+ suspend: () => undefined,
+ revive: () => rebuildSharedContext(),
+ fail: (reason, err) => failSharedGlyph(reason, err),
+ setTimer: (cb, ms) => window.setTimeout(cb, ms),
+ clearTimer: (h) => window.clearTimeout(h)
+ })
return {
engine,
atlas,
canvas,
gl,
+ raster,
+ atlasLoss,
+ sourceLoss: raster.onSourceLoss({
+ lost: () => {
+ atlasLoss.onLost()
+ },
+ restored: () => atlasLoss.onRestored()
+ }),
resetLog: installAtlasResetLog(atlas),
fontKey: fontKeyOf(fontFamily, fontSize, fontWeight, fontWeightBold),
dpr,
@@ -949,6 +1001,13 @@ function disposeContext(): void {
// than submit against deleted objects (see `LiveContext.disposed`).
ctx.disposed = true
try {
+ // FIRST, and before anything that can throw: the atlas page's listeners and the watchdog behind
+ // them are the two things here that could outlive the context. A surviving listener would drive
+ // a rebuild off a page nobody is drawing from, and a surviving watchdog would fail a session
+ // whose context was merely handed back (this rebuild, the mode switched off) — which cannot then
+ // be re-enabled without a relaunch.
+ ctx.sourceLoss.dispose()
+ ctx.atlasLoss.stop()
ctx.resetLog.dispose()
ctx.engine.disposeAll()
ctx.gl.dispose()
@@ -1169,6 +1228,37 @@ export function createPixelRatioWatcher(
}
}
+/**
+ * Bring the engine's GPU objects back — UNLESS the atlas page did not survive whatever took them.
+ * Returns whether the caller may carry on with this context; false means it has been rebuilt and
+ * the generation bump is already on its way.
+ *
+ * THE CASE THIS CATCHES, and why the WebGL side's own policy cannot. A GPU reset takes the WebGL
+ * context AND blanks the OffscreenCanvas the atlas rasterizes into. The WebGL half announces itself
+ * and is answered by `engine.reviveGpu`, which re-uploads the atlas page — and `reviveGpu`'s comment
+ * says outright that this costs one upload rather than a re-rasterization "because the atlas SOURCE
+ * did not die with the context". When it did die, that upload is of an EMPTY page: `GlyphAtlas.slots`
+ * still holds every key, so nothing re-rasterizes, and every terminal on the canvas goes blank at
+ * once and stays blank until a font or dpr change happens to rebuild.
+ *
+ * The 2D context usually announces itself too (`onSourceLoss`), and when it does this check never
+ * fires. It exists for the case where it does NOT — a backing store that comes back wiped with no
+ * event — which is why the question is asked of the PIXELS (`ATLAS_SENTINEL_RGBA`) rather than of a
+ * flag. One 1px readback, on a path that runs at most once per context.
+ */
+function reviveGpuOrRebuild(ctx: LiveContext): boolean {
+ if (!ctx.raster.sourceIntact()) {
+ console.warn(
+ '[glyphgrid] the atlas page did not survive the GPU outage — every cached glyph now points ' +
+ 'at a blank texel, so the context is being rebuilt rather than re-uploaded'
+ )
+ rebuildSharedContext()
+ return false
+ }
+ ctx.engine.reviveGpu()
+ return true
+}
+
/** Fires when a context has just been BUILT. The component listens so it can mount the fresh
* canvas: creation is now driven by the first terminal that offers a device cell, which can
* happen after the layer's own effect has already run and found nothing. Deliberately NOT a
@@ -1965,7 +2055,9 @@ export function SharedGlyphLayer(): JSX.Element {
// comment: nothing enforces that ordering, and a mount is the one moment we can still decide.
if (ctx.engine.gpuIsSuspended()) {
try {
- ctx.engine.reviveGpu()
+ // Rebuilt instead of revived (a blanked atlas page) means this context is gone and the
+ // generation bump will re-run this effect against the fresh one.
+ if (!reviveGpuOrRebuild(ctx)) return
console.warn('[glyphgrid] mounted onto a suspended engine — GPU objects rebuilt')
} catch (err) {
// The context is still gone (its programs will not compile), so there is nothing to mount
@@ -2171,7 +2263,11 @@ export function SharedGlyphLayer(): JSX.Element {
ctx.engine.suspendGpu()
},
revive: () => {
- ctx.engine.reviveGpu()
+ // A GPU reset takes the atlas page with the context. Reviving onto a blanked page would
+ // upload an empty atlas over every terminal on the canvas, so that case rebuilds instead —
+ // and there is no runtime to start here, because there is no longer a context to start it
+ // against.
+ if (!reviveGpuOrRebuild(ctx)) return
runtime = startRuntime()
},
fail: (reason, err) => failSharedGlyph(reason, err),
diff --git a/src/renderer/glyphgrid/raster.test.ts b/src/renderer/glyphgrid/raster.test.ts
index e2302ded4..b98b11456 100644
--- a/src/renderer/glyphgrid/raster.test.ts
+++ b/src/renderer/glyphgrid/raster.test.ts
@@ -2,7 +2,10 @@ import { afterEach, describe, expect, it } from 'vitest'
import { GlyphAtlas, GUTTER_PX } from './atlas'
import { packColor } from './cells'
import {
+ ATLAS_SENTINEL_RGBA,
+ SENTINEL_CSS,
createCanvasRasterizer,
+ sentinelIntact,
shrinkEligible,
shrinkToFit,
underlineThickness
@@ -62,6 +65,16 @@ function stubCanvas(
pixelAt: (x: number, y: number) => string
/** The page-wide `imageSmoothingEnabled` as it stands NOW — for asserting it was restored. */
smoothingNow: () => boolean
+ /** Wipe every texel WITHOUT going through `clearPage` — what a GPU reset does to the backing
+ * store behind the rasterizer's back, and the case the sentinel exists to detect. */
+ blankPage: () => void
+ /** Drive `ctx.isContextLost()`, the cheap check that runs before the readback. */
+ setContextLost: (lost: boolean) => void
+ /** Dispatch a canvas context event; returns whether a listener cancelled it. Cancelling
+ * `contextlost` is how a page REFUSES automatic restoration, so "was it cancelled" is a
+ * behavioural assertion, not a detail. */
+ fire: (type: 'contextlost' | 'contextrestored') => boolean
+ listenerCount: () => number
restore: () => void
} {
const ops: Op[] = []
@@ -184,8 +197,20 @@ function stubCanvas(
fontBoundingBoxDescent: 4,
actualBoundingBoxLeft: 0,
actualBoundingBoxRight: inkWidth
- })
+ }),
+ isContextLost: () => contextLost,
+ /** Only the 1x1 form the sentinel check uses. The model stores CSS colour strings, so this is
+ * the inverse of `rgb(r,g,b)` — and an unpainted texel is transparent-black, exactly as a real
+ * fresh (or blanked) page reads back. */
+ getImageData(x: number, y: number): { data: number[] } {
+ const color = px[y * sizePx + x] ?? ''
+ const m = /^rgb\((\d+),(\d+),(\d+)\)$/.exec(color)
+ if (!m) return { data: [0, 0, 0, 0] }
+ return { data: [Number(m[1]), Number(m[2]), Number(m[3]), 255] }
+ }
}
+ const listeners = new Map<string, Set<(e: { preventDefault(): void }) => void>>()
+ let contextLost = false
const prev = (globalThis as Record<string, unknown>).OffscreenCanvas
;(globalThis as Record<string, unknown>).OffscreenCanvas = class {
constructor(
@@ -197,6 +222,14 @@ function stubCanvas(
getContext(): unknown {
return ctx
}
+ addEventListener(type: string, fn: (e: { preventDefault(): void }) => void): void {
+ const set = listeners.get(type) ?? new Set()
+ set.add(fn)
+ listeners.set(type, set)
+ }
+ removeEventListener(type: string, fn: (e: { preventDefault(): void }) => void): void {
+ listeners.get(type)?.delete(fn)
+ }
}
return {
ops,
@@ -206,6 +239,22 @@ function stubCanvas(
smoothingNow() {
return ctx.imageSmoothingEnabled
},
+ blankPage() {
+ px.fill('')
+ },
+ setContextLost(lost: boolean) {
+ contextLost = lost
+ },
+ fire(type) {
+ let cancelled = false
+ for (const fn of listeners.get(type) ?? []) fn({ preventDefault: () => (cancelled = true) })
+ return cancelled
+ },
+ listenerCount() {
+ let n = 0
+ for (const set of listeners.values()) n += set.size
+ return n
+ },
restore() {
;(globalThis as Record<string, unknown>).OffscreenCanvas = prev
}
@@ -252,8 +301,13 @@ describe('createCanvasRasterizer', () => {
createCanvasRasterizer(FONT, 256)
// The old opaque-black page fill is GONE: the backdrop is now per-slot (the bg fill in
// `draw`), and a page-wide fill would put an opaque colour in slot 0, which every space
- // samples.
- expect(stub.ops).toEqual([])
+ // samples. The ONE texel painted here is the sentinel, and it lands in slot 0's GUTTER —
+ // outside every sampled rect on the page. See `sentinelIntact`.
+ expect(stub.ops).toEqual([{ kind: 'fillRect', fill: SENTINEL_CSS, args: [0, 0, 1, 1] }])
+ // The part that actually matters: slot 0's SAMPLED cell box is untouched, so a space still
+ // samples transparent-black.
+ expect(stub.pixelAt(GUTTER_PX, GUTTER_PX)).toBe('')
+ expect(stub.pixelAt(GUTTER_PX + COLS_W - 1, GUTTER_PX + COLS_H - 1)).toBe('')
})
it('fills the FULL PITCH rect with bg, then clips the ink to the CELL rect and draws it in fg', () => {
@@ -573,8 +627,13 @@ describe('createCanvasRasterizer', () => {
stub.ops.length = 0
r.clearPage()
// clearRect, NOT a fill: the page ground has to go back to transparent-black so slot 0 stays
- // the blank slot every space samples.
- expect(stub.ops).toEqual([{ kind: 'clearRect', args: [0, 0, 256, 256] }])
+ // the blank slot every space samples. The sentinel is then REPAINTED, because a reset is a
+ // normal event and a page missing its sentinel afterwards would read as a lost 2D context and
+ // rebuild the whole canvas on the next revive.
+ expect(stub.ops).toEqual([
+ { kind: 'clearRect', args: [0, 0, 256, 256] },
+ { kind: 'fillRect', fill: SENTINEL_CSS, args: [0, 0, 1, 1] }
+ ])
})
it('never draws slot 0, so the blank slot every space samples stays transparent', () => {
@@ -1145,3 +1204,96 @@ describe('font weight reaches the rasterized glyph', () => {
expect(fontStringFor(400, 700, true)).toContain('700 16px')
})
})
+
+/**
+ * THE BLANK-EVERYTHING BUG the sentinel exists for.
+ *
+ * The atlas page is an OffscreenCanvas 2D context, and a GPU reset (sleep/wake, a driver hiccup)
+ * blanks its backing store. Nothing downstream notices: `GlyphAtlas.slots` still holds every key, so
+ * no glyph is ever re-rasterized, and `engine.reviveGpu` re-uploads the now-EMPTY page as the atlas
+ * texture. Every terminal on the canvas shows empty cells at once, for the rest of the session.
+ *
+ * One texel of known colour, checked with a 1px readback, is what turns that into a detectable
+ * event — including the silent case, where the 2D context fires no `contextlost` at all.
+ */
+describe('sentinelIntact', () => {
+ it('accepts the sentinel colour', () => {
+ expect(sentinelIntact([...ATLAS_SENTINEL_RGBA])).toBe(true)
+ })
+
+ it('REJECTS transparent-black, which is what a blanked page reads back as', () => {
+ expect(sentinelIntact([0, 0, 0, 0])).toBe(false)
+ })
+
+ it('rejects an opaque black or white page — a wipe need not be to transparent', () => {
+ expect(sentinelIntact([0, 0, 0, 255])).toBe(false)
+ expect(sentinelIntact([255, 255, 255, 255])).toBe(false)
+ })
+
+ it('tolerates a few units of colour-management rounding either way', () => {
+ expect(sentinelIntact([252, 3, 251, 255])).toBe(true)
+ })
+
+ it('rejects a short buffer rather than reading past the end', () => {
+ expect(sentinelIntact([255, 0, 255])).toBe(false)
+ })
+})
+
+describe('atlas page health', () => {
+ it('reports the page intact right after construction', () => {
+ const stub = stubCanvas()
+ active = stub
+ expect(createCanvasRasterizer(FONT, 256)!.sourceIntact()).toBe(true)
+ })
+
+ it('reports the page intact after a clearPage, because a reset repaints the sentinel', () => {
+ const stub = stubCanvas()
+ active = stub
+ const r = createCanvasRasterizer(FONT, 256)!
+ r.clearPage()
+ expect(r.sourceIntact()).toBe(true)
+ })
+
+ it('reports LOST when the backing store was wiped behind our back', () => {
+ // Exactly the silent case: no event fired, `slots` still full, and the next `reviveGpu` would
+ // upload an empty page over every terminal on the canvas.
+ const stub = stubCanvas()
+ active = stub
+ const r = createCanvasRasterizer(FONT, 256)!
+ stub.blankPage()
+ expect(r.sourceIntact()).toBe(false)
+ })
+
+ it('reports LOST on isContextLost() without needing the readback', () => {
+ const stub = stubCanvas()
+ active = stub
+ const r = createCanvasRasterizer(FONT, 256)!
+ stub.setContextLost(true)
+ expect(r.sourceIntact()).toBe(false)
+ })
+
+ it('routes contextlost / contextrestored to the caller and does NOT cancel the loss', () => {
+ // Cancelling `contextlost` tells the browser not to restore automatically, which is the
+ // opposite of what this wants: the restore is the signal that a fresh page can be built.
+ const stub = stubCanvas()
+ active = stub
+ const r = createCanvasRasterizer(FONT, 256)!
+ const seen: string[] = []
+ r.onSourceLoss({ lost: () => seen.push('lost'), restored: () => seen.push('restored') })
+ expect(stub.fire('contextlost')).toBe(false)
+ stub.fire('contextrestored')
+ expect(seen).toEqual(['lost', 'restored'])
+ })
+
+ it('dispose() unsubscribes, so a rebuilt context never hears the old page`s events', () => {
+ const stub = stubCanvas()
+ active = stub
+ const r = createCanvasRasterizer(FONT, 256)!
+ const seen: string[] = []
+ const sub = r.onSourceLoss({ lost: () => seen.push('lost'), restored: () => undefined })
+ sub.dispose()
+ expect(stub.listenerCount()).toBe(0)
+ stub.fire('contextlost')
+ expect(seen).toEqual([])
+ })
+})
diff --git a/src/renderer/glyphgrid/raster.ts b/src/renderer/glyphgrid/raster.ts
index 9726f6e87..e7cf7866e 100644
--- a/src/renderer/glyphgrid/raster.ts
+++ b/src/renderer/glyphgrid/raster.ts
@@ -2,6 +2,76 @@ import { GUTTER_PX, partCells, slotPitch, type GlyphRasterizer } from './atlas'
import { boxGlyphOps } from './box-glyphs'
import { unpackColor } from './cells'
+/**
+ * THE SENTINEL TEXEL, and the blank-everything bug it exists to detect.
+ *
+ * The atlas page is an OffscreenCanvas 2D context created once, for the life of the shared context.
+ * A GPU reset — macOS sleep/wake, a driver hiccup, a GPU-process restart — BLANKS its backing store,
+ * and every layer above it keeps believing the page is full: `GlyphAtlas.slots` still holds every
+ * key, so not one glyph is re-rasterized, and `engine.reviveGpu` (whose comment says outright that
+ * the 2D source survived) re-uploads the empty page as the atlas texture. The result is every
+ * terminal on the canvas showing empty cells at the same instant, permanently, with the app
+ * otherwise alive — which is exactly the field report this answers.
+ *
+ * The WebGL half of that reset arrives as an event and has a policy. The 2D half may fire
+ * `contextlost` too (handled — see `onSourceLoss`), but it is not guaranteed to: a page can come back
+ * wiped with no event at all. So the revive path needs a way to ASK, and a 1-texel readback of a
+ * colour we painted ourselves is the cheapest honest answer — cheaper than hashing the page,
+ * and unlike "is any slot allocated" it distinguishes a page we filled from a page that was emptied.
+ *
+ * WHERE IT LIVES: page pixel (0,0), the top-left corner of SLOT 0's pitch cell, inside its gutter.
+ * That is the one texel on the page that no sampling can reach. Slot 0 is never inked (`glyphFor`
+ * returns it for blanks without drawing) and never sampled (the shader branches on the glyph lane
+ * being 0 and paints the cell's own background), and slot 1's ink starts `ceil(cellW) + 3*GUTTER_PX`
+ * texels away — several LOD-2 blocks clear, so it cannot bleed into a real glyph's mip either. Any
+ * other placement costs a slot or contaminates one.
+ *
+ * WHY IT IS REPAINTED BY `clearPage`: an atlas reset is a NORMAL event (the page is a working set,
+ * not a cache of everything), and a page that lost its sentinel to an ordinary reset would read as a
+ * lost context and rebuild the whole canvas on the next revive.
+ */
+export const ATLAS_SENTINEL_RGBA = [255, 0, 255, 255] as const
+
+/** The same colour as the canvas takes it. Exported so a test asserts the ONE op this adds. */
+export const SENTINEL_CSS = 'rgb(255,0,255)'
+
+/** How far a channel may drift and still count as the sentinel. The canvas is sRGB and the fill is
+ * exact, so this absorbs colour-management rounding rather than any real difference — a wiped page
+ * reads back 0,0,0,0 and misses by 255. */
+const SENTINEL_TOLERANCE = 8
+
+/** Does this 1px readback still hold the sentinel? Pure, so the rule is testable without a canvas.
+ * A short buffer answers NO: a readback that gave us less than a pixel is not evidence of health. */
+export function sentinelIntact(px: ArrayLike<number>): boolean {
+ if (px.length < 4) return false
+ for (let i = 0; i < 4; i++) {
+ if (Math.abs(px[i] - ATLAS_SENTINEL_RGBA[i]) > SENTINEL_TOLERANCE) return false
+ }
+ return true
+}
+
+/** What the shared layer needs to hear from the atlas page — see `ATLAS_SENTINEL_RGBA`. */
+export interface AtlasPageLossHandlers {
+ /** The 2D context was lost. The page's pixels are gone; the caller waits for `restored`. */
+ lost(): void
+ /** The browser handed a fresh, EMPTY 2D context back. The caller's answer is a full rebuild:
+ * there is no restoring the old pixels, only re-rasterizing them from a fresh page. */
+ restored(): void
+}
+
+/** The page-health surface `createCanvasRasterizer` adds on top of `GlyphRasterizer`. Kept OFF the
+ * atlas's own interface deliberately: the atlas neither calls these nor should have to fake them,
+ * and the only consumer is the shared layer that owns the context's lifetime. */
+export interface AtlasPageHealth {
+ /** Is the page still the one we rasterized into? False = the backing store was blanked or the
+ * context was lost, and every cached slot now points at nothing. */
+ sourceIntact(): boolean
+ /** Subscribe to the page's own `contextlost`/`contextrestored`. Never cancels the loss event —
+ * cancelling is how a page REFUSES automatic restoration, and the restore is the signal we
+ * want. */
+ onSourceLoss(handlers: AtlasPageLossHandlers): { dispose(): void }
+}
+
export interface RasterFont {
family: string
sizePx: number
@@ -342,16 +412,24 @@ function baselineIn(ctx: OffscreenCanvasRenderingContext2D, font: RasterFont): n
export function createCanvasRasterizer(
font: RasterFont,
atlasSizePx: number
-): GlyphRasterizer | null {
+): (GlyphRasterizer & AtlasPageHealth) | null {
if (typeof OffscreenCanvas === 'undefined') return null
const canvas = new OffscreenCanvas(atlasSizePx, atlasSizePx)
const ctx = canvas.getContext('2d', { alpha: true })
if (!ctx) return null
ctx.textBaseline = 'alphabetic'
- // NOTHING is painted here. A fresh OffscreenCanvas is already transparent-black, which is the
+ /** One texel, in the one place nothing samples — see `ATLAS_SENTINEL_RGBA`. Unclipped and
+ * unsaved, because it runs only where no clip is installed (construction and `clearPage`). */
+ const paintSentinel = (): void => {
+ ctx.fillStyle = SENTINEL_CSS
+ ctx.fillRect(0, 0, 1, 1)
+ }
+ // NOTHING ELSE is painted here. A fresh OffscreenCanvas is already transparent-black, which is the
// page ground this atlas wants; the backdrop the platform rasterizer needs is per-slot and is
// painted in `draw`. (Round 6's page-wide opaque black fill lived here — see the header for why
- // it must not come back.)
+ // it must not come back.) The sentinel is one texel of slot 0's GUTTER, so every SAMPLED rect on
+ // the page — slot 0's cell box included — is still transparent-black.
+ paintSentinel()
const baseline = baselineIn(ctx, font)
// The slot pitch, from the SAME helper the atlas lays the page out with — the background fill
// below has to cover exactly one pitch cell.
@@ -385,6 +463,49 @@ export function createCanvasRasterizer(
* never-allocated pitch cell) an opaque colour, and slot 0 is what every space samples. */
clearPage() {
ctx.clearRect(0, 0, atlasSizePx, atlasSizePx)
+ // ...and back to that state EXACTLY, sentinel included. A reset is a normal event, so a page
+ // left without one would read as a lost 2D context on the next revive and rebuild the whole
+ // canvas for nothing.
+ paintSentinel()
+ },
+ /** The health check the revive path runs. Two questions, cheapest first: has the context
+ * declared itself lost, and — the case that fires no event at all — is the page still the one
+ * we painted?
+ *
+ * A readback that THROWS answers "intact". It tells us nothing about the page, and treating an
+ * unavailable `getImageData` as a loss would rebuild the whole canvas on every restore, which
+ * is worse than the bug. */
+ sourceIntact() {
+ const lost = (ctx as { isContextLost?: () => boolean }).isContextLost
+ if (typeof lost === 'function' && lost.call(ctx)) return false
+ try {
+ return sentinelIntact(ctx.getImageData(0, 0, 1, 1).data)
+ } catch {
+ return true
+ }
+ },
+ onSourceLoss(handlers) {
+ const target = canvas as unknown as {
+ addEventListener?: (type: string, fn: (e: Event) => void) => void
+ removeEventListener?: (type: string, fn: (e: Event) => void) => void
+ }
+ // An OffscreenCanvas that is not an EventTarget (an old runtime, a test double) degrades to
+ // "not watched" — `sourceIntact` is still the backstop, and it needs no events.
+ if (typeof target.addEventListener !== 'function') return { dispose: () => undefined }
+ // DELIBERATELY NOT `preventDefault()`. On a 2D canvas, cancelling `contextlost` tells the
+ // browser NOT to restore automatically — the opposite of the WebGL convention, where
+ // cancelling is how you ASK for the restore. The restore is what we are waiting for: it is
+ // the moment a fresh page can be rasterized into.
+ const onLost = (): void => handlers.lost()
+ const onRestored = (): void => handlers.restored()
+ target.addEventListener('contextlost', onLost)
+ target.addEventListener('contextrestored', onRestored)
+ return {
+ dispose: () => {
+ target.removeEventListener?.('contextlost', onLost)
+ target.removeEventListener?.('contextrestored', onRestored)
+ }
+ }
},
/** `x, y` is the INK origin the atlas hands us — already one gutter inside the pitch cell on
* each axis (`GlyphAtlas.cellXY`) — and `fg`/`bg` are the FINAL packed colour lanes for this