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): a terminal is one renderer's, structurally — plus tests that can see a pitch/extent conflation

enes418735de7383
diff --git a/src/renderer/canvas/SharedGlyphLayer.test.ts b/src/renderer/canvas/SharedGlyphLayer.test.ts
index a42c1b18c..dda17f580 100644
--- a/src/renderer/canvas/SharedGlyphLayer.test.ts
+++ b/src/renderer/canvas/SharedGlyphLayer.test.ts
@@ -8,6 +8,7 @@ import {
setNodeZOrder,
setSharedGlyphCamera,
sharedGlyphActive,
+ sharedGlyphAvailable,
subscribeNodeZOrder,
useSharedGlyph
} from './SharedGlyphLayer'
@@ -370,3 +371,61 @@ describe('graceful degrade without a GPU', () => {
}
})
})
+
+/**
+ * The BOTH-RENDERERS invariant, tested at the one seam that is reachable headless.
+ *
+ * A terminal is either a budget-coordinated per-node WebGL client or a grid on the shared canvas —
+ * never both (the glyph addon's `setRenderer` and `WebglAddon.dispose()` each silently replace the
+ * other's renderer) and never neither. `TerminalNode` decides that from `sharedGlyphAvailable()`,
+ * so the predicate must answer "shared" for a canvas whose context has not been BUILT yet: the
+ * atlas now adopts a live terminal's device cell, which makes "no context yet" the normal state at
+ * a fresh mount and again after every font change.
+ */
+describe('sharedGlyphAvailable', () => {
+ const CELL = { cellW: 15.66, cellH: 31 }
+
+ beforeEach(() => {
+ // `creationAttempted` is a module singleton that survives a store reset, and only
+ // `disposeContext()` clears it — which an enable/disable pair runs, silently (unlike
+ // `markFailed`, which logs). Without this the block would depend on what ran before it.
+ useSharedGlyph.getState().setEnabled(true)
+ useSharedGlyph.getState().setEnabled(false)
+ })
+
+ afterEach(() => {
+ useSharedGlyph.setState({ enabled: false, generation: 0, failed: false })
+ })
+
+ it('is false while the mode is off, and false once the session has failed', () => {
+ expect(sharedGlyphAvailable()).toBe(false)
+ useSharedGlyph.getState().setEnabled(true)
+ useSharedGlyph.getState().markFailed()
+ expect(sharedGlyphAvailable()).toBe(false)
+ })
+
+ it('is TRUE with the mode on and no context built yet — the fresh-mount state', () => {
+ useSharedGlyph.getState().setEnabled(true)
+ // Nothing has asked for a context, so none exists. A probe that reported "not shared" here
+ // would hand every terminal on the canvas a WebGL budget client moments before each of them
+ // attaches a grid.
+ expect(sharedGlyphAvailable()).toBe(true)
+ })
+
+ it('turns false once this machine has PROVED it cannot build a context', () => {
+ useSharedGlyph.getState().setEnabled(true)
+ // No OffscreenCanvas in this environment: creation is attempted and produces nothing.
+ expect(getSharedGlyphContext(CELL)).toBeNull()
+ expect(sharedGlyphAvailable()).toBe(false)
+ })
+
+ it('is TRUE again after a disposal — a font change must not look like a failure', () => {
+ useSharedGlyph.getState().setEnabled(true)
+ expect(getSharedGlyphContext(CELL)).toBeNull() // latches the failed attempt
+ expect(sharedGlyphAvailable()).toBe(false)
+ // Mode off → disposeContext() (the same call a font change makes) → the latch is cleared.
+ useSharedGlyph.getState().setEnabled(false)
+ useSharedGlyph.getState().setEnabled(true)
+ expect(sharedGlyphAvailable()).toBe(true)
+ })
+})
diff --git a/src/renderer/canvas/SharedGlyphLayer.tsx b/src/renderer/canvas/SharedGlyphLayer.tsx
index 0c1d0b1ba..3b6ee692c 100644
--- a/src/renderer/canvas/SharedGlyphLayer.tsx
+++ b/src/renderer/canvas/SharedGlyphLayer.tsx
@@ -139,6 +139,29 @@ export function sharedGlyphActive(): boolean {
return s.enabled && !s.failed
}
+/**
+ * Will this canvas paint terminals into the shared context — whether or not one has been BUILT
+ * yet? This, not the presence of a context object, is the question a terminal asks when deciding
+ * which renderer it belongs to (and therefore whether it takes a WebGL budget client).
+ *
+ * Deliberately non-creating, and deliberately NOT `getSharedGlyphContext(…) !== null`. Since the
+ * atlas adopts a live terminal's device cell, the context now comes into existence at the first
+ * `setupGlyph` — so "no context yet" is the normal state at a fresh mount, and again after every
+ * font change (the layer disposes the context BEFORE it bumps the generation). A caller reading
+ * that as "not shared" would hand every terminal on the canvas a budget client moments before
+ * they all attach grids: the both-renderers hazard. Nor may such a caller build one to find out —
+ * at the font-change bump xterm has not re-measured its cell yet, so a context created there
+ * would rasterize its atlas at the OLD cell while every grid registers against the new one.
+ *
+ * False therefore means only: the mode is off, the session has failed, or this machine has
+ * already proved it cannot build a context (`creationAttempted` with nothing live — a flag every
+ * disposal resets, so a font change never looks like a failure).
+ */
+export function sharedGlyphAvailable(): boolean {
+ if (!sharedGlyphActive()) return false
+ return live !== null || !creationAttempted
+}
+
/** Reactive form of `sharedGlyphActive()` — Canvas mounts the layer on this. */
export function useSharedGlyphActive(): boolean {
return useSharedGlyph((s) => s.enabled && !s.failed)
diff --git a/src/renderer/glyphgrid/atlas.test.ts b/src/renderer/glyphgrid/atlas.test.ts
index a27be3aaa..b7c194f30 100644
--- a/src/renderer/glyphgrid/atlas.test.ts
+++ b/src/renderer/glyphgrid/atlas.test.ts
@@ -51,22 +51,39 @@ describe('GlyphAtlas', () => {
expect(atlas.slotRect(10)).toEqual({ u0: 0, v0: 0.2, u1: 0.1, v1: 0.4 })
})
- it('slotRect agrees with the shader uv derivation for every interesting slot', () => {
- // What this pins, exactly: `slotRect` against a HAND-TRANSCRIBED copy of gl-webgl2's vertex
- // shader formula as of Phase 0 — cols = floor(sizePx/cellW), cellUv = [cellW/sizePx,
- // cellH/sizePx], slotOrigin = (slot % cols, floor(slot / cols)) * cellUv (see `uAtlasCols` /
- // `uAtlasCell` in VERT). So it catches a change to the CPU side (atlas padding, page metrics,
- // slot ordering) — and nothing else.
- //
- // It is NOT a tie to the live GLSL: the shader side below is this test's own copy, so editing
- // the real shader leaves this green, and `slotRect` currently has no production caller at all
- // (the shader derives its uvs itself from the two uniforms). The actual tie — a visual pass,
- // or pinning the GLSL against a generated line — is owed to Phase 1b.
- const atlas = new GlyphAtlas(fakeRasterizer(10, 20), 100)
- const cols = Math.floor(100 / atlas.strideX)
- const cellUv = [10 / 100, 20 / 100]
- const strideUv = [atlas.strideX / 100, atlas.strideY / 100]
- for (const slot of [0, 1, cols - 1, cols, cols + 1, atlas.capacity - 1]) {
+ // What this pins, exactly: `slotRect` against a HAND-TRANSCRIBED copy of gl-webgl2's vertex
+ // shader formula — cols = floor(sizePx/strideX), cellUv = [cellW/sizePx, cellH/sizePx],
+ // strideUv = [strideX/sizePx, strideY/sizePx], slotOrigin = (slot % cols, floor(slot / cols)) *
+ // strideUv (see `uAtlasCols` / `uAtlasCell` / `uAtlasStride` in VERT). So it catches a change to
+ // the CPU side (atlas padding, page metrics, slot ordering) — and nothing else.
+ //
+ // Every number on the shader side is computed HERE, from the cell the rasterizer was built with
+ // — never read back off the atlas. Deriving `cols` from `atlas.strideX` would make the test
+ // agree with whatever the atlas decided, including conflating the pitch with the extent.
+ //
+ // It is NOT a tie to the live GLSL: the shader side below is this test's own copy, so editing
+ // the real shader leaves this green, and `slotRect` currently has no production caller at all
+ // (the shader derives its uvs itself from the uniforms). The actual tie — a visual pass, or
+ // pinning the GLSL against a generated line — is owed to Phase 1b.
+ //
+ // Run over an integer cell AND a fractional one: an integer cell has stride === extent, so it
+ // alone cannot tell a pitch/extent conflation from a correct derivation.
+ it.each([
+ { label: 'integer cell (stride === extent)', cellW: 10, cellH: 20, sizePx: 100 },
+ { label: 'fractional device cell (13px font at dpr 2)', cellW: 15.66, cellH: 31.2, sizePx: 512 }
+ ])('slotRect agrees with the shader uv derivation for every interesting slot — $label', ({
+ cellW,
+ cellH,
+ sizePx
+ }) => {
+ const atlas = new GlyphAtlas(fakeRasterizer(cellW, cellH), sizePx)
+ const strideX = Math.ceil(cellW)
+ const strideY = Math.ceil(cellH)
+ const cols = Math.floor(sizePx / strideX)
+ const rows = Math.floor(sizePx / strideY)
+ const cellUv = [cellW / sizePx, cellH / sizePx]
+ const strideUv = [strideX / sizePx, strideY / sizePx]
+ for (const slot of [0, 1, cols - 1, cols, cols + 1, cols * rows - 1]) {
const u0 = (slot % cols) * strideUv[0]
const v0 = Math.floor(slot / cols) * strideUv[1]
expect(atlas.slotRect(slot)).toEqual({ u0, v0, u1: u0 + cellUv[0], v1: v0 + cellUv[1] })
diff --git a/src/renderer/glyphgrid/engine.test.ts b/src/renderer/glyphgrid/engine.test.ts
index 2a8641b8b..ac974c7fd 100644
--- a/src/renderer/glyphgrid/engine.test.ts
+++ b/src/renderer/glyphgrid/engine.test.ts
@@ -264,16 +264,20 @@ describe('GlyphGridEngine', () => {
it('uploads the atlas with the rasterizer metrics before beginFrame', () => {
const gl = fakeGL()
- const { atlas: a, source } = loadedAtlas(512, 7, 15)
+ // A FRACTIONAL cell on purpose — that is what xterm reports (`charWidth * dpr`), and it is the
+ // only shape in which conflating the sampled EXTENT with the slot PITCH is observable: with an
+ // integer cell the two are equal, so passing either number for the other would pass.
+ const { atlas: a, source } = loadedAtlas(512, 15.66, 31.2)
const e = new GlyphGridEngine(gl, a)
e.setViewport(800, 600, 1)
e.setCamera({ x: 0, y: 0, zoom: 1 })
e.register(spec('a', 0))
a.glyphFor(0x41, false, false) // dirties the atlas
expect(e.frame()).toBe(true)
- // …including the slot PITCH beside the sampled extent: the shader needs both, and handing it
- // the extent as the pitch would overlap every slot with its neighbour.
- expect(gl.uploadAtlas).toHaveBeenCalledWith(source, 512, 7, 15, 7, 15)
+ // The extent stays exact (texel:pixel 1:1 against the quad the grid draws) and the pitch is
+ // the whole-texel slot spacing; the shader needs both, and handing it the extent as the pitch
+ // would overlap every slot with its neighbour.
+ expect(gl.uploadAtlas).toHaveBeenCalledWith(source, 512, 15.66, 31.2, 16, 32)
// Stronger than "before the first drawGrid": beginFrame pushes uAtlasCols/uAtlasCell from
// the values uploadAtlas stored, so an upload landing after it would leave frame 1 sampling
// slot 0 everywhere and the uniforms permanently one upload stale.
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 7169ab20b..f95bb0b2b 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -60,6 +60,7 @@ import {
getSharedGlyphContext,
nodeZFor,
sharedGlyphActive,
+ sharedGlyphAvailable,
subscribeNodeZOrder,
useSharedGlyph
} from '../canvas/SharedGlyphLayer'
@@ -811,6 +812,13 @@ export function TerminalNode({
// "lost context" placeholder). The callbacks stay dumb and idempotent.
let webgl: WebglAddon | null = null
let webglHandle: WebglClientHandle | null = null
+ /** The IntersectionObserver's last verdict, re-stated to any budget client registered after
+ * it (the observer will not fire again until visibility actually CHANGES, and a fresh client
+ * starts out believing it is hidden). Declared up here with the handle it belongs to, not
+ * next to the observer: `ensureWebglClient` can run from the glyph setup at mount, which is
+ * BEFORE the observer is built — a `let` declared down there would be in its temporal dead
+ * zone and throw. */
+ let wasVisible = false
// --- glyphgrid (experimental shared renderer) -----------------------------------------
// Live only while this terminal paints into the shared canvas instead of its own renderer.
// All four stay null for the default modes: `setupGlyph()` returns on its first gate without
@@ -1070,6 +1078,38 @@ export function TerminalNode({
}
applyFitRef.current = applyFit
+ /**
+ * THE BOTH-RENDERERS INVARIANT, in two calls: a terminal is either a budget-coordinated
+ * per-node WebGL client or a grid on the shared canvas — never both, and never neither.
+ *
+ * Holding both is not a cosmetic overlap. The glyph addon's `setRenderer` silently disposes
+ * whatever renderer it replaces, so a webgl grant landing afterwards leaves the coordinator
+ * accounting for a context nobody paints with; and the reverse — `releaseWebgl` running while
+ * a glyph attachment is live — is worse: `WebglAddon.dispose()` puts xterm back on its own DOM
+ * renderer, which disposes OUR addon, and the DOM rows are `visibility: hidden` in glyph mode,
+ * so the node goes blank with a grid still registered.
+ *
+ * That is why `dropWebglClient` runs BEFORE `attachGlyphGrid` and not after it: disposing the
+ * handle releases any live grant synchronously, so xterm is back on its own renderer before we
+ * install ours.
+ *
+ * Both are idempotent, and both are called from the glyph setup/teardown as well as from the
+ * mode probes — the invariant must hold structurally, not because one probe happened to run at
+ * the right moment.
+ */
+ const dropWebglClient = (): void => {
+ if (!webglHandle) return
+ webglHandle.dispose()
+ webglHandle = null
+ }
+ const ensureWebglClient = (): void => {
+ // `disposed` covers unmount/park/respawn, where the cleanup has already disposed the handle
+ // and a fresh registration would be a leak into a coordinator nothing will unregister from.
+ if (disposed || webglHandle) return
+ webglHandle = registerWebglClient(id, { acquire: acquireWebgl, release: releaseWebgl })
+ webglHandle.setVisible(wasVisible)
+ }
+
// --- glyphgrid (experimental shared renderer) -------------------------------------------
//
// Lives INSIDE the lifecycle effect, not in an effect of its own, for one reason: React runs
@@ -1120,6 +1160,13 @@ export function TerminalNode({
term.element?.classList.remove('glyphgrid-mode')
const restored = attach ? attach.dispose() : true
grid?.dispose()
+ // The other half of the both-renderers invariant: xterm owns its own pixels again, so it is
+ // a budget client again. Belt and braces — the generation handler and the participation
+ // effect also decide this from the MODE, and either may (correctly) dispose the client again
+ // a moment later. Skipped when the restore failed: that xterm paints nothing, and a webgl
+ // grant onto it would only add a second broken renderer to the first. `ensureWebglClient`
+ // itself refuses once `disposed` is set, which is every unmount/park/respawn path.
+ if (restored) ensureWebglClient()
return restored
}
@@ -1147,7 +1194,14 @@ export function TerminalNode({
// from, and `getSharedGlyphContext` answers null rather than guess metrics that would leave
// every glyph rescaled against the quad it is drawn onto.
const ctx = getSharedGlyphContext(deviceCellOf(term) ?? undefined)
- if (!ctx) return
+ // Nothing to paint into (no WebGL2, no OffscreenCanvas, no readable device cell): this
+ // terminal keeps its own renderer, so it must be a budget CLIENT — the other half of the
+ // both-renderers invariant, which is "never both" AND "never neither". Same on every failure
+ // path below.
+ if (!ctx) {
+ ensureWebglClient()
+ return
+ }
const host = term.element
const cell = forcedCell ?? cssCellOf(term)
const offset = host ? screenOffsetInNode(term) : null
@@ -1156,6 +1210,7 @@ export function TerminalNode({
`${id}:geometry`,
`no grid for node ${id}: ${!host ? 'no xterm element' : !cell ? 'cell size unavailable' : 'terminal is not laid out inside a node'}`
)
+ ensureWebglClient()
return
}
glyphBodyOffsetRef.current = offset
@@ -1183,12 +1238,21 @@ export function TerminalNode({
})
} catch (err) {
glyphWarn(`${id}:register`, `could not register a grid for node ${id}: ${String(err)}`)
+ ensureWebglClient()
return
}
+ // BEFORE the attach, never after: disposing the budget client releases any live grant
+ // synchronously, and `releaseWebgl` puts xterm back on its own DOM renderer — which, run a
+ // line later, would dispose the glyph addon we are about to install and leave the node blank.
+ // See the both-renderers invariant above.
+ dropWebglClient()
const attached = attachGlyphGrid(term, handle, ctx.atlas)
if (!attached) {
// Nothing was touched (the attach contract) — drop the grid we just made and stay put.
handle.dispose()
+ // …and this terminal is painting its own pixels after all, so it goes back to being a
+ // budget client. Without this the node would end up with NEITHER renderer coordinated.
+ ensureWebglClient()
glyphWarn(`${id}:attach`, `node ${id} stays on the DOM renderer: xterm internals not recognised`)
return
}
@@ -1827,22 +1891,23 @@ export function TerminalNode({
// there is no per-terminal context to budget, nothing to acquire on approach and no DOM-strand
// heal to run — the whole webgl client is skipped rather than registered and left idle.
//
- // The decision is made on the MODE and the context — NOT on whether the grid registration then
- // succeeded. A node that is collapsed right now registers nothing yet but will on expand, and
- // a terminal cannot be allowed to end up holding both renderers: the glyph addon's
- // `setRenderer` silently disposes the webgl one, leaving the budget coordinator accounting for
- // a context nobody paints with and `releaseWebgl` sweeping canvases out from under a live
- // attachment. Failing the registration (unrecognised internals) leaves this terminal on
- // xterm's own DOM renderer — correct, just unbudgeted, and warned once. The mode itself is
- // re-read on every generation bump (the subscription below), never only at mount.
- const glyphMode = sharedGlyphActive() && getSharedGlyphContext() !== null
- if (glyphMode) setupGlyph()
- else webglHandle = registerWebglClient(id, { acquire: acquireWebgl, release: releaseWebgl })
-
- // The IntersectionObserver's last verdict, read by the subscription below when it hands a
- // fresh budget client this terminal's visibility. Declared here (not with the observer) so it
- // exists before anything can close over it.
- let wasVisible = false
+ // The decision is made on the MODE, not on whether the grid registration then succeeded: a
+ // node that is collapsed right now registers nothing yet but will on expand, and a terminal
+ // cannot be allowed to end up holding both renderers (see `dropWebglClient`/`ensureWebglClient`
+ // for exactly how each half of that breaks). A registration that FAILS — unrecognised
+ // internals, no readable geometry — leaves this terminal on xterm's own DOM renderer and
+ // `setupGlyph` arms the budget client from inside that failure path, so it is coordinated
+ // rather than merely warned about. The mode itself is re-read on every generation bump (the
+ // subscription below), never only at mount.
+ //
+ // The probe asks `sharedGlyphAvailable()`, NOT "does a context object exist right now". The
+ // atlas is built from a live terminal's device cell, so the context is created by the first
+ // `setupGlyph` — "none yet" is the normal state at a fresh mount and after every font change,
+ // and reading it as "not shared" would register a budget client on a terminal that attaches a
+ // grid a moment later, i.e. both renderers at once. `setupGlyph`/`teardownGlyph` own the
+ // budget client too, so the invariant holds structurally even if this probe is ever wrong.
+ if (sharedGlyphAvailable()) setupGlyph()
+ else ensureWebglClient()
// ...but the mode can also change UNDER a mounted terminal — the user flips the Settings row
// with a canvas full of live sessions — so the subscription below is UNCONDITIONAL, not part
@@ -1883,17 +1948,13 @@ export function TerminalNode({
// below schedules — after this. `setVisible` re-states what the IntersectionObserver last
// reported, because it will not fire again until visibility actually changes and a fresh
// client starts out believing it is hidden.
- // The SAME test the mount above makes — mode AND a context that exists — so a machine
- // without WebGL2 (where `getSharedGlyphContext()` is null however the setting reads) keeps
- // its budget client instead of ending up with neither renderer coordinated.
- const shared = sharedGlyphActive() && getSharedGlyphContext() !== null
- if (shared && webglHandle) {
- webglHandle.dispose()
- webglHandle = null
- } else if (!shared && !webglHandle) {
- webglHandle = registerWebglClient(id, { acquire: acquireWebgl, release: releaseWebgl })
- webglHandle.setVisible(wasVisible)
- }
+ // The SAME test the mount above makes, and it must stay non-creating HERE above all: this
+ // handler runs BEFORE React has applied a new font size to xterm, so a probe that built a
+ // context would rasterize the atlas at the OLD cell and pin every regrid to the new one.
+ // A machine without WebGL2 answers false (creation was attempted and produced nothing) and
+ // keeps its budget client instead of ending up with neither renderer coordinated.
+ if (sharedGlyphAvailable()) dropWebglClient()
+ else ensureWebglClient()
setGlyphEpoch((n) => n + 1)
} catch (err) {
console.warn(`[glyphgrid] generation handler failed for ${id} (continuing)`, err)