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): guard the atlas reset against re-entrant repacks

enes1cfc610d5feb
diff --git a/src/renderer/glyphgrid/atlas.test.ts b/src/renderer/glyphgrid/atlas.test.ts
index c2ab85d08..450c922c4 100644
--- a/src/renderer/glyphgrid/atlas.test.ts
+++ b/src/renderer/glyphgrid/atlas.test.ts
@@ -79,6 +79,20 @@ describe('GlyphAtlas', () => {
expect(new Set(slots).size).toBe(slots.length)
})
+ // packColor's own `>>> 0` note applies one layer up: `0xff << 24` is NEGATIVE in JS, so the
+ // same colour reaches this file as -16777216 from an arithmetic path and as 4278190080 from a
+ // `readCell` lane. Two spellings of one colour would mean two slots holding identical pixels —
+ // wasted page, and resets arriving twice as fast.
+ it('keys a colour by its VALUE, so a signed lane is not a second slot', () => {
+ const r = fakeRasterizer()
+ const atlas = new GlyphAtlas(r, 100)
+ const signed = 0xff << 24 // -16777216
+ const unsigned = 0xff000000 // 4278190080 — the same colour
+ const a = atlas.glyphFor(0x41, false, false, signed, signed)
+ expect(atlas.glyphFor(0x41, false, false, unsigned, unsigned)).toBe(a)
+ expect(r.calls).toHaveLength(1)
+ })
+
it('the colors ride into the rasterizer untouched (it, not the shader, paints them)', () => {
const r = fakeRasterizer()
const atlas = new GlyphAtlas(r, 100)
@@ -371,6 +385,45 @@ describe('GlyphAtlas', () => {
expect(atlas.resetCount).toBe(1) // and does NOT recurse into a second reset
})
+ // REPRODUCED BY REVIEW, and it was a stack overflow, not a slow path: a subscriber's repack
+ // that needs MORE keys than the fresh page holds used to re-enter reset() from inside reset()'s
+ // own notification loop — clearing the page the repack was half-way through writing, and
+ // recursing until the stack died (the throw then vanished into the per-subscriber try/catch,
+ // leaving a half-packed page and no error anywhere).
+ it('a subscriber that overflows the fresh page degrades — it never re-enters the reset', () => {
+ const { r, atlas } = fullAfterOne() // capacity 2 → exactly ONE real slot
+ const got: number[] = []
+ atlas.onReset(() => {
+ // Three allocations into a page that holds one. The first fits; the rest must degrade.
+ got.push(atlas.glyphFor(0x61, false, false, FG, BG))
+ got.push(atlas.glyphFor(0x62, false, false, FG, BG))
+ got.push(atlas.glyphFor(0x63, false, false, FG, BG))
+ })
+ atlas.glyphFor(0x41, false, false, FG, BG) // fills the page
+ r.calls.length = 0
+ expect(() => atlas.glyphFor(0x42, false, false, FG, BG)).not.toThrow()
+ expect(got).toEqual([1, 0, 0])
+ expect(atlas.resetCount).toBe(1) // ONE reset, not one per over-capacity request
+ // And the page holds exactly what the repack managed to write: one clear, one draw.
+ expect(r.calls).toEqual(['CLEAR', `${0x61}||${FG}|${BG}@16,2`])
+ })
+
+ it('recovers on the NEXT request — the guard is scoped to the reset, not sticky', () => {
+ const { atlas } = fullAfterOne()
+ let overflow = true
+ atlas.onReset(() => {
+ if (!overflow) return
+ overflow = false
+ atlas.glyphFor(0x61, false, false, FG, BG) // fills the fresh page
+ atlas.glyphFor(0x62, false, false, FG, BG) // degrades to blank
+ })
+ atlas.glyphFor(0x41, false, false, FG, BG)
+ expect(atlas.glyphFor(0x42, false, false, FG, BG)).toBe(0) // repack took the only slot
+ // A later request, outside any reset, still gets the normal reset-then-allocate treatment.
+ expect(atlas.glyphFor(0x63, false, false, FG, BG)).toBe(1)
+ expect(atlas.resetCount).toBe(2)
+ })
+
it('every subscriber is called, and each one can be disposed independently', () => {
const { atlas } = fullAfterOne()
const hits: string[] = []
diff --git a/src/renderer/glyphgrid/atlas.ts b/src/renderer/glyphgrid/atlas.ts
index 55beee6c2..3363863bb 100644
--- a/src/renderer/glyphgrid/atlas.ts
+++ b/src/renderer/glyphgrid/atlas.ts
@@ -99,6 +99,8 @@ export class GlyphAtlas {
private dirtyFlag = false
private resets = 0
private resetSubs = new Set<() => void>()
+ /** True only while `reset()` is notifying subscribers. See the guard in `glyphFor`. */
+ private inReset = false
constructor(
private rasterizer: GlyphRasterizer,
@@ -193,10 +195,19 @@ export class GlyphAtlas {
* immediately packs into the fresh page and can never write a lane pointing at a slot that no
* longer holds what it held.
*
- * A subscriber MAY call back into `glyphFor` (that is what a repack is), and doing so is safe:
- * the reset path never recurses, and an allocation that no longer fits the freshly-filled page
- * degrades to the blank slot instead of resetting again. It is still the wrong shape for the
- * addon — a full repack inside someone else's pack loop — which is why T4 defers it.
+ * A subscriber MAY call back into `glyphFor` — that is what a repack is — and the reset path is
+ * re-entrancy-GUARDED, not merely re-entrancy-safe: while subscribers are running, an allocation
+ * that would trigger a reset returns the BLANK slot instead (`inReset`). A repack needing more
+ * keys than the fresh page holds is a real case, and letting it reset again would clear the page
+ * that same repack is half-way through writing — measured, on a page with one usable slot and a
+ * subscriber asking for three, as unbounded recursion into a stack overflow that the
+ * per-subscriber catch below then SWALLOWED, leaving a half-packed page and no error anywhere.
+ * Degrading instead costs those cells one frame of blank: the next repack round re-requests them,
+ * and a page genuinely too small for the canvas is the LRU escalation's problem, not a
+ * recursion's.
+ *
+ * A full repack inside someone else's pack loop is still the wrong SHAPE for the addon — which
+ * is why T4 defers it to the redraw path rather than running it here.
*/
onReset(cb: () => void): GlyphAtlasSubscription {
this.resetSubs.add(cb)
@@ -219,25 +230,42 @@ export class GlyphAtlas {
private reset(): void {
this.slots.clear()
this.nextSlot = 1
- this.resets++
this.rasterizer.clearPage()
+ // Counted only once the page is actually blank: `resetCount` is read as "how many times this
+ // atlas started over", and a clearPage() that threw must not leave a count claiming it did.
+ this.resets++
this.dirtyFlag = true
- // Iterate a COPY: a subscriber is allowed to dispose itself (or another) from inside its own
- // callback, and mutating the live set mid-iteration would skip the next subscriber.
- for (const cb of [...this.resetSubs]) {
- try {
- cb()
- } catch (err) {
- // One broken repack must not cost the other subscribers their notification — nor the
- // frame. The page is already consistent by the time we get here.
- console.warn('[glyphgrid] atlas onReset subscriber threw:', err)
+ // NOTE: nothing subscribes yet — T3+T4 wire the addon repack; until then a reset leaves stale
+ // lanes rendering WRONG glyphs (worse than the old blank degrade). Do not run a device round
+ // before T4.
+ this.inReset = true
+ try {
+ // Iterate a COPY: a subscriber is allowed to dispose itself (or another) from inside its own
+ // callback, and mutating the live set mid-iteration would skip the next subscriber.
+ for (const cb of [...this.resetSubs]) {
+ try {
+ cb()
+ } catch (err) {
+ // One broken repack must not cost the other subscribers their notification — nor the
+ // frame. The page is already consistent by the time we get here.
+ console.warn('[glyphgrid] atlas onReset subscriber threw:', err)
+ }
}
+ } finally {
+ // `finally`, so a throw that escapes the loop (it cannot today — every callback is caught —
+ // but a future edit to that catch would) can never leave the atlas permanently unable to
+ // reset again.
+ this.inReset = false
}
}
glyphFor(code: number, bold: boolean, italic: boolean, fg: number, bg: number): number {
if (code === 0x20 || code === 0) return 0
- const key = `${code}|${bold ? 1 : 0}${italic ? 1 : 0}|${fg}|${bg}`
+ // `>>> 0` on both lanes: `0xff << 24` is NEGATIVE in JS (packColor carries the same note), so
+ // one colour can arrive as -16777216 from an arithmetic path and as 4278190080 off a cell
+ // lane. Keying the two spellings separately would put identical pixels in two slots — wasted
+ // page, and resets arriving twice as fast.
+ const key = `${code}|${bold ? 1 : 0}${italic ? 1 : 0}|${fg >>> 0}|${bg >>> 0}`
const hit = this.slots.get(key)
if (hit !== undefined) return hit
if (this.nextSlot >= this.capacity) {
@@ -245,9 +273,15 @@ export class GlyphAtlas {
// included) can never satisfy this request: resetting would blank an empty page and notify
// every subscriber on EVERY glyph, forever. Degrade to blank instead.
if (this.capacity <= 1) return 0
+ // RE-ENTRANCY GUARD: we are inside reset()'s notification, i.e. a subscriber's repack, and
+ // it has already refilled the fresh page. Resetting again would clear the very page that
+ // repack is writing and recurse without bound (measured: stack overflow, swallowed by the
+ // per-subscriber catch, page left half-packed). Degrade instead — this cell is blank for one
+ // frame and the NEXT repack round re-requests it. See `onReset`.
+ if (this.inReset) return 0
this.reset()
- // A subscriber may have repacked enough rows to fill the fresh page again. Never recurse —
- // one reset per request — and degrade to blank rather than allocate off the end of the page.
+ // A subscriber may have repacked enough rows to fill the fresh page again. Degrade to blank
+ // rather than allocate off the end of the page.
if (this.nextSlot >= this.capacity) return 0
}
const slot = this.nextSlot++
@@ -268,9 +302,13 @@ export class GlyphAtlas {
}
/** The uv rect of a slot: the ORIGIN is the ink origin (pitch cell + gutter), the SIZE is the
- * exact cell — the three numbers are not interchangeable (see `strideX` and `GUTTER_PX`), and
- * the shader must derive its uv the same way (`uAtlasStride` for the pitch, the gutter for the
- * origin offset, `uAtlasCell` for the extent). */
+ * exact cell — the three numbers are not interchangeable (see `strideX` and `GUTTER_PX`).
+ *
+ * The shader has to derive the same rect (`uAtlasStride` for the pitch, the gutter for the
+ * origin offset, `uAtlasCell` for the extent). PHASE 1c INTERIM: it does NOT yet — gl-webgl2's
+ * VERT is still missing the gutter term, so every glyph samples GUTTER_PX texels off until T3
+ * adds it. This rect, and the uv-tie test that transcribes it, are the CPU-side truth T3
+ * aligns to. */
slotRect(slot: number): { u0: number; v0: number; u1: number; v1: number } {
// A degenerate page has no sampleable area at all: return the ZERO rect rather than let the
// division produce NaN, which the shader would turn into undefined texture reads.
diff --git a/src/renderer/glyphgrid/gl-webgl2.ts b/src/renderer/glyphgrid/gl-webgl2.ts
index eafdf0af3..7d6189999 100644
--- a/src/renderer/glyphgrid/gl-webgl2.ts
+++ b/src/renderer/glyphgrid/gl-webgl2.ts
@@ -28,6 +28,10 @@ void main() {
vec2 ndc = vec2(screen.x / uView.x * 2.0 - 1.0, 1.0 - screen.y / uView.y * 2.0);
gl_Position = vec4(ndc, 0.0, 1.0);
float slot = float(aCell.x);
+ // PHASE 1c interim: uv lacks the gutter term — T3 adds uAtlasGutter; glyphs sample 2 texels off
+ // until then. The atlas already lays every slot out with GUTTER_PX of ink-free margin inside its
+ // pitch cell (atlas.ts), so this origin is one gutter short on both axes; the uv-tie test in
+ // atlas.test.ts transcribes the derivation T3 has to land here.
vec2 slotOrigin = vec2(mod(slot, uAtlasCols), floor(slot / uAtlasCols)) * uAtlasStride;
vUv = slotOrigin + unit * uAtlasCell;
vCell = aCell;
diff --git a/src/renderer/glyphgrid/harness/GlyphGridHarness.tsx b/src/renderer/glyphgrid/harness/GlyphGridHarness.tsx
index 427f10e51..8553ba7c9 100644
--- a/src/renderer/glyphgrid/harness/GlyphGridHarness.tsx
+++ b/src/renderer/glyphgrid/harness/GlyphGridHarness.tsx
@@ -79,6 +79,28 @@ const OVERLAP_BG = [
]
/** Default grid tint — the 40 disjoint grids' plate and cell background. */
const BASE_BG = packColor(20, 20, 24, 255)
+/**
+ * The foreground palette the synthetic feed draws from — FOUR entries, and the count is
+ * load-bearing.
+ *
+ * The atlas is keyed by colour (Phase 1c), so the key space this harness generates is
+ * `codes x bold x fg x bg` = 90 x 2 x 4 x 4 = 2880, against a capacity of 3588 slots
+ * (1024px page, 13x22 pitch). A random fg per cell — what this used to do — puts the key space at
+ * ~54k and the page then RESETS several times a second: 30+ full-page clears per second, and,
+ * until T4 wires the repack, every already-uploaded lane pointing at a recycled slot, i.e. a
+ * screen of permanently wrong glyphs. That is a broken harness, not a stress test.
+ */
+const FG_PALETTE = [
+ packColor(200, 200, 160, 255),
+ packColor(160, 210, 200, 255),
+ packColor(220, 170, 170, 255),
+ packColor(180, 200, 240, 255)
+]
+/** ATLAS RESET STRESS. Flip to true to give every cell a random foreground, which blows the key
+ * space past the page's capacity and exercises reset-on-full continuously. Deliberately a manual
+ * switch: with it on the glyphs on screen are expected to be WRONG (no repack subscriber yet), so
+ * it is a test of the reset MACHINERY, never of rendering quality. */
+const ATLAS_RESET_STRESS = false
/** A little air around the fitted layout, so the outermost grids are visibly INSIDE the frame
* rather than clipping its edge — the tester has to be able to count them. */
const FIT_MARGIN = 0.92
@@ -229,8 +251,11 @@ export function GlyphGridHarness() {
// gets a valid code point.
const code = 0x21 + Math.floor(Math.random() * 90)
// Resolved BEFORE the atlas request: the atlas is keyed by colour, so the slot and the
- // lane have to be asked for with the same pair.
- const fg = packColor(180 + Math.floor(Math.random() * 75), 200, 160, 255)
+ // lane have to be asked for with the same pair — and from a BOUNDED palette, or the key
+ // space outgrows the page (see FG_PALETTE / ATLAS_RESET_STRESS).
+ const fg = ATLAS_RESET_STRESS
+ ? packColor(180 + Math.floor(Math.random() * 75), 200, 160, 255)
+ : FG_PALETTE[Math.floor(Math.random() * FG_PALETTE.length)]
writeCell(
row,
c,