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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(glyphgrid): engine — registry, damage, z-order, idle-quiet frames
enes69ed63899e3c
diff --git a/src/renderer/glyphgrid/atlas.ts b/src/renderer/glyphgrid/atlas.tsindex ae7dbd6c6..5f8a25aec 100644--- a/src/renderer/glyphgrid/atlas.ts+++ b/src/renderer/glyphgrid/atlas.ts@@ -16,9 +16,23 @@ export class GlyphAtlas {constructor(private rasterizer: GlyphRasterizer,- private sizePx = 1024+ private pageSizePx = 1024) {}+ /** The three metrics `GlyphGL.uploadAtlas` needs to map a slot index to texels. They are+ * passthroughs on purpose: the page size is the atlas's own, the cell size belongs to the+ * rasterizer that filled it, and the engine must never have to know a second source for+ * either — a mismatch here shifts every glyph by a fraction of a cell. */+ get sizePx(): number {+ return this.pageSizePx+ }+ get cellW(): number {+ return this.rasterizer.cellW+ }+ get cellH(): number {+ return this.rasterizer.cellH+ }+get capacity(): number {const cols = Math.floor(this.sizePx / this.rasterizer.cellW)const rows = Math.floor(this.sizePx / this.rasterizer.cellH)diff --git a/src/renderer/glyphgrid/engine.test.ts b/src/renderer/glyphgrid/engine.test.tsnew file mode 100644index 000000000..5f72456be--- /dev/null+++ b/src/renderer/glyphgrid/engine.test.ts@@ -0,0 +1,246 @@+import { describe, expect, it, vi } from 'vitest'+import { GlyphAtlas } from './atlas'+import { CELL_STRIDE } from './cells'+import { GlyphGridEngine, type GridSpec } from './engine'+import type { GlyphGL, GridDraw } from './gl'++function fakeGL(): GlyphGL & { drawn: string[] } {+ const drawn: string[] = []+ return {+ drawn,+ resize: vi.fn(),+ // Recorded in `drawn` too: the atlas upload MUST land before any drawGrid of the same+ // frame, or the shader samples an incomplete texture (solid blocks).+ uploadAtlas: vi.fn(() => {+ drawn.push('ATLAS')+ }),+ beginFrame: () => drawn.push('BEGIN'),+ drawGrid: (g: GridDraw & { id?: string }) => drawn.push(`grid@${g.originX},${g.originY}`),+ endFrame: () => drawn.push('END'),+ dispose: vi.fn()+ }+}++const atlas = () =>+ new GlyphAtlas({ cellW: 10, cellH: 20, source: null, draw: () => undefined }, 100)++/** An atlas whose rasterizer already has a texture source, so the engine can upload it. */+function loadedAtlas(sizePx = 512, cellW = 7, cellH = 15) {+ const source = {} as unknown as TexImageSource+ return {+ source,+ atlas: new GlyphAtlas({ cellW, cellH, source, draw: () => undefined }, sizePx)+ }+}++const spec = (id: string, x: number, z = 0): GridSpec => ({+ id,+ cols: 2,+ rows: 1,+ cellW: 10,+ cellH: 20,+ originX: x,+ originY: 0,+ z,+ bgColor: 0+})++describe('GlyphGridEngine', () => {+ it('an idle engine draws nothing; a dirty grid draws exactly one frame', () => {+ 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 dirties+ expect(e.frame()).toBe(false) // idle → no draw+ h.updateRow(0, new Uint32Array(2 * CELL_STRIDE))+ expect(e.frame()).toBe(true)+ expect(e.frame()).toBe(false)+ })++ it('camera movement dirties the frame', () => {+ const e = new GlyphGridEngine(fakeGL(), atlas())+ e.setViewport(800, 600, 1)+ e.register(spec('a', 0))+ e.frame()+ e.setCamera({ x: 1, y: 0, zoom: 1 })+ expect(e.frame()).toBe(true)+ })++ it('an unchanged camera does not dirty the frame', () => {+ const e = new GlyphGridEngine(fakeGL(), atlas())+ e.setViewport(800, 600, 1)+ e.setCamera({ x: 3, y: 4, zoom: 2 })+ e.register(spec('a', 0))+ e.frame()+ e.setCamera({ x: 3, y: 4, zoom: 2 })+ expect(e.frame()).toBe(false)+ })++ it('culls grids outside the visible world rect', () => {+ const e = new GlyphGridEngine(fakeGL(), atlas())+ e.setViewport(100, 100, 1)+ e.setCamera({ x: 0, y: 0, zoom: 1 })+ e.register(spec('in', 0))+ e.register(spec('out', 5000))+ expect(e.drawOrder()).toEqual(['in'])+ })++ it('draws in z order ascending, ties by registration order', () => {+ const e = new GlyphGridEngine(fakeGL(), atlas())+ e.setViewport(800, 600, 1)+ e.setCamera({ x: 0, y: 0, zoom: 1 })+ e.register(spec('bottom', 0, 0))+ e.register(spec('top', 10, 5))+ e.register(spec('mid', 20, 2))+ expect(e.drawOrder()).toEqual(['bottom', 'mid', 'top'])+ })++ it('frame() submits the visible grids in draw order, between begin and end', () => {+ 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('bottom', 0, 0))+ e.register(spec('top', 10, 5))+ e.register(spec('offscreen', 5000, 1))+ e.frame()+ expect(gl.drawn).toEqual(['BEGIN', 'grid@0,0', 'grid@10,0', 'END'])+ })++ it('updateRow rejects a wrong-length row', () => {+ const e = new GlyphGridEngine(fakeGL(), atlas())+ const h = e.register(spec('a', 0))+ expect(() => h.updateRow(0, new Uint32Array(3))).toThrow(/row length/)+ })++ it('updateRow rejects an out-of-range row', () => {+ const e = new GlyphGridEngine(fakeGL(), atlas())+ const h = e.register(spec('a', 0)) // rows: 1+ expect(() => h.updateRow(1, new Uint32Array(2 * CELL_STRIDE))).toThrow(/row 1/)+ })++ it('updateRow writes row-major: cellIndex = row * cols + col', () => {+ 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), rows: 3 })+ const row = new Uint32Array(2 * CELL_STRIDE)+ row[0] = 0xaa // row 1, col 0 → cellIndex 2+ row[CELL_STRIDE] = 0xbb // row 1, col 1 → cellIndex 3+ h.updateRow(1, row)+ let submitted: Uint32Array | null = null+ gl.drawGrid = (g) => {+ submitted = g.cells+ }+ e.frame()+ const cells = submitted as unknown as Uint32Array+ expect(cells[2 * CELL_STRIDE]).toBe(0xaa)+ expect(cells[3 * CELL_STRIDE]).toBe(0xbb)+ })++ it('setOrigin / setZ dirty only on a real change', () => {+ const e = new GlyphGridEngine(fakeGL(), atlas())+ e.setViewport(800, 600, 1)+ e.setCamera({ x: 0, y: 0, zoom: 1 })+ const h = e.register(spec('a', 0, 1))+ e.frame()+ h.setOrigin(0, 0)+ h.setZ(1)+ expect(e.frame()).toBe(false)+ h.setOrigin(40, 0)+ expect(e.frame()).toBe(true)+ h.setZ(2)+ expect(e.frame()).toBe(true)+ })++ it('resize reshapes the cell buffer and dirties', () => {+ const e = new GlyphGridEngine(fakeGL(), atlas())+ e.setViewport(800, 600, 1)+ e.setCamera({ x: 0, y: 0, zoom: 1 })+ const h = e.register(spec('a', 0))+ e.frame()+ h.resize(5, 2)+ expect(e.frame()).toBe(true)+ // The new shape is what updateRow validates against now.+ expect(() => h.updateRow(1, new Uint32Array(5 * CELL_STRIDE))).not.toThrow()+ expect(() => h.updateRow(0, new Uint32Array(2 * CELL_STRIDE))).toThrow(/row length/)+ })++ it('dispose removes the grid from the draw order', () => {+ const e = new GlyphGridEngine(fakeGL(), atlas())+ e.setViewport(800, 600, 1)+ e.setCamera({ x: 0, y: 0, zoom: 1 })+ const h = e.register(spec('a', 0))+ h.dispose()+ expect(e.drawOrder()).toEqual([])+ })++ it('refuses a duplicate id instead of silently replacing a live grid', () => {+ const e = new GlyphGridEngine(fakeGL(), atlas())+ e.register(spec('a', 0))+ expect(() => e.register(spec('a', 10))).toThrow(/already registered/)+ })++ it('uploads the atlas with the rasterizer metrics before any drawGrid', () => {+ const gl = fakeGL()+ const { atlas: a, source } = loadedAtlas(512, 7, 15)+ 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)+ expect(gl.uploadAtlas).toHaveBeenCalledWith(source, 512, 7, 15)+ expect(gl.drawn.indexOf('ATLAS')).toBeLessThan(gl.drawn.indexOf('grid@0,0'))+ expect(a.dirty).toBe(false)+ })++ it('uploads a never-uploaded atlas even when it is not dirty, and only once', () => {+ const gl = fakeGL()+ const { atlas: a } = loadedAtlas()+ a.glyphFor(0x41, false, false)+ a.clearDirty() // rasterized elsewhere: has content, reports clean+ const e = new GlyphGridEngine(gl, a)+ e.setViewport(800, 600, 1)+ e.setCamera({ x: 0, y: 0, zoom: 1 })+ e.register(spec('a', 0))+ expect(e.frame()).toBe(true)+ expect(gl.uploadAtlas).toHaveBeenCalledTimes(1)+ e.setCamera({ x: 1, y: 0, zoom: 1 })+ expect(e.frame()).toBe(true)+ expect(gl.uploadAtlas).toHaveBeenCalledTimes(1) // clean + already uploaded → no re-upload+ })++ it('draws a frame as soon as a pending atlas upload appears, and never uploads a null source', () => {+ const gl = fakeGL()+ const { atlas: a } = loadedAtlas()+ const e = new GlyphGridEngine(gl, a)+ e.setViewport(800, 600, 1)+ e.setCamera({ x: 0, y: 0, zoom: 1 })+ expect(e.frame()).toBe(true) // pending upload counts as damage+ expect(gl.uploadAtlas).toHaveBeenCalledTimes(1)+ expect(e.frame()).toBe(false)++ const gl2 = fakeGL()+ const e2 = new GlyphGridEngine(gl2, atlas()) // source: null+ e2.setViewport(800, 600, 1)+ e2.setCamera({ x: 0, y: 0, zoom: 1 })+ e2.register(spec('a', 0))+ e2.frame()+ expect(gl2.uploadAtlas).not.toHaveBeenCalled()+ })++ it('setViewport sizes the GL surface and dirties', () => {+ const gl = fakeGL()+ const e = new GlyphGridEngine(gl, atlas())+ e.setCamera({ x: 0, y: 0, zoom: 1 })+ e.register(spec('a', 0))+ e.frame()+ e.setViewport(640, 480, 2)+ expect(gl.resize).toHaveBeenCalledWith(640, 480, 2)+ expect(e.frame()).toBe(true)+ })+})diff --git a/src/renderer/glyphgrid/engine.ts b/src/renderer/glyphgrid/engine.tsnew file mode 100644index 000000000..7f1551d0a--- /dev/null+++ b/src/renderer/glyphgrid/engine.ts@@ -0,0 +1,191 @@+import type { GlyphAtlas } from './atlas'+import { rectsIntersect, visibleWorldRect, type Camera, type Rect } from './camera'+import { CELL_STRIDE } from './cells'+import type { GlyphGL } from './gl'++/** One registered grid: a cols×rows character matrix placed in world space. `z` is the node+ * stacking order — grids are drawn ASCENDING (painter's algorithm), so a higher z lands on+ * top. */+export interface GridSpec {+ id: string+ cols: number+ rows: number+ /** cell size in world units (CSS px at zoom 1) */+ cellW: number+ cellH: number+ /** world position of the grid's top-left corner */+ originX: number+ originY: number+ z: number+ bgColor: number+}++export interface GridHandle {+ /**+ * Replace one row of cells. `cells` is exactly `cols * CELL_STRIDE` lanes laid out per+ * cells.ts ([glyph, fg, bg, flags] per cell) and is COPIED, so the caller may reuse its+ * scratch buffer. Marks the engine dirty.+ *+ * The glyph lane must be a slot obtained from `GlyphAtlas.glyphFor(code, bold, italic)` —+ * never a raw code point. The atlas owns the slot space (0 is the permanently blank slot,+ * and an unrasterized code degrades to it), so a code point written here would sample an+ * arbitrary neighbouring glyph.+ */+ updateRow(row: number, cells: Uint32Array): void+ setOrigin(x: number, y: number): void+ setZ(z: number): void+ resize(cols: number, rows: number): void+ dispose(): void+}++interface Grid extends GridSpec {+ /** Row-major: the cell at (row, col) starts at lane `(row * cols + col) * CELL_STRIDE`.+ * This is the layout the instanced shader binds — see gl.ts / gl-webgl2.ts. */+ cells: Uint32Array+ seq: number // registration order — the z tie-break+}++/**+ * The renderer's brain: a registry of grids, damage tracking, culling and z-ordered submission.+ *+ * Two contracts the rest of the engine depends on:+ * - **Idle frames cost nothing.** `frame()` draws only when something actually changed and+ * reports whether it drew, so the rAF driver (and the tests) can prove an untouched canvas+ * issues zero GL calls.+ * - **The atlas is uploaded before the first `drawGrid` of a frame.** A draw that samples a+ * texture the glyphs have not been uploaded into paints solid blocks; the engine is the only+ * place that sees both, so it is the enforcer.+ */+export class GlyphGridEngine {+ private grids = new Map<string, Grid>()+ private camera: Camera = { x: 0, y: 0, zoom: 1 }+ private viewW = 1+ private viewH = 1+ private dirty = false+ private seq = 0+ /** False until an atlas source has actually reached the GPU — see `atlasUploadPending`. */+ private atlasUploaded = false++ constructor(+ private gl: GlyphGL,+ private atlas: GlyphAtlas+ ) {}++ register(spec: GridSpec): GridHandle {+ if (this.grids.has(spec.id))+ throw new Error(`glyphgrid: grid "${spec.id}" already registered — dispose it first`)+ const grid: Grid = {+ ...spec,+ cells: new Uint32Array(spec.cols * spec.rows * CELL_STRIDE),+ seq: this.seq+++ }+ this.grids.set(spec.id, grid)+ this.dirty = true+ const engine = this+ return {+ updateRow(row, cells) {+ if (row < 0 || row >= grid.rows)+ throw new Error(`glyphgrid: row ${row} out of range (rows=${grid.rows})`)+ if (cells.length !== grid.cols * CELL_STRIDE)+ throw new Error(`glyphgrid: row length ${cells.length} != ${grid.cols * CELL_STRIDE}`)+ grid.cells.set(cells, row * grid.cols * CELL_STRIDE)+ engine.dirty = true+ },+ setOrigin(x, y) {+ if (grid.originX === x && grid.originY === y) return+ grid.originX = x+ grid.originY = y+ engine.dirty = true+ },+ setZ(z) {+ if (grid.z === z) return+ grid.z = z+ engine.dirty = true+ },+ resize(cols, rows) {+ if (grid.cols === cols && grid.rows === rows) return+ // Content is re-fed by the owner after a resize; carrying old cells over a shape+ // change would misalign every row.+ grid.cols = cols+ grid.rows = rows+ grid.cells = new Uint32Array(cols * rows * CELL_STRIDE)+ engine.dirty = true+ },+ dispose() {+ // Identity-checked: only drop the map entry if it is still THIS grid, so a stale+ // handle can never evict a grid that re-registered under the same id.+ if (engine.grids.get(grid.id) !== grid) return+ engine.grids.delete(grid.id)+ engine.dirty = true+ }+ }+ }++ setCamera(cam: Camera): void {+ if (cam.x === this.camera.x && cam.y === this.camera.y && cam.zoom === this.camera.zoom) return+ this.camera = { ...cam }+ this.dirty = true+ }++ setViewport(w: number, h: number, dpr: number): void {+ this.viewW = w+ this.viewH = h+ this.gl.resize(w, h, dpr)+ this.dirty = true+ }++ /** Visible grid ids in draw order (z ascending, ties by registration order). Pure. */+ drawOrder(): string[] {+ const visible: Rect = visibleWorldRect(this.camera, this.viewW, this.viewH)+ return [...this.grids.values()]+ .filter((g) =>+ rectsIntersect(visible, {+ x: g.originX,+ y: g.originY,+ w: g.cols * g.cellW,+ h: g.rows * g.cellH+ })+ )+ .sort((a, b) => a.z - b.z || a.seq - b.seq)+ .map((g) => g.id)+ }++ /** True while the atlas holds pixels the GPU has not seen. `!atlasUploaded` is NOT covered+ * by `atlas.dirty`: an atlas populated before the engine existed (or by another consumer+ * that already called clearDirty) reports clean while the texture is still empty — that+ * atlas must reach the GPU on the first frame, and the pending upload is itself damage, or+ * a canvas that goes idle right after would sit on solid blocks until the next input. */+ private atlasUploadPending(): boolean {+ return !!this.atlas.source && (this.atlas.dirty || !this.atlasUploaded)+ }++ /** Draw ONE frame if anything is dirty; returns whether it drew. */+ frame(): boolean {+ const uploadAtlas = this.atlasUploadPending()+ if (!this.dirty && !uploadAtlas) return false+ this.dirty = false+ if (uploadAtlas && this.atlas.source) {+ // BEFORE any drawGrid, always: see the class contract.+ this.gl.uploadAtlas(this.atlas.source, this.atlas.sizePx, this.atlas.cellW, this.atlas.cellH)+ this.atlas.clearDirty()+ this.atlasUploaded = true+ }+ this.gl.beginFrame(this.camera)+ for (const id of this.drawOrder()) {+ const g = this.grids.get(id)+ if (!g) continue+ this.gl.drawGrid({+ cells: g.cells,+ cols: g.cols,+ rows: g.rows,+ cellW: g.cellW,+ cellH: g.cellH,+ originX: g.originX,+ originY: g.originY,+ bgColor: g.bgColor+ })+ }+ this.gl.endFrame()+ return true+ }+}