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): renderer addon core + xterm attach shell

enes4bb9bd66ecf9
diff --git a/src/renderer/glyphgrid/addon.test.ts b/src/renderer/glyphgrid/addon.test.ts
new file mode 100644
index 000000000..f326f0551
--- /dev/null
+++ b/src/renderer/glyphgrid/addon.test.ts
@@ -0,0 +1,404 @@
+import { describe, expect, it } from 'vitest'
+import type { GlyphAtlas } from './atlas'
+import { CELL_STRIDE, FLAG_CURSOR, FLAG_SELECTED, packColor, readCell } from './cells'
+import type { GridHandle } from './engine'
+import { GlyphGridRendererAddonCore, type TermInternals } from './addon'
+import type { CellView, ThemeLanes } from './feed'
+
+const THEME: ThemeLanes = {
+ fg: packColor(0xd0, 0xd1, 0xd2, 0xff),
+ bg: packColor(0x10, 0x11, 0x12, 0xff),
+ ansi: Array.from({ length: 256 }, (_, i) => packColor(i, 0x80, 0xff - i, 0xff)),
+ cursorFg: packColor(0x01, 0x02, 0x03, 0xff),
+ cursorBg: packColor(0xfa, 0xfb, 0xfc, 0xff),
+ selectionBg: packColor(0x30, 0x50, 0x80, 0xff)
+}
+
+/** A cell whose code point encodes the ABSOLUTE buffer row it came from, so a packed row can be
+ * traced back to the buffer row that produced it — which is the whole point of the mapping
+ * tests (a viewportY off-by-one is otherwise invisible). */
+function rowCodedCell(absRow: number, col: number): CellView {
+ const code = 0x100 + absRow * 16 + col
+ return {
+ getChars: () => String.fromCodePoint(code),
+ getCode: () => code,
+ getWidth: () => 1,
+ isBold: () => 0,
+ isItalic: () => 0,
+ isUnderline: () => 0,
+ isInverse: () => 0,
+ isDim: () => 0,
+ isFgDefault: () => true,
+ isFgPalette: () => false,
+ isFgRGB: () => false,
+ isBgDefault: () => true,
+ isBgPalette: () => false,
+ isBgRGB: () => false,
+ getFgColor: () => 0,
+ getBgColor: () => 0
+ }
+}
+
+interface RecordedRow {
+ row: number
+ /** Copy — the core reuses ONE row buffer, so keeping the live reference would record the last
+ * frame N times. */
+ cells: Uint32Array
+ /** The buffer INSTANCE handed to updateRow, kept only to assert the reuse contract. */
+ buf: Uint32Array
+}
+
+function recordingHandle(): GridHandle & {
+ rows: RecordedRow[]
+ log: string[]
+ resizes: Array<[number, number]>
+} {
+ const rows: RecordedRow[] = []
+ const log: string[] = []
+ const resizes: Array<[number, number]> = []
+ return {
+ rows,
+ log,
+ resizes,
+ updateRow(row, cells) {
+ log.push(`updateRow:${row}`)
+ rows.push({ row, cells: cells.slice(), buf: cells })
+ },
+ setOrigin() {},
+ setZ() {},
+ resize(cols, r) {
+ log.push(`resize:${cols}x${r}`)
+ resizes.push([cols, r])
+ },
+ dispose() {
+ log.push('dispose')
+ }
+ }
+}
+
+function recordingAtlas(): Pick<GlyphAtlas, 'glyphFor'> {
+ // Identity-ish: the slot IS derived from the code point, so a packed glyph lane names the cell
+ // it came from without a second bookkeeping structure.
+ return { glyphFor: (code) => code }
+}
+
+interface FakeTermOpts {
+ cols?: number
+ rows?: number
+ viewportY?: number
+ baseY?: number
+ cursorX?: number
+ cursorY?: number
+ cursorVisible?: boolean
+ focus?: boolean
+}
+
+function fakeTerm(o: FakeTermOpts = {}): TermInternals & { state: Required<FakeTermOpts> } {
+ const state: Required<FakeTermOpts> = {
+ cols: o.cols ?? 4,
+ rows: o.rows ?? 6,
+ viewportY: o.viewportY ?? 0,
+ baseY: o.baseY ?? 0,
+ cursorX: o.cursorX ?? 0,
+ cursorY: o.cursorY ?? 0,
+ cursorVisible: o.cursorVisible ?? true,
+ focus: o.focus ?? true
+ }
+ const workCell = rowCodedCell(-1, -1)
+ return {
+ state,
+ cols: () => state.cols,
+ rows: () => state.rows,
+ viewportY: () => state.viewportY,
+ baseY: () => state.baseY,
+ cursorX: () => state.cursorX,
+ cursorY: () => state.cursorY,
+ cursorVisible: () => state.cursorVisible,
+ readCell: (absRow, col) => rowCodedCell(absRow, col),
+ makeWorkCell: () => workCell,
+ deviceMetrics: () => ({ charW: 16, charH: 34, cellW: 16, cellH: 34 }),
+ dpr: () => 2,
+ theme: () => THEME,
+ hasFocus: () => state.focus
+ }
+}
+
+function make(o: FakeTermOpts = {}): {
+ core: GlyphGridRendererAddonCore
+ term: ReturnType<typeof fakeTerm>
+ handle: ReturnType<typeof recordingHandle>
+} {
+ const term = fakeTerm(o)
+ const handle = recordingHandle()
+ const core = new GlyphGridRendererAddonCore(term, handle, recordingAtlas())
+ return { core, term, handle }
+}
+
+/** The glyph lane of a packed row decodes back to (absRow, col) — see rowCodedCell. */
+function decodeRow(cells: Uint32Array, cols: number): Array<{ absRow: number; col: number }> {
+ const out: Array<{ absRow: number; col: number }> = []
+ for (let c = 0; c < cols; c++) {
+ const g = readCell(cells, c).glyph
+ out.push({ absRow: Math.floor((g - 0x100) / 16), col: (g - 0x100) % 16 })
+ }
+ return out
+}
+
+describe('GlyphGridRendererAddonCore.renderRows', () => {
+ it('packs exactly the requested viewport rows, mapped through viewportY', () => {
+ const { core, handle } = make({ viewportY: 0 })
+ core.renderRows(2, 4)
+ expect(handle.rows.map((r) => r.row)).toEqual([2, 3, 4])
+ for (const rec of handle.rows) {
+ // Every column of the row came from the SAME absolute buffer row, and that row is the
+ // viewport row (viewportY = 0).
+ expect(decodeRow(rec.cells, 4).map((d) => d.absRow)).toEqual([rec.row, rec.row, rec.row, rec.row])
+ expect(decodeRow(rec.cells, 4).map((d) => d.col)).toEqual([0, 1, 2, 3])
+ }
+ })
+
+ it('maps a SCROLLED buffer: viewport row r reads absolute row viewportY + r', () => {
+ const { core, handle } = make({ viewportY: 100, baseY: 140 })
+ core.renderRows(0, 1)
+ expect(handle.rows.map((r) => r.row)).toEqual([0, 1])
+ expect(decodeRow(handle.rows[0].cells, 4)[0].absRow).toBe(100)
+ expect(decodeRow(handle.rows[1].cells, 4)[0].absRow).toBe(101)
+ })
+
+ it('clamps the requested range to the grid', () => {
+ const { core, handle } = make({ rows: 3 })
+ core.renderRows(-5, 99)
+ expect(handle.rows.map((r) => r.row)).toEqual([0, 1, 2])
+ })
+
+ it('reuses ONE row buffer across rows (allocation-free hot path)', () => {
+ const { core, handle } = make()
+ core.renderRows(0, 3)
+ const first = handle.rows[0].buf
+ for (const rec of handle.rows) expect(rec.buf).toBe(first)
+ expect(first.length).toBe(4 * CELL_STRIDE)
+ })
+
+ it('paints the block cursor on the cursor row, converted from base-relative coords', () => {
+ // Cursor sits at buffer row baseY + cursorY = 140 + 3 = 143; the viewport starts at 140, so
+ // it belongs on viewport row 3.
+ const { core, handle } = make({ viewportY: 140, baseY: 140, cursorY: 3, cursorX: 2 })
+ core.renderRows(0, 5)
+ const flagsOn = (row: number, col: number): number =>
+ readCell(handle.rows.find((r) => r.row === row)!.cells, col).flags & FLAG_CURSOR
+ expect(flagsOn(3, 2)).toBe(FLAG_CURSOR)
+ expect(flagsOn(3, 1)).toBe(0)
+ expect(flagsOn(2, 2)).toBe(0)
+ })
+
+ it('clamps a deferred-wrap cursor (x === cols) onto the last column', () => {
+ const { core, handle } = make({ cols: 4, rows: 2, cursorX: 4, cursorY: 0 })
+ core.renderRows(0, 1)
+ const row0 = handle.rows.find((r) => r.row === 0)!
+ expect(readCell(row0.cells, 3).flags & FLAG_CURSOR).toBe(FLAG_CURSOR)
+ expect(readCell(row0.cells, 2).flags & FLAG_CURSOR).toBe(0)
+ })
+
+ it('paints NO cursor while the cursor is hidden or the terminal is blurred', () => {
+ const hidden = make({ cursorVisible: false, cursorY: 1, cursorX: 1 })
+ hidden.core.renderRows(0, 2)
+ for (const rec of hidden.handle.rows)
+ for (let c = 0; c < 4; c++) expect(readCell(rec.cells, c).flags & FLAG_CURSOR).toBe(0)
+
+ const blurred = make({ focus: false, cursorY: 1, cursorX: 1 })
+ blurred.core.renderRows(0, 2)
+ for (const rec of blurred.handle.rows)
+ for (let c = 0; c < 4; c++) expect(readCell(rec.cells, c).flags & FLAG_CURSOR).toBe(0)
+ })
+})
+
+describe('GlyphGridRendererAddonCore.handleResize', () => {
+ it('resizes the grid BEFORE repacking, then repacks every row', () => {
+ const { core, handle } = make({ cols: 4, rows: 6 })
+ handle.log.length = 0
+ handle.rows.length = 0
+ core.handleResize(8, 3)
+ expect(handle.log[0]).toBe('resize:8x3')
+ expect(handle.rows.map((r) => r.row)).toEqual([0, 1, 2])
+ // The row buffer follows the new column count — the engine rejects a mismatched length.
+ expect(handle.rows[0].buf.length).toBe(8 * CELL_STRIDE)
+ expect(handle.rows[0].cells.length).toBe(8 * CELL_STRIDE)
+ })
+
+ it('rebuilds dimensions from the new grid size', () => {
+ const { core } = make({ cols: 4, rows: 6 })
+ core.handleResize(10, 5)
+ expect(core.dimensions.device.canvas.width).toBe(16 * 10)
+ expect(core.dimensions.device.canvas.height).toBe(34 * 5)
+ expect(core.dimensions.css.canvas.width).toBe(80) // round(160 / dpr 2)
+ expect(core.dimensions.css.cell.width).toBe(8)
+ })
+})
+
+describe('GlyphGridRendererAddonCore.dimensions', () => {
+ it('mirrors xterm dimension shape at construction', () => {
+ const { core } = make({ cols: 4, rows: 6 })
+ expect(core.dimensions).toEqual({
+ css: { canvas: { width: 32, height: 102 }, cell: { width: 8, height: 17 } },
+ device: {
+ canvas: { width: 64, height: 204 },
+ cell: { width: 16, height: 34 },
+ char: { width: 16, height: 34, left: 0, top: 0 }
+ }
+ })
+ })
+})
+
+describe('GlyphGridRendererAddonCore selection', () => {
+ it('repacks the union of the OLD and NEW spans, and nothing else', () => {
+ const { core, handle } = make({ rows: 8, viewportY: 0 })
+ core.handleSelectionChanged([1, 1], [2, 2], false)
+ handle.rows.length = 0
+ core.handleSelectionChanged([0, 5], [3, 6], false)
+ expect([...new Set(handle.rows.map((r) => r.row))].sort((a, b) => a - b)).toEqual([1, 2, 5, 6])
+ })
+
+ it('repacks the cleared rows when the selection goes away', () => {
+ const { core, handle } = make({ rows: 8 })
+ core.handleSelectionChanged([1, 2], [3, 3], false)
+ handle.rows.length = 0
+ core.handleSelectionChanged(undefined, undefined, false)
+ expect(handle.rows.map((r) => r.row)).toEqual([2, 3])
+ for (const rec of handle.rows)
+ for (let c = 0; c < 4; c++) expect(readCell(rec.cells, c).flags & FLAG_SELECTED).toBe(0)
+ })
+
+ it('marks a LINEAR span: first row from startCol, middle rows full width, last row to endCol', () => {
+ const { core, handle } = make({ rows: 8, cols: 4 })
+ core.handleSelectionChanged([2, 1], [3, 3], false)
+ const sel = (row: number): number[] =>
+ [0, 1, 2, 3].filter(
+ (c) => readCell(handle.rows.find((r) => r.row === row)!.cells, c).flags & FLAG_SELECTED
+ )
+ expect(sel(1)).toEqual([2, 3])
+ expect(sel(2)).toEqual([0, 1, 2, 3])
+ expect(sel(3)).toEqual([0, 1, 2])
+ })
+
+ it('marks a RECTANGULAR (column-select) span identically on every row in range', () => {
+ const { core, handle } = make({ rows: 8, cols: 4 })
+ core.handleSelectionChanged([3, 1], [1, 3], true)
+ const sel = (row: number): number[] =>
+ [0, 1, 2, 3].filter(
+ (c) => readCell(handle.rows.find((r) => r.row === row)!.cells, c).flags & FLAG_SELECTED
+ )
+ // Endpoints arrive in either order; the rectangle spans [min, max).
+ expect(sel(1)).toEqual([1, 2])
+ expect(sel(2)).toEqual([1, 2])
+ expect(sel(3)).toEqual([1, 2])
+ })
+
+ it('translates an absolute span through a scrolled viewport', () => {
+ const { core, handle } = make({ rows: 4, cols: 4, viewportY: 100, baseY: 100 })
+ core.handleSelectionChanged([0, 101], [4, 101], false)
+ expect(handle.rows.map((r) => r.row)).toEqual([1])
+ expect(readCell(handle.rows[0].cells, 0).flags & FLAG_SELECTED).toBe(FLAG_SELECTED)
+ })
+
+ it('ignores a span that lies entirely outside the viewport', () => {
+ const { core, handle } = make({ rows: 4, viewportY: 100 })
+ handle.rows.length = 0
+ core.handleSelectionChanged([0, 10], [4, 12], false)
+ expect(handle.rows).toEqual([])
+ })
+})
+
+describe('GlyphGridRendererAddonCore cursor + focus', () => {
+ it('repacks exactly the old and the new cursor row on a move', () => {
+ const { core, term, handle } = make({ rows: 8, cursorY: 1 })
+ core.renderRows(0, 7)
+ handle.rows.length = 0
+ term.state.cursorY = 5
+ core.handleCursorMove()
+ expect(handle.rows.map((r) => r.row).sort((a, b) => a - b)).toEqual([1, 5])
+ })
+
+ it('repacks one row when the cursor moves within its row', () => {
+ const { core, term, handle } = make({ rows: 8, cursorY: 2, cursorX: 0 })
+ handle.rows.length = 0
+ term.state.cursorX = 3
+ core.handleCursorMove()
+ expect(handle.rows.map((r) => r.row)).toEqual([2])
+ expect(readCell(handle.rows[0].cells, 3).flags & FLAG_CURSOR).toBe(FLAG_CURSOR)
+ })
+
+ it('blur repacks the cursor row without the cursor; focus paints it back', () => {
+ const { core, handle } = make({ rows: 8, cursorY: 4, cursorX: 1 })
+ handle.rows.length = 0
+ core.handleBlur()
+ expect(handle.rows.map((r) => r.row)).toEqual([4])
+ expect(readCell(handle.rows[0].cells, 1).flags & FLAG_CURSOR).toBe(0)
+
+ handle.rows.length = 0
+ core.handleFocus()
+ expect(handle.rows.map((r) => r.row)).toEqual([4])
+ expect(readCell(handle.rows[0].cells, 1).flags & FLAG_CURSOR).toBe(FLAG_CURSOR)
+ })
+})
+
+describe('GlyphGridRendererAddonCore redraw requests', () => {
+ it('clear() repacks everything and asks xterm for a full redraw', () => {
+ const { core, handle } = make({ rows: 5 })
+ const seen: Array<{ start: number; end: number }> = []
+ core.onRequestRedraw((e) => seen.push(e))
+ handle.rows.length = 0
+ core.clear()
+ expect(handle.rows.map((r) => r.row)).toEqual([0, 1, 2, 3, 4])
+ expect(seen).toEqual([{ start: 0, end: 4 }])
+ })
+
+ it('a theme change repacks everything and asks for a full redraw', () => {
+ const { core, handle } = make({ rows: 3 })
+ const seen: Array<{ start: number; end: number }> = []
+ core.onRequestRedraw((e) => seen.push(e))
+ handle.rows.length = 0
+ core.handleThemeChange()
+ expect(handle.rows.map((r) => r.row)).toEqual([0, 1, 2])
+ expect(seen).toEqual([{ start: 0, end: 2 }])
+ })
+
+ it('a disposed redraw subscription stops receiving', () => {
+ const { core } = make()
+ const seen: number[] = []
+ const sub = core.onRequestRedraw(() => seen.push(1))
+ core.clear()
+ sub.dispose()
+ core.clear()
+ expect(seen).toHaveLength(1)
+ })
+})
+
+describe('GlyphGridRendererAddonCore.dispose', () => {
+ it('makes every further call inert — a torn-down terminal must never touch the grid', () => {
+ const { core, handle } = make({ rows: 6 })
+ const seen: number[] = []
+ core.onRequestRedraw(() => seen.push(1))
+ core.dispose()
+ handle.log.length = 0
+ handle.rows.length = 0
+ core.renderRows(0, 5)
+ core.clear()
+ core.handleThemeChange()
+ core.handleResize(9, 9)
+ core.handleSelectionChanged([0, 0], [2, 2], false)
+ core.handleCursorMove()
+ core.handleBlur()
+ core.handleFocus()
+ core.handleCharSizeChanged()
+ core.handleDevicePixelRatioChange()
+ expect(handle.log).toEqual([])
+ expect(handle.rows).toEqual([])
+ expect(seen).toEqual([])
+ })
+
+ it('does NOT dispose the grid handle — the node that registered it owns its lifetime', () => {
+ const { core, handle } = make()
+ core.dispose()
+ expect(handle.log).not.toContain('dispose')
+ })
+})
diff --git a/src/renderer/glyphgrid/addon.ts b/src/renderer/glyphgrid/addon.ts
new file mode 100644
index 000000000..0fa0ca48f
--- /dev/null
+++ b/src/renderer/glyphgrid/addon.ts
@@ -0,0 +1,373 @@
+/** The xterm-facing brain of the glyphgrid renderer: xterm's renderer callbacks in, packed grid
+ * rows out.
+ *
+ * Like the rest of this directory it imports NOTHING from xterm. Everything the terminal knows
+ * arrives through `TermInternals`, a hand-written narrowing of the handful of xterm internals we
+ * read, built by `src/renderer/terminal/glyphgrid-attach.ts`. That split is the point: xterm's
+ * private surface is the part of that library most likely to move under us, and keeping it behind
+ * one injected interface means a bump breaks ONE thin shell instead of the renderer, and lets the
+ * whole render path be unit-tested without a DOM, a canvas or a terminal. */
+
+import type { GlyphAtlas } from './atlas'
+import { CELL_STRIDE } from './cells'
+import type { GridHandle } from './engine'
+import { packViewportRow, type CellView, type ThemeLanes } from './feed'
+
+/** Cell/char metrics in DEVICE pixels, already carrying xterm's own rounding (charSize × dpr,
+ * ceil on char height, letterSpacing, lineHeight). The shell computes them exactly the way
+ * xterm's own renderers do, because `dimensions.css.cell` derived from them is what xterm maps
+ * MOUSE COORDINATES through — a rounding that differs by a fraction of a pixel per row puts the
+ * selection on the wrong line at the bottom of a tall terminal. */
+export interface DeviceMetrics {
+ charW: number
+ charH: number
+ cellW: number
+ cellH: number
+}
+
+/** What the addon needs from a live terminal. Kept minimal so the addon is testable with fakes and
+ * survives xterm minor bumps. */
+export interface TermInternals {
+ cols(): number
+ rows(): number
+ /** buffer.ydisp — the absolute row the viewport's top line shows. */
+ viewportY(): number
+ /** buffer.ybase — the absolute row the cursor's row index is relative to. */
+ baseY(): number
+ cursorX(): number
+ /** base-relative (buffer.y); viewport row = baseY + cursorY - viewportY */
+ cursorY(): number
+ /** xterm's `isCursorInitialized && !isCursorHidden`. A TUI that hides the cursor (DECTCEM)
+ * must not leave a phantom block sitting in the middle of the screen. */
+ cursorVisible(): boolean
+ readCell(absoluteRow: number, col: number, into: CellView): CellView | undefined
+ makeWorkCell(): CellView
+ deviceMetrics(): DeviceMetrics
+ dpr(): number
+ theme(): ThemeLanes
+ /** Read ONCE, at construction — see `focused`. */
+ hasFocus(): boolean
+}
+
+/** The exact shape of xterm's `IRenderer.dimensions`. RenderService reads it straight off the
+ * renderer object (`get dimensions()`), so it must exist from the first tick after setRenderer. */
+export interface RendererDims {
+ css: { canvas: { width: number; height: number }; cell: { width: number; height: number } }
+ device: {
+ canvas: { width: number; height: number }
+ cell: { width: number; height: number }
+ char: { width: number; height: number; left: number; top: number }
+ }
+}
+
+type SelPoint = readonly [number, number]
+
+/** Inclusive viewport-row range, or null for "nothing to do". */
+type RowRange = readonly [number, number] | null
+
+/** Order two absolute buffer points. xterm's selection service already hands them over ordered,
+ * but a renderer that assumed so and was wrong would silently draw NOTHING (every row would fall
+ * outside the range) — a cheap comparison buys immunity. */
+function orderPoints(a: SelPoint, b: SelPoint): [SelPoint, SelPoint] {
+ if (a[1] > b[1] || (a[1] === b[1] && a[0] > b[0])) return [b, a]
+ return [a, b]
+}
+
+export class GlyphGridRendererAddonCore {
+ /** Rebuilt on resize / char-size / dpr change; never reassigned in place, so a consumer holding
+ * the old object sees a consistent snapshot rather than a half-updated one. */
+ dimensions: RendererDims
+
+ private cols: number
+ private rows: number
+ private disposed = false
+ /** ONE row buffer for every row of every frame — `GridHandle.updateRow` copies, so reusing it is
+ * safe, and packing a 200-row canvas of terminals must not allocate. Replaced only when the
+ * column count changes (the engine rejects a row of the wrong length). */
+ private rowBuf: Uint32Array
+ private readonly workCell: CellView
+ private readonly redrawListeners = new Set<(e: { start: number; end: number }) => void>()
+
+ /** Absolute buffer selection, normalized so `selTop` is never after `selBottom`. */
+ private selTop: SelPoint | undefined
+ private selBottom: SelPoint | undefined
+ private columnSelect = false
+
+ /** Focus is OURS to track, not a live read of the terminal: xterm calls handleBlur/handleFocus
+ * from its own focus events, and whether the browser-service flag has already flipped by then
+ * is an ordering detail we would be betting the cursor's correctness on. Seeded once. */
+ private focused: boolean
+ /** Viewport row the cursor was on at the last cursor-move — the row a move has to REPAINT to
+ * erase the old block. Geometric (not focus-gated), so blur/focus and moves stay independent. */
+ private lastCursorRow: number
+
+ /** Mutable because `readCellBound` closes over it: one closure for the lifetime of the addon
+ * instead of one per packed row. */
+ private absRow = 0
+ private readonly readCellBound = (col: number, into: CellView): CellView | undefined =>
+ this.internals.readCell(this.absRow, col, into)
+
+ constructor(
+ private readonly internals: TermInternals,
+ private readonly handle: GridHandle,
+ private readonly atlas: Pick<GlyphAtlas, 'glyphFor'>
+ ) {
+ this.cols = internals.cols()
+ this.rows = internals.rows()
+ this.rowBuf = new Uint32Array(Math.max(0, this.cols) * CELL_STRIDE)
+ this.workCell = internals.makeWorkCell()
+ this.focused = internals.hasFocus()
+ this.lastCursorRow = this.cursorViewportRow()
+ this.dimensions = this.buildDims()
+ }
+
+ // ---------------------------------------------------------------- xterm renderer surface
+ //
+ // Every member RenderService calls, and nothing else. The one deliberate omission is the
+ // OPTIONAL `clearTextureAtlas`: the atlas is SHARED by every terminal on the canvas, so one
+ // terminal must not be able to wipe it — a font change tears the whole shared context down and
+ // re-registers each node instead. RenderService calls it as `?.()`, so leaving it off is the
+ // supported way to decline.
+
+ renderRows(start: number, end: number): void {
+ this.packRows(start, end)
+ }
+
+ /** xterm calls this when the active buffer switches (alt screen in/out). The grid's rows are
+ * simply repacked from whatever buffer is now active; the redraw request is what gets the
+ * ranges xterm considers dirty replayed on top. */
+ clear(): void {
+ this.repackAll()
+ }
+
+ handleResize(cols: number, rows: number): void {
+ if (this.disposed) return
+ this.cols = cols
+ this.rows = rows
+ if (this.rowBuf.length !== cols * CELL_STRIDE) this.rowBuf = new Uint32Array(cols * CELL_STRIDE)
+ // The grid must be the new size BEFORE the first row of the new frame reaches it — an
+ // updateRow of the new width against the old grid is rejected outright.
+ this.handle.resize(cols, rows)
+ this.dimensions = this.buildDims()
+ this.packRows(0, rows - 1)
+ }
+
+ /** Cell metrics changed (font size, letter spacing). Only the DIMENSIONS are ours to fix: the
+ * grid's own cell size is fixed at registration and a change tears the shared context down and
+ * re-registers every node (see the shared layer), so there is nothing to repack here. */
+ handleCharSizeChanged(): void {
+ if (this.disposed) return
+ this.dimensions = this.buildDims()
+ }
+
+ handleDevicePixelRatioChange(): void {
+ if (this.disposed) return
+ this.dimensions = this.buildDims()
+ }
+
+ /** Absolute buffer coords, straight from xterm's selection service.
+ *
+ * Only the rows the selection ENTERED or LEFT are repacked — the union of the old and the new
+ * span. xterm's own DOM renderer repaints all `rows` here, which on this canvas would mean
+ * repacking every row of every terminal on every drag tick. */
+ handleSelectionChanged(
+ start: SelPoint | undefined,
+ end: SelPoint | undefined,
+ columnSelectMode: boolean
+ ): void {
+ if (this.disposed) return
+ const before = this.selectionRowRange()
+ if (start && end) {
+ const [top, bottom] = orderPoints(start, end)
+ this.selTop = top
+ this.selBottom = bottom
+ } else {
+ this.selTop = undefined
+ this.selBottom = undefined
+ }
+ this.columnSelect = columnSelectMode
+ const after = this.selectionRowRange()
+ for (const [from, to] of mergeRanges(before, after)) this.packRows(from, to)
+ }
+
+ handleCursorMove(): void {
+ if (this.disposed) return
+ const next = this.cursorViewportRow()
+ const prev = this.lastCursorRow
+ this.lastCursorRow = next
+ this.packRows(next, next)
+ if (prev !== next) this.packRows(prev, prev)
+ }
+
+ handleBlur(): void {
+ if (this.disposed) return
+ this.focused = false
+ this.packCursorRow()
+ }
+
+ handleFocus(): void {
+ if (this.disposed) return
+ this.focused = true
+ this.packCursorRow()
+ }
+
+ /** Not part of xterm's renderer surface — the shell calls it from `_themeService.onChangeColors`.
+ * Every packed lane is a resolved color, so a theme change invalidates the whole grid. */
+ handleThemeChange(): void {
+ this.repackAll()
+ }
+
+ onRequestRedraw(cb: (e: { start: number; end: number }) => void): { dispose(): void } {
+ this.redrawListeners.add(cb)
+ return {
+ dispose: (): void => {
+ this.redrawListeners.delete(cb)
+ }
+ }
+ }
+
+ /** Called by xterm when the renderer is replaced (RenderService holds it in a MutableDisposable),
+ * and by the shell's own teardown. Everything after this is a silent no-op: a terminal being
+ * torn down mid-frame is a teardown race, not a bug, and it must never write into a grid whose
+ * owner has already dropped it.
+ *
+ * The grid HANDLE is deliberately not disposed — the node that registered it owns its lifetime
+ * (it outlives a renderer swap back to DOM). */
+ dispose(): void {
+ this.disposed = true
+ this.redrawListeners.clear()
+ }
+
+ // ---------------------------------------------------------------- internals
+
+ private repackAll(): void {
+ if (this.disposed) return
+ this.packRows(0, this.rows - 1)
+ this.emitRedraw(0, this.rows - 1)
+ }
+
+ private packCursorRow(): void {
+ const row = this.cursorViewportRow()
+ this.packRows(row, row)
+ }
+
+ /** The single funnel: every path that changes what a row should look like ends here.
+ *
+ * Reads viewport/theme/cursor ONCE for the whole range — they cannot change mid-loop, and
+ * `theme()` in particular hands back the shell's cached snapshot, which there is no reason to
+ * re-read per row. */
+ private packRows(from: number, to: number): void {
+ if (this.disposed) return
+ const start = Math.max(0, from)
+ const end = Math.min(this.rows - 1, to)
+ if (end < start || this.cols <= 0) return
+ const theme = this.internals.theme()
+ const viewportY = this.internals.viewportY()
+ // -1 = no cursor anywhere in this pass (hidden by the app, or the terminal is not focused —
+ // xterm draws a hollow outline there, which this engine has no flag for; painting nothing is
+ // the honest v1 degradation and is what handleBlur repacks the row to produce).
+ const cursorRow =
+ this.focused && this.internals.cursorVisible()
+ ? this.internals.baseY() + this.internals.cursorY() - viewportY
+ : -1
+ // CLAMPED, exactly as xterm's own renderers do (`Math.min(buffer.x, cols - 1)`): with a
+ // deferred wrap pending, the buffer's x sits ON `cols`, one past the last column. Left
+ // unclamped it matches no column and the cursor simply VANISHES at the end of a full line —
+ // which is where a shell prompt spends much of its time.
+ const cursorCol = Math.min(this.internals.cursorX(), this.cols - 1)
+ for (let row = start; row <= end; row++) {
+ this.absRow = viewportY + row
+ packViewportRow(this.rowBuf, this.readCellBound, this.workCell, {
+ cols: this.cols,
+ atlas: this.atlas,
+ theme,
+ selection: this.selectionOnRow(this.absRow),
+ // A block cursor on a DOUBLE-WIDTH glyph paints the left half only: the cursor is one
+ // column and the glyph is two. Known v1 limitation (the two-column rule needs the wide
+ // flag honoured in the shader) — visible, harmless, tracked for Phase 2.
+ cursorCol: row === cursorRow ? cursorCol : -1
+ })
+ this.handle.updateRow(row, this.rowBuf)
+ }
+ }
+
+ /** Column span [start, endExclusive) of the selection on one ABSOLUTE buffer row, or null.
+ *
+ * Mirrors xterm's own selection render model exactly (DomRenderer.handleSelectionChanged):
+ * in column-select mode every row in range gets the same [min, max) rectangle; linearly, the
+ * first row starts at the start column, the last ends at the end column (EXCLUSIVE), and the
+ * rows between are full width. */
+ private selectionOnRow(absRow: number): readonly [number, number] | null {
+ const top = this.selTop
+ const bottom = this.selBottom
+ if (!top || !bottom) return null
+ if (absRow < top[1] || absRow > bottom[1]) return null
+ let startCol: number
+ let endCol: number
+ if (this.columnSelect) {
+ startCol = Math.min(top[0], bottom[0])
+ endCol = Math.max(top[0], bottom[0])
+ } else {
+ startCol = absRow === top[1] ? top[0] : 0
+ endCol = absRow === bottom[1] ? bottom[0] : this.cols
+ }
+ return endCol > startCol ? [startCol, endCol] : null
+ }
+
+ /** Which VIEWPORT rows the current selection covers — the repaint unit, clamped to the grid. */
+ private selectionRowRange(): RowRange {
+ const top = this.selTop
+ const bottom = this.selBottom
+ if (!top || !bottom) return null
+ const viewportY = this.internals.viewportY()
+ const from = Math.max(0, top[1] - viewportY)
+ const to = Math.min(this.rows - 1, bottom[1] - viewportY)
+ return to < from ? null : [from, to]
+ }
+
+ private cursorViewportRow(): number {
+ return this.internals.baseY() + this.internals.cursorY() - this.internals.viewportY()
+ }
+
+ /** Exactly xterm's own dimension math (DomRenderer._updateDimensions), which is why the shell
+ * hands over DEVICE metrics rather than css ones: css.cell is derived from the ROUNDED css
+ * canvas, and xterm maps mouse coordinates through it. */
+ private buildDims(): RendererDims {
+ const m = this.internals.deviceMetrics()
+ const dpr = this.internals.dpr() || 1
+ const cols = Math.max(0, this.cols)
+ const rows = Math.max(0, this.rows)
+ const deviceCanvasW = m.cellW * cols
+ const deviceCanvasH = m.cellH * rows
+ const cssCanvasW = Math.round(deviceCanvasW / dpr)
+ const cssCanvasH = Math.round(deviceCanvasH / dpr)
+ return {
+ css: {
+ canvas: { width: cssCanvasW, height: cssCanvasH },
+ // A zero-column grid would make these NaN, which propagates into xterm's mouse math.
+ cell: { width: cols > 0 ? cssCanvasW / cols : 0, height: rows > 0 ? cssCanvasH / rows : 0 }
+ },
+ device: {
+ canvas: { width: deviceCanvasW, height: deviceCanvasH },
+ cell: { width: m.cellW, height: m.cellH },
+ char: { width: m.charW, height: m.charH, left: 0, top: 0 }
+ }
+ }
+ }
+
+ private emitRedraw(start: number, end: number): void {
+ if (this.disposed) return
+ for (const cb of this.redrawListeners) cb({ start, end })
+ }
+}
+
+/** Union of two inclusive row ranges as a list of ranges to repack. Overlapping or touching
+ * ranges collapse into one; disjoint ones stay separate, so a selection jumping from the top of
+ * the viewport to the bottom does not repack everything in between. */
+function mergeRanges(a: RowRange, b: RowRange): Array<readonly [number, number]> {
+ if (!a) return b ? [b] : []
+ if (!b) return [a]
+ const [lo, hi] = a[0] <= b[0] ? [a, b] : [b, a]
+ if (hi[0] <= lo[1] + 1) return [[lo[0], Math.max(lo[1], hi[1])]]
+ return [lo, hi]
+}
diff --git a/src/renderer/terminal/glyphgrid-attach.ts b/src/renderer/terminal/glyphgrid-attach.ts
new file mode 100644
index 000000000..b1b85b9a3
--- /dev/null
+++ b/src/renderer/terminal/glyphgrid-attach.ts
@@ -0,0 +1,197 @@
+/** The ONE place that touches xterm's private surface for the glyphgrid renderer.
+ *
+ * `src/renderer/glyphgrid/` must never import xterm — that isolation is what keeps the engine and
+ * the addon unit-testable and lets an xterm bump break exactly one file. This is that file: it
+ * reads the internals, wraps them in the addon's `TermInternals`, and hands the addon to xterm's
+ * render service as the terminal's renderer.
+ *
+ * It has NO unit tests by design (there is no jsdom in which xterm's render service, char-size
+ * measurement and WebGL all exist); it is verified on device. That is exactly why it is kept
+ * small and why every internal access goes through the single guarded `coreOf()` — anything
+ * missing means we return null and the caller stays on xterm's own DOM renderer, which is the
+ * behavior we ship today. */
+
+import type { Terminal } from '@xterm/xterm'
+import {
+ GlyphGridRendererAddonCore,
+ type DeviceMetrics,
+ type TermInternals
+} from '../glyphgrid/addon'
+import type { GlyphAtlas } from '../glyphgrid/atlas'
+import { packColor } from '../glyphgrid/cells'
+import type { GridHandle } from '../glyphgrid/engine'
+import type { CellView, ThemeLanes } from '../glyphgrid/feed'
+
+/** xterm's IColor — `rgba` is 0xRRGGBBAA. */
+interface XtermColor {
+ rgba: number
+}
+interface XtermColors {
+ foreground: XtermColor
+ background: XtermColor
+ cursor: XtermColor
+ cursorAccent: XtermColor
+ selectionBackgroundOpaque: XtermColor
+ ansi: XtermColor[]
+}
+interface XtermLine {
+ length: number
+ loadCell(col: number, cell: unknown): unknown
+}
+/** The private members of xterm 5.5 we depend on. Names verified against the shipped bundle. */
+interface XtermCore {
+ _renderService: { setRenderer(r: unknown): void; handleResize(cols: number, rows: number): void }
+ _createRenderer(): unknown
+ _themeService: {
+ colors: XtermColors
+ onChangeColors(cb: (colors: XtermColors) => void): { dispose(): void }
+ }
+ _charSizeService: { width: number; height: number }
+ _coreBrowserService: { dpr: number; isFocused: boolean }
+ _bufferService: { buffer: { lines: { get(row: number): XtermLine | undefined } } }
+ coreService: { isCursorInitialized: boolean; isCursorHidden: boolean }
+}
+
+/** Every internal read in this module starts here. Presence-checked rather than cast, so a bumped
+ * xterm that dropped or renamed one of these degrades to "no glyphgrid" instead of throwing
+ * somewhere inside a render tick. */
+function coreOf(term: Terminal): XtermCore | null {
+ try {
+ const c = (term as unknown as { _core?: Partial<XtermCore> })._core
+ if (!c) return null
+ if (typeof c._createRenderer !== 'function') return null
+ if (!c._renderService || typeof c._renderService.setRenderer !== 'function') return null
+ if (!c._themeService?.colors || typeof c._themeService.onChangeColors !== 'function') return null
+ if (!c._charSizeService || !c._coreBrowserService || !c._bufferService?.buffer) return null
+ if (!c.coreService) return null
+ return c as XtermCore
+ } catch {
+ return null
+ }
+}
+
+/** 0xRRGGBBAA → an OPAQUE packed lane. Alpha is forced: the engine's plate owns occlusion in v1,
+ * and a theme's translucent background would otherwise punch a hole in a node. */
+function lane(c: XtermColor | undefined): number {
+ const v = ((c?.rgba ?? 0) >>> 8) & 0xffffff
+ return packColor((v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff, 0xff)
+}
+
+function themeLanes(colors: XtermColors): ThemeLanes {
+ return {
+ fg: lane(colors.foreground),
+ bg: lane(colors.background),
+ ansi: colors.ansi.map(lane),
+ // xterm paints the glyph under a block cursor in `cursorAccent` on `cursor`.
+ cursorFg: lane(colors.cursorAccent),
+ cursorBg: lane(colors.cursor),
+ selectionBg: lane(colors.selectionBackgroundOpaque)
+ }
+}
+
+/** xterm's own device-metric rounding (DomRenderer._updateDimensions), reproduced exactly: the
+ * addon derives `dimensions.css.cell` from these, and xterm maps MOUSE coordinates through that
+ * — an off-by-a-fraction here puts selection on the wrong line at the bottom of the terminal. */
+function deviceMetrics(term: Terminal, core: XtermCore): DeviceMetrics {
+ const dpr = core._coreBrowserService.dpr || 1
+ const charW = core._charSizeService.width * dpr
+ const charH = Math.ceil(core._charSizeService.height * dpr)
+ return {
+ charW,
+ charH,
+ cellW: charW + Math.round(term.options.letterSpacing ?? 0),
+ cellH: Math.floor(charH * (term.options.lineHeight ?? 1))
+ }
+}
+
+/** Put xterm back on its own DOM renderer — the same guarded sequence as TerminalNode's
+ * `restoreDomRenderer` safety net. `setRenderer` disposes whatever renderer it replaces, so this
+ * is also what retires the addon. */
+function restoreDomRenderer(term: Terminal): boolean {
+ const core = coreOf(term)
+ if (!core) return false
+ try {
+ core._renderService.setRenderer(core._createRenderer())
+ core._renderService.handleResize(term.cols, term.rows)
+ return true
+ } catch {
+ return false
+ }
+}
+
+/** Point `term` at the shared glyph grid. Returns null — having touched nothing — when the
+ * internals are not what we expect, so the caller simply stays on the DOM renderer. */
+export function attachGlyphGrid(
+ term: Terminal,
+ handle: GridHandle,
+ atlas: GlyphAtlas
+): { dispose(): void } | null {
+ const core = coreOf(term)
+ if (!core) return null
+ let theme = themeLanes(core._themeService.colors)
+ // ONE cell object for every read of every frame. `loadCell` fills it in place; the public
+ // `getNullCell()` hands back the very CellData class xterm's own renderers allocate, so its
+ // getters agree with the buffer's encoding. (The public `buffer.getLine()` path is not used:
+ // it allocates a wrapper per call — per CELL here — which is the frame budget.)
+ const workCell = term.buffer.active.getNullCell() as unknown as CellView
+
+ const internals: TermInternals = {
+ cols: () => term.cols,
+ rows: () => term.rows,
+ viewportY: () => term.buffer.active.viewportY,
+ baseY: () => term.buffer.active.baseY,
+ cursorX: () => term.buffer.active.cursorX,
+ cursorY: () => term.buffer.active.cursorY,
+ cursorVisible: () => core.coreService.isCursorInitialized && !core.coreService.isCursorHidden,
+ readCell: (row, col, into) => {
+ const line = core._bufferService.buffer.lines.get(row)
+ // Past the end of the buffer or of a short line: no cell. The feed renders that as a blank
+ // on the theme background — reading past `length` would hand back undefined lanes.
+ if (!line || col >= line.length) return undefined
+ line.loadCell(col, into)
+ return into
+ },
+ makeWorkCell: () => workCell,
+ deviceMetrics: () => deviceMetrics(term, core),
+ dpr: () => core._coreBrowserService.dpr || 1,
+ theme: () => theme,
+ hasFocus: () => core._coreBrowserService.isFocused
+ }
+
+ let addon: GlyphGridRendererAddonCore
+ try {
+ addon = new GlyphGridRendererAddonCore(internals, handle, atlas)
+ // The addon IS the renderer object: its public surface is exactly what RenderService calls.
+ core._renderService.setRenderer(addon)
+ } catch {
+ // A throw here can leave xterm holding a half-installed renderer (setRenderer disposed the DOM
+ // one first), so restore before reporting failure rather than just returning.
+ restoreDomRenderer(term)
+ return null
+ }
+
+ // xterm's render service already schedules a full refresh on a color change; this keeps the
+ // snapshot the addon packs from in step with it, and repaints in case the refresh is coalesced
+ // away.
+ const themeSub = core._themeService.onChangeColors((colors) => {
+ theme = themeLanes(colors)
+ addon.handleThemeChange()
+ })
+
+ let disposed = false
+ return {
+ dispose(): void {
+ if (disposed) return
+ disposed = true
+ try {
+ themeSub.dispose()
+ } catch {
+ // already torn down with the terminal — fine
+ }
+ restoreDomRenderer(term)
+ // Belt and braces: `setRenderer` disposes the addon for us, but if the restore failed the
+ // addon must still go inert so it can never write into a grid the node is about to drop.
+ addon.dispose()
+ }
+ }
+}