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
fix(glyphgrid): 1:1 atlas texels, an opaque label row, and a camera that keeps up with the pan
enes7bf8681adfbd
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 8fc3eb301..fad1cd84f 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -4987,6 +4987,16 @@ export function Canvas() {(_e: unknown, vp: Viewport) => {viewportRef.current = vpmarkDirty()+ // SYNCHRONOUS, and deliberately OUTSIDE the coalescing rAF below. React Flow applies the+ // viewport's CSS transform inside the d3-zoom event that raised this callback, so the node+ // chrome has already moved by the time we return; the shared glyph canvas is redrawn by the+ // layer's own persistent rAF, which must therefore be able to read this frame's camera+ // BEFORE it runs. Fed from the coalescing rAF instead, the camera arrived one tick late and+ // the canvas painted the PREVIOUS pan every frame — the drawn text lagging the node bodies+ // by a frame or two, which reads as the text wobbling loose behind its own node while the+ // DOM moves rigidly. Cost is three field writes plus a change-gated `engine.setCamera`, so+ // there is nothing here worth coalescing.+ setSharedGlyphCamera(vp)// Latch the WebGL gesture flag for the whole pan/zoom, releasing it a beat after the last// viewport event: renderer swaps (heavyweight, non-atomic) may only run at rest — a swap// executed mid-gesture is both the jank and the black-terminal window (see webgl-budget's@@ -5008,9 +5018,6 @@ export function Canvas() {// Feed the WebGL budget's zoom gate (suspend GPU rendering when zoomed way out).// Idempotent + hysteresis inside; per-frame call cost is a float compare.setWebglZoom(viewportRef.current.zoom)- // Same coalesced frame feeds the shared glyph canvas: its camera and the DOM nodes'- // transform must move together, or the text lags the node bodies by a frame.- setSharedGlyphCamera(viewportRef.current)})}},diff --git a/src/renderer/canvas/SharedGlyphLayer.test.ts b/src/renderer/canvas/SharedGlyphLayer.test.tsindex cf68a3cf4..a42c1b18c 100644--- a/src/renderer/canvas/SharedGlyphLayer.test.ts+++ b/src/renderer/canvas/SharedGlyphLayer.test.ts@@ -256,6 +256,8 @@ describe('setNodeZOrder', () => {})describe('graceful degrade without a GPU', () => {+ /** A plausible xterm device cell (13px font at dpr 2): fractional width, integer height. */+ const CELL = { cellW: 15.66, cellH: 31 }let warn: ReturnType<typeof vi.spyOn>beforeEach(() => {warn = vi.spyOn(console, 'warn').mockImplementation(() => {})@@ -265,18 +267,58 @@ describe('graceful degrade without a GPU', () => {})it('getSharedGlyphContext returns null while the shared mode is off — no context is acquired', () => {- expect(getSharedGlyphContext()).toBeNull()+ expect(getSharedGlyphContext(CELL)).toBeNull()})it('returns null (rather than throwing) when WebGL2/OffscreenCanvas are unavailable', () => {useSharedGlyph.getState().setEnabled(true)- expect(getSharedGlyphContext()).toBeNull()+ expect(getSharedGlyphContext(CELL)).toBeNull()})it('returns null once the session has failed', () => {useSharedGlyph.getState().setEnabled(true)useSharedGlyph.getState().markFailed()- expect(getSharedGlyphContext()).toBeNull()+ expect(getSharedGlyphContext(CELL)).toBeNull()+ })++ // The atlas rasterizes into xterm's DEVICE cell, and only a live terminal knows it. A caller+ // with no cell to offer (the layer component itself) must therefore adopt an existing context or+ // get null — never build one from guessed metrics, which is the mismatch that made every glyph+ // resample against the quad it is drawn onto.+ it('does not CREATE a context for a caller that supplies no device cell', () => {+ useSharedGlyph.getState().setEnabled(true)+ const g = globalThis as unknown as Record<string, unknown>+ const hadDocument = 'document' in g+ const hadOffscreen = 'OffscreenCanvas' in g+ const prevDocument = g.document+ const prevOffscreen = g.OffscreenCanvas+ try {+ let constructed = 0+ g.document = { createElement: () => ({ style: {}, className: '' }) }+ g.OffscreenCanvas = class {+ constructor() {+ constructed+++ }+ getContext(): null {+ return null+ }+ }+ expect(getSharedGlyphContext()).toBeNull()+ expect(constructed).toBe(0)+ // …and an unusable cell is the same as no cell: it must not latch the one creation attempt.+ expect(getSharedGlyphContext({ cellW: 0, cellH: NaN })).toBeNull()+ expect(constructed).toBe(0)+ // A usable one does reach construction.+ expect(getSharedGlyphContext(CELL)).toBeNull() // no 2d context in this environment+ expect(constructed).toBe(1)+ } finally {+ if (hadDocument) g.document = prevDocument+ else delete g.document+ if (hadOffscreen) g.OffscreenCanvas = prevOffscreen+ else delete g.OffscreenCanvas+ useSharedGlyph.getState().markFailed()+ useSharedGlyph.setState({ enabled: false, failed: false })+ }})it('setSharedGlyphCamera is inert without a context', () => {@@ -310,7 +352,7 @@ describe('graceful degrade without a GPU', () => {}}- expect(getSharedGlyphContext()).toBeNull()+ expect(getSharedGlyphContext(CELL)).toBeNull()expect(warn).toHaveBeenCalled()expect(String(warn.mock.calls[0]?.[0])).toContain('[glyphgrid]')// A construction throw is "not available here", NOT a session failure: flipping `failed`diff --git a/src/renderer/canvas/SharedGlyphLayer.tsx b/src/renderer/canvas/SharedGlyphLayer.tsxindex e6b2c4aa3..0c1d0b1ba 100644--- a/src/renderer/canvas/SharedGlyphLayer.tsx+++ b/src/renderer/canvas/SharedGlyphLayer.tsx@@ -26,7 +26,7 @@* same one `terminal/glyphgrid-attach.ts` makes for xterm's internals.*/-import { useEffect, useRef } from 'react'+import { useEffect, useRef, useState } from 'react'import { create } from 'zustand'import { GlyphAtlas } from '../glyphgrid/atlas'import type { Camera } from '../glyphgrid/camera'@@ -37,22 +37,37 @@ import { createCanvasRasterizer } from '../glyphgrid/raster'import { useSettings } from '../state/settings'/** Atlas page edge, in DEVICE pixels. 2048 (not Phase 0's 1024) because the atlas cells are- * device-sized: at dpr 2 a 13px terminal font is roughly a 16x38 device cell, so a 1024 page- * holds ~1600 glyphs — enough for ASCII plus a little, and nothing like enough for a session+ * device-sized: at dpr 2 a 13px terminal font is roughly a 16x32 device cell, so a 1024 page+ * holds ~2000 glyphs — enough for ASCII plus a little, and nothing like enough for a session* that also shows box drawing, powerline glyphs and CJK. A full page degrades to the blank slot* (GlyphAtlas never throws), i.e. missing text, so the page is sized for the pathological* session rather than the average one. 2048² RGBA = 16 MB of VRAM, once, for the whole canvas. */const ATLAS_PAGE_PX = 2048-/** Fallback cell metrics as a fraction of the font size, used only when the 2D context cannot- * measure (no OffscreenCanvas → we bail before this, or a font that reports nothing). Roughly a- * monospace advance and line box. */-const FALLBACK_ADVANCE_RATIO = 0.6-const FALLBACK_LINE_RATIO = 1.2-/** A cell larger than this would make the atlas page hold almost nothing; clamped rather than- * trusted, since the ratio comes from a user-typed font family. */+/** A cell larger than this would make the atlas page hold almost nothing. The number now comes+ * from xterm rather than from a measurement of a user-typed font family, so this is a sanity+ * clamp on a pathological font size rather than a guard against a bad guess. */const MAX_CELL_PX = 256+/**+ * The cell the atlas rasterizes into, in DEVICE pixels.+ *+ * **The invariant: the atlas texel grid IS xterm's device cell grid, always.** The engine draws a+ * cell as `css.cell × zoom` onto a dpr-scaled buffer, i.e. `device.cell` device pixels at zoom 1,+ * and the atlas slot is stretched over exactly that quad. Any disagreement between the two is a+ * per-glyph resample — the "text is rougher than the DOM renderer" report. So the atlas does not+ * measure anything itself: the first terminal to build the context hands over xterm's own+ * `dimensions.device.cell`, which already carries xterm's rounding chain (charSize × dpr, ceil on+ * the char height, letterSpacing, lineHeight).+ *+ * One cell for the whole canvas is correct because the font settings are GLOBAL — every terminal+ * computes the same device cell from the same font family/size and the same dpr.+ */+export interface DeviceCell {+ cellW: number+ cellH: number+}+// ---------------------------------------------------------------------------------------------// Store — the reactive half of the seam// ---------------------------------------------------------------------------------------------@@ -243,47 +258,18 @@ function fontKeyOf(fontFamily: string, fontSize: number): string {return `${fontFamily}|${fontSize}`}-/**- * The atlas cell, in DEVICE pixels.- *- * Deliberately NOT xterm's measurement. xterm measures the advance of 'W' in a live DOM span per- * terminal (`_charSizeService`), and the addon feeds those exact numbers to the ENGINE as the- * grid's cell size — so cell GEOMETRY on screen is always xterm's own, and mouse coordinates- * stay aligned. The number computed here decides only how many texels a glyph is rasterized- * into; a fraction of a pixel of disagreement rescales the bitmap slightly, it can never move a- * cell. Measuring here through the DOM instead would mean creating and laying out a probe- * element from a module singleton before any terminal exists, for a strictly cosmetic gain.- *- * Rounded UP because every draw is clipped to its slot rect (see raster.ts): a slot a hair too- * small clips the glyph, a slot a hair too big wastes atlas area.- */-function measureCellDevicePx(family: string, sizePx: number): { cellW: number; cellH: number } {- const fallback = {- cellW: Math.max(1, Math.ceil(sizePx * FALLBACK_ADVANCE_RATIO)),- cellH: Math.max(1, Math.ceil(sizePx * FALLBACK_LINE_RATIO))- }- try {- const ctx = new OffscreenCanvas(8, 8).getContext('2d')- if (!ctx) return fallback- ctx.font = `${sizePx}px ${family}`- const m = ctx.measureText('W')- // `fontBoundingBox*` is the FONT's line box, not this glyph's ink box — the right metric for- // a cell, and the one that keeps descenders inside their slot. Guarded because it is- // optional in the spec (and undefined in some engines).- const ascent = m.fontBoundingBoxAscent- const descent = m.fontBoundingBoxDescent- const w = Math.ceil(m.width)- const h = Number.isFinite(ascent) && Number.isFinite(descent) ? Math.ceil(ascent + descent) : 0- return {- cellW: w > 0 ? Math.min(w, MAX_CELL_PX) : fallback.cellW,- cellH: h > 0 ? Math.min(h, MAX_CELL_PX) : fallback.cellH- }- } catch {- return fallback- }+/** Sanity-check the cell a caller supplies before it becomes the atlas's fixed geometry. Null =+ * "do not build a context from this" — the caller stays on the DOM renderer, which is always a+ * correct outcome. */+function usableCell(cell: DeviceCell | undefined): DeviceCell | null {+ if (!cell) return null+ const { cellW, cellH } = cell+ if (!Number.isFinite(cellW) || !Number.isFinite(cellH)) return null+ if (cellW <= 0 || cellH <= 0) return null+ return { cellW: Math.min(cellW, MAX_CELL_PX), cellH: Math.min(cellH, MAX_CELL_PX) }}-function createContext(): LiveContext | null {+function createContext(cell: DeviceCell): LiveContext | null {if (typeof document === 'undefined' || typeof OffscreenCanvas === 'undefined') return nullconst { fontFamily, fontSize } = useSettings.getState().settingsconst dpr = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1@@ -295,7 +281,7 @@ function createContext(): LiveContext | null {// grid on the canvas for a cosmetic gain. The drawing BUFFER does follow the dpr, on every// resize (see the component's `pushViewport`), so geometry is never wrong.const devicePx = Math.max(1, fontSize * dpr)- const { cellW, cellH } = measureCellDevicePx(fontFamily, devicePx)+ const { cellW, cellH } = cell// Rasterizer FIRST: it needs no GPU, so a missing OffscreenCanvas bails out before a WebGL// context has been created (the harness learned this the expensive way — a context acquired// and then dropped unreferenced is exactly the leak this whole layer exists to avoid).@@ -324,6 +310,7 @@ function disposeContext(): void {const ctx = livelive = nullcreationAttempted = false+ cellMismatchWarned = falseif (!ctx) return// BEFORE any GL call: a rAF tick already scheduled with this context must skip its frame rather// than submit against deleted objects (see `LiveContext.disposed`).@@ -375,11 +362,54 @@ function ensureSettingsSubscription(): void {})}-/** The singleton, created on first use. Internal because it also exposes the canvas + GL, which- * only this file's component may touch. */-function ensureLiveContext(): LiveContext | null {+/** 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+ * generation bump — that notification is a re-evaluate-your-participation signal to every+ * registered terminal, and raising it from INSIDE the call one of them is making would re-enter+ * `setupGlyph` before it has registered its grid. */+const contextListeners = new Set<() => void>()++export function subscribeSharedGlyphContext(fn: () => void): () => void {+ contextListeners.add(fn)+ return () => {+ contextListeners.delete(fn)+ }+}++/** One line per context lifetime: every terminal supplies its own device cell and they are all+ * supposed to agree (the font settings are global). A disagreement is a real defect — a dpr+ * change under a live context, a per-terminal letterSpacing — and the symptom is soft text, so+ * say so rather than silently rescaling. */+let cellMismatchWarned = false+function warnOnCellDrift(ctx: LiveContext, cell: DeviceCell | null): void {+ if (!cell || cellMismatchWarned) return+ if (Math.abs(ctx.atlas.cellW - cell.cellW) < 0.01 && Math.abs(ctx.atlas.cellH - cell.cellH) < 0.01)+ return+ cellMismatchWarned = true+ console.warn(+ `[glyphgrid] atlas cell ${ctx.atlas.cellW}×${ctx.atlas.cellH} does not match this terminal's ` ++ `device cell ${cell.cellW}×${cell.cellH} — its glyphs will be resampled`+ )+}++/**+ * The singleton, created on first use. Internal because it also exposes the canvas + GL, which+ * only this file's component may touch.+ *+ * Creation needs `cell` — xterm's device cell (see `DeviceCell`) — so a caller that has no+ * terminal to ask (the component itself) gets the EXISTING context or null, and never builds one+ * with guessed metrics. The first caller that does have one fixes the atlas geometry for the life+ * of the context; a font change tears it down and the next caller rebuilds it with the new cell.+ */+function ensureLiveContext(cell?: DeviceCell): LiveContext | null {if (!sharedGlyphActive()) return null- if (live) return live+ if (live) {+ warnOnCellDrift(live, usableCell(cell))+ return live+ }+ const seed = usableCell(cell)+ if (!seed) return nullif (creationAttempted) return nullcreationAttempted = trueensureSettingsSubscription()@@ -392,20 +422,28 @@ function ensureLiveContext(): LiveContext | null {// null paths treat as "not available here". `creationAttempted` is already true, so the throw// is never retried in a loop.try {- live = createContext()+ live = createContext(seed)} catch (err) {console.warn('[glyphgrid] shared context construction threw; staying on the DOM renderer', err)live = null}+ // Announced only on success, and AFTER `live` is set, so a listener that immediately asks for+ // the context finds it.+ if (live) for (const fn of contextListeners) fn()return live}/*** The shared engine + atlas, created on first use. Null means "stay on the DOM renderer": the- * mode is off, the session has failed, or this machine has no WebGL2/OffscreenCanvas.+ * mode is off, the session has failed, this machine has no WebGL2/OffscreenCanvas — or no context+ * exists yet and the caller passed no `deviceCell` to build one from.+ *+ * `deviceCell` is xterm's `dimensions.device.cell` for the asking terminal. It is what the atlas+ * rasterizes into, and the invariant it exists for is on `DeviceCell`: **the atlas texel grid is+ * xterm's device cell grid, always.***/-export function getSharedGlyphContext(): SharedGlyphContext | null {- return ensureLiveContext()+export function getSharedGlyphContext(deviceCell?: DeviceCell): SharedGlyphContext | null {+ return ensureLiveContext(deviceCell)}/** Camera feed. Always records (so a context created later opens at the right place) and only@@ -438,10 +476,18 @@ export function SharedGlyphLayer(): JSX.Element {const hostRef = useRef<HTMLDivElement>(null)const generation = useSharedGlyph((s) => s.generation)const failed = useSharedGlyph((s) => s.failed)+ /** Bumped when a terminal BUILDS the context. The layer cannot build one itself — the atlas+ * geometry comes from a live terminal's device cell (see `DeviceCell`) — so whichever of the+ * two runs first, the canvas still gets mounted: if this effect ran first it found nothing and+ * this tick brings it back. Declared BEFORE the mounting effect so the subscription is live by+ * the time a terminal in the same commit can create one. */+ const [contextTick, setContextTick] = useState(0)+ useEffect(() => subscribeSharedGlyphContext(() => setContextTick((n) => n + 1)), [])useEffect(() => {const host = hostRef.currentif (!host || failed) return+ // No cell argument: the component never CREATES a context, it only adopts one.const ctx = ensureLiveContext()if (!ctx) returnconst canvas = ctx.canvas@@ -500,7 +546,7 @@ export function SharedGlyphLayer(): JSX.Element {// (a project switch must not cost a context rebuild). Only `failSharedGlyph` and a font// change dispose it.}- }, [generation, failed])+ }, [generation, failed, contextTick])return (<divdiff --git a/src/renderer/glyphgrid/atlas.test.ts b/src/renderer/glyphgrid/atlas.test.tsindex 36decbc97..a27be3aaa 100644--- a/src/renderer/glyphgrid/atlas.test.ts+++ b/src/renderer/glyphgrid/atlas.test.ts@@ -63,15 +63,54 @@ describe('GlyphAtlas', () => {// (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 / 10)+ 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]) {- const u0 = (slot % cols) * cellUv[0]- const v0 = Math.floor(slot / cols) * cellUv[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] })}})+ // The defect this split exists for: the atlas used to be built from its OWN `measureText`+ // metrics, rounded up to whole texels, while the grid draws each cell at xterm's exact device+ // cell — so every glyph was stretched over a quad a couple of percent smaller than its bitmap+ // and resampled ("rougher than the DOM renderer"). Now the sampled EXTENT is the exact+ // (fractional) cell and only the slot PITCH rounds.+ describe('fractional device cells (xterm reports charWidth * dpr, which is not an integer)', () => {+ it('keeps the sampled extent exact and rounds only the slot pitch', () => {+ const atlas = new GlyphAtlas(fakeRasterizer(15.66, 31), 2048)+ expect(atlas.cellW).toBe(15.66) // extent: unrounded, so texel:pixel is 1:1 at zoom 1+ expect(atlas.strideX).toBe(16) // pitch: whole texels+ expect(atlas.cellH).toBe(31)+ expect(atlas.strideY).toBe(31)+ const rect = atlas.slotRect(1)+ expect(rect.u1 - rect.u0).toBeCloseTo(15.66 / 2048, 12)+ expect(rect.u0).toBeCloseTo(16 / 2048, 12) // …starting on a texel boundary+ })++ it('lays slots out on the pitch, so no two glyphs share a boundary texel', () => {+ const r = fakeRasterizer(15.66, 31)+ const atlas = new GlyphAtlas(r, 2048)+ atlas.glyphFor(0x41, false, false) // slot 1+ atlas.glyphFor(0x42, false, false) // slot 2+ expect(r.calls[0]).toBe(`${0x41}|@16,0`)+ expect(r.calls[1]).toBe(`${0x42}|@32,0`)+ })++ it('counts capacity in whole pitches — the gutter is not usable area', () => {+ // floor(100/16) = 6 cols, floor(100/31) = 3 rows.+ expect(new GlyphAtlas(fakeRasterizer(15.66, 31), 100).capacity).toBe(18)+ })++ it('a sub-texel cell still yields a finite pitch rather than an infinite capacity', () => {+ const atlas = new GlyphAtlas(fakeRasterizer(0.4, 0.4), 100)+ expect(atlas.strideX).toBe(1)+ expect(atlas.capacity).toBe(10000)+ })+ })+it('a degenerate page (sizePx < cellW) yields blank slots and a zero rect, never NaN', () => {const atlas = new GlyphAtlas(fakeRasterizer(10, 20), 5)expect(atlas.capacity).toBe(0)diff --git a/src/renderer/glyphgrid/atlas.ts b/src/renderer/glyphgrid/atlas.tsindex 005976ae7..1b5773145 100644--- a/src/renderer/glyphgrid/atlas.ts+++ b/src/renderer/glyphgrid/atlas.ts@@ -24,13 +24,16 @@ export class GlyphAtlas {private pageSizePx = 1024) {}- /** The three metrics `GlyphGL.uploadAtlas` needs to map a slot index to texels. They are+ /** The 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}+ /** The SAMPLED extent of a slot, in texels: exactly the device cell the grids draw with, which+ * is fractional in general (xterm's `device.cell.width` is `charWidth * dpr`). Keeping it+ * exact is what makes the texel:pixel mapping 1:1 at zoom 1 — see `strideX`. */get cellW(): number {return this.rasterizer.cellW}@@ -38,9 +41,31 @@ export class GlyphAtlas {return this.rasterizer.cellH}+ /**+ * The slot PITCH, in whole texels — the cell rounded UP, so consecutive slots never share a+ * texel.+ *+ * Pitch and extent are separate for one reason. Rounding the CELL to whole texels (what this+ * atlas used to do) means a glyph rasterized into N texels is drawn onto a quad of N±0.5+ * device pixels: the GPU resamples every glyph by a couple of percent, which is precisely the+ * "rougher than the DOM renderer" report. Rounding only the PITCH keeps the extent exact —+ * texel:pixel 1:1 — while still starting every slot on a texel boundary, which matters because+ * a fractional origin would put two neighbouring glyphs' anti-aliasing in the SAME boundary+ * texel, and a full-block glyph would then bleed a dim column into an unrelated slot.+ *+ * The `max(1, …)` is not decoration: a pitch of 0 makes `capacity` infinite and `cellXY`'s+ * modulo NaN.+ */+ get strideX(): number {+ return Math.max(1, Math.ceil(this.rasterizer.cellW))+ }+ get strideY(): number {+ return Math.max(1, Math.ceil(this.rasterizer.cellH))+ }+get capacity(): number {- const cols = Math.floor(this.sizePx / this.rasterizer.cellW)- const rows = Math.floor(this.sizePx / this.rasterizer.cellH)+ const cols = Math.floor(this.sizePx / this.strideX)+ const rows = Math.floor(this.sizePx / this.strideY)return cols * rows}@@ -51,15 +76,15 @@ export class GlyphAtlas {* either the page metrics or the padding changed, and the symptom is every glyph rendering* a fraction of a cell off — not a crash, just permanently wrong text.*- * On a DEGENERATE page (`sizePx < cellW`, so `cols === 0`) `slot % 0` is NaN, which would+ * On a DEGENERATE page (`sizePx < strideX`, so `cols === 0`) `slot % 0` is NaN, which would* propagate silently into the uv rect. Capacity is 0 there, so no slot is ever allocated and* the origin is simply (0,0) — the blank slot. */private cellXY(slot: number): { x: number; y: number } {- const cols = Math.floor(this.sizePx / this.rasterizer.cellW)+ const cols = Math.floor(this.sizePx / this.strideX)if (cols <= 0) return { x: 0, y: 0 }return {- x: (slot % cols) * this.rasterizer.cellW,- y: Math.floor(slot / cols) * this.rasterizer.cellH+ x: (slot % cols) * this.strideX,+ y: Math.floor(slot / cols) * this.strideY}}@@ -79,6 +104,9 @@ export class GlyphAtlas {return slot}+ /** The uv rect of a slot: the ORIGIN follows the whole-texel pitch, the SIZE is the exact+ * cell — the two are not the same number (see `strideX`), and the shader derives its uv the+ * same way (`uAtlasStride` for the origin, `uAtlasCell` for the extent). */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/camera.test.ts b/src/renderer/glyphgrid/camera.test.tsindex 0bf289b06..5813b936c 100644--- a/src/renderer/glyphgrid/camera.test.ts+++ b/src/renderer/glyphgrid/camera.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'import {rectsIntersect,screenToWorld,+ snapPanToDevicePx,visibleWorldRect,worldToScreen,type Camera@@ -34,3 +35,51 @@ describe('glyphgrid camera', () => {expect(rectsIntersect(a, { x: 20, y: 20, w: 1, h: 1 })).toBe(false)})})++describe('snapPanToDevicePx', () => {+ it('rounds the pan to whole device pixels, in CSS units', () => {+ // dpr 2: the CSS-px pan lands on halves, which is where a device pixel actually is.+ expect(snapPanToDevicePx({ x: 10.3, y: -4.4, zoom: 1 }, 2)).toEqual({+ x: 10.5,+ y: -4.5,+ zoom: 1+ })+ expect(snapPanToDevicePx({ x: 10.3, y: -4.4, zoom: 1 }, 1)).toEqual({ x: 10, y: -4, zoom: 1 })+ })++ it('never moves the world by as much as a device pixel', () => {+ for (const dpr of [1, 1.5, 2, 3]) {+ for (const x of [0, 0.1, 12.49, -12.49, 1234.567, -0.5]) {+ const snapped = snapPanToDevicePx({ x, y: x, zoom: 1 }, dpr)+ expect(Math.abs(snapped.x - x) * dpr).toBeLessThanOrEqual(0.5 + 1e-9)+ }+ }+ })++ it('leaves the ZOOM alone — quantizing a scale would step visibly and fix nothing', () => {+ expect(snapPanToDevicePx({ x: 0, y: 0, zoom: 1.234567 }, 2).zoom).toBe(1.234567)+ })++ it('is idempotent, so a still camera cannot drift frame to frame', () => {+ const once = snapPanToDevicePx({ x: 10.3, y: -4.4, zoom: 1 }, 2)+ expect(snapPanToDevicePx(once, 2)).toEqual(once)+ })++ it('passes through when the dpr is unknown rather than rounding to NaN', () => {+ for (const dpr of [0, -1, NaN, Infinity]) {+ expect(snapPanToDevicePx({ x: 10.3, y: -4.4, zoom: 1 }, dpr)).toEqual({+ x: 10.3,+ y: -4.4,+ zoom: 1+ })+ }+ })++ it('returns a COPY — the GL layer holds it for the whole frame', () => {+ const cam: Camera = { x: 1, y: 2, zoom: 1 }+ const snapped = snapPanToDevicePx(cam, 2)+ expect(snapped).not.toBe(cam)+ cam.x = 999+ expect(snapped.x).toBe(1)+ })+})diff --git a/src/renderer/glyphgrid/camera.ts b/src/renderer/glyphgrid/camera.tsindex 3d57959a5..a9a770ad9 100644--- a/src/renderer/glyphgrid/camera.ts+++ b/src/renderer/glyphgrid/camera.ts@@ -27,6 +27,32 @@ export function visibleWorldRect(cam: Camera, viewW: number, viewH: number): Recreturn { x: tl.x, y: tl.y, w: viewW / cam.zoom, h: viewH / cam.zoom }}+/**+ * Snap a camera's PAN to whole DEVICE pixels. The zoom is returned untouched.+ *+ * The glyph atlas is sampled with NEAREST magnification, so where a cell's quad lands within the+ * device-pixel grid decides which texel each screen pixel takes. A pan carrying a sub-device-pixel+ * fraction re-rolls that choice EVERY frame: during a drag the same glyph is resampled slightly+ * differently sixty times a second, and the text ripples behind node chrome that is moving+ * rigidly — the "our text waves while the node doesn't" report. Rounding shifts the whole world by+ * at most half a device pixel (invisible, and constant while the camera is still) and locks the+ * texel alignment for the duration of the pan.+ *+ * The ZOOM is deliberately NOT snapped: it is a scale, not an offset. Quantizing it would step+ * visibly while zooming and would still leave the cell PITCH fractional, so it buys nothing.+ *+ * A non-finite or non-positive dpr (a mocked GL surface, a browser mid-monitor-switch) means+ * "device pixels are unknown here" — pass the camera through rather than round to NaN.+ */+export function snapPanToDevicePx(cam: Camera, dpr: number): Camera {+ if (!Number.isFinite(dpr) || dpr <= 0) return { x: cam.x, y: cam.y, zoom: cam.zoom }+ return {+ x: Math.round(cam.x * dpr) / dpr,+ y: Math.round(cam.y * dpr) / dpr,+ zoom: cam.zoom+ }+}+/** Strict overlap (shared edge does not count — an edge-touching grid draws zero pixels). */export function rectsIntersect(a: Rect, b: Rect): boolean {return a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.hdiff --git a/src/renderer/glyphgrid/engine.test.ts b/src/renderer/glyphgrid/engine.test.tsindex 26437612f..2a8641b8b 100644--- a/src/renderer/glyphgrid/engine.test.ts+++ b/src/renderer/glyphgrid/engine.test.ts@@ -271,7 +271,9 @@ describe('GlyphGridEngine', () => {e.register(spec('a', 0))a.glyphFor(0x41, false, false) // dirties the atlasexpect(e.frame()).toBe(true)- expect(gl.uploadAtlas).toHaveBeenCalledWith(source, 512, 7, 15)+ // …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)// 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/glyphgrid/engine.ts b/src/renderer/glyphgrid/engine.tsindex affff70d9..9e9bfa0ed 100644--- a/src/renderer/glyphgrid/engine.ts+++ b/src/renderer/glyphgrid/engine.ts@@ -338,7 +338,9 @@ export class GlyphGridEngine {this.atlas.source,this.atlas.sizePx,this.atlas.cellW,- this.atlas.cellH+ this.atlas.cellH,+ this.atlas.strideX,+ this.atlas.strideY)this.atlas.clearDirty()this.atlasUploaded = truediff --git a/src/renderer/glyphgrid/gl-webgl2.ts b/src/renderer/glyphgrid/gl-webgl2.tsindex f435888aa..3253e3152 100644--- a/src/renderer/glyphgrid/gl-webgl2.ts+++ b/src/renderer/glyphgrid/gl-webgl2.ts@@ -1,4 +1,4 @@-import type { Camera } from './camera'+import { snapPanToDevicePx, type Camera } from './camera'import { CELL_STRIDE, unpackColor } from './cells'import type { GlyphGL, GridDrawParams } from './gl'import { plateRectDevice } from './plate'@@ -11,7 +11,8 @@ uniform vec2 uView; // viewport size (screen px)uniform vec2 uGridOrigin; // grid top-left (world px)uniform vec2 uCell; // cell size (world px)uniform float uCols;-uniform vec2 uAtlasCell; // glyph uv size (u1-u0, v1-v0)+uniform vec2 uAtlasCell; // glyph uv EXTENT (u1-u0, v1-v0) — the exact device cell+uniform vec2 uAtlasStride; // glyph uv PITCH — the whole-texel slot spacing (>= uAtlasCell)uniform float uAtlasCols;in uvec4 aCell; // [glyph, fg, bg, flags] — CELL_STRIDE lanesout vec2 vUv;@@ -27,7 +28,7 @@ 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);- vec2 slotOrigin = vec2(mod(slot, uAtlasCols), floor(slot / uAtlasCols)) * uAtlasCell;+ vec2 slotOrigin = vec2(mod(slot, uAtlasCols), floor(slot / uAtlasCols)) * uAtlasStride;vUv = slotOrigin + unit * uAtlasCell;vCell = aCell;}`@@ -73,6 +74,7 @@ export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {const atlasTex = gl.createTexture()let atlasCols = 1let atlasCellUv: [number, number] = [0, 0]+ let atlasStrideUv: [number, number] = [0, 0]let view: [number, number] = [1, 1]/** Stored at resize because the plate's scissor rect is in DEVICE pixels and needs the* drawing buffer's height to flip Y — neither is derivable from the CSS-px viewport alone. */@@ -126,13 +128,16 @@ export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {deviceH = canvas.heightgl.viewport(0, 0, canvas.width, canvas.height)},- uploadAtlas(source, sizePx, cellW, cellH) {+ uploadAtlas(source, sizePx, cellW, cellH, strideX, strideY) {gl.bindTexture(gl.TEXTURE_2D, atlasTex)gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source)gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)- atlasCols = Math.floor(sizePx / cellW)+ // Columns follow the PITCH (that is how the atlas laid the page out), while the sampled+ // extent stays the exact cell — mixing the two shifts every glyph by a fraction of a cell.+ atlasCols = Math.floor(sizePx / strideX)atlasCellUv = [cellW / sizePx, cellH / sizePx]+ atlasStrideUv = [strideX / sizePx, strideY / sizePx]},createGrid(id, cols, rows) {// Re-creating under a live id is the RESIZE path: drop the old buffer first, or every@@ -169,17 +174,22 @@ export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {gl.bufferSubData(gl.ARRAY_BUFFER, firstRow * cols * CELL_STRIDE * 4, cells)},beginFrame(camera: Camera) {- // COPIED, not aliased: the plate math reads this during the drawGrid calls that follow,- // and a caller mutating its own camera object mid-frame would move grids apart.- cam = { ...camera }+ // COPIED, not aliased (the plate math reads this during the drawGrid calls that follow, and+ // a caller mutating its own camera object mid-frame would move grids apart) — and SNAPPED:+ // a sub-device-pixel pan makes the NEAREST-sampled atlas resample every glyph differently+ // each frame, which is the shimmer that made panned text look like it was rippling behind+ // its node. See `snapPanToDevicePx`; the plate reads the same snapped camera, so plate and+ // cells can never drift a pixel apart.+ cam = snapPanToDevicePx(camera, dpr)gl.clearColor(0, 0, 0, 0)gl.clear(gl.COLOR_BUFFER_BIT)gl.useProgram(program)- gl.uniform2f(u('uPan'), camera.x, camera.y)- gl.uniform1f(u('uZoom'), camera.zoom)+ gl.uniform2f(u('uPan'), cam.x, cam.y)+ gl.uniform1f(u('uZoom'), cam.zoom)gl.uniform2f(u('uView'), view[0], view[1])gl.uniform1f(u('uAtlasCols'), atlasCols)gl.uniform2f(u('uAtlasCell'), atlasCellUv[0], atlasCellUv[1])+ gl.uniform2f(u('uAtlasStride'), atlasStrideUv[0], atlasStrideUv[1])gl.uniform1i(u('uAtlas'), 0)},drawGrid(g: GridDrawParams) {diff --git a/src/renderer/glyphgrid/gl.ts b/src/renderer/glyphgrid/gl.tsindex b050a1487..ab9975a1d 100644--- a/src/renderer/glyphgrid/gl.ts+++ b/src/renderer/glyphgrid/gl.ts@@ -37,7 +37,17 @@ export interface GridDrawParams {export interface GlyphGL {/** w/h in CSS px, dpr the device pixel ratio — sizes the backing store and the viewport. */resize(w: number, h: number, dpr: number): void- uploadAtlas(source: TexImageSource, sizePx: number, cellW: number, cellH: number): void+ /** `cellW/cellH` are the SAMPLED extent of a slot (the exact device cell, fractional in+ * general); `strideX/strideY` are the whole-texel slot pitch the atlas laid the page out on.+ * They differ by under a texel and must not be conflated — see `GlyphAtlas.strideX`. */+ uploadAtlas(+ source: TexImageSource,+ sizePx: number,+ cellW: number,+ cellH: number,+ strideX: number,+ strideY: number+ ): void/** Allocate the grid's GPU-side cell buffer (cols*rows*CELL_STRIDE uint32s, zeroed).* Re-calling with the same id REALLOCATES — that is the resize path. */createGrid(id: string, cols: number, rows: number): voiddiff --git a/src/renderer/glyphgrid/raster.ts b/src/renderer/glyphgrid/raster.tsindex f99404307..a5077ce73 100644--- a/src/renderer/glyphgrid/raster.ts+++ b/src/renderer/glyphgrid/raster.ts@@ -3,10 +3,42 @@ import type { GlyphRasterizer } from './atlas'export interface RasterFont {family: stringsizePx: number+ /** The cell, in DEVICE pixels — xterm's own `dimensions.device.cell`, NOT a metric measured+ * here. Fractional widths are expected and must not be rounded on the way in: the atlas's+ * whole-texel slot pitch is derived separately (`GlyphAtlas.strideX`), and rounding the cell+ * is what rescales every glyph against the quad it is drawn onto. */cellW: numbercellH: number}+/**+ * Where the alphabetic baseline sits inside the cell, in device px.+ *+ * The rule a CSS line box uses — HALF-LEADING: the font's natural line box (ascent + descent) is+ * centered in the cell and the baseline falls `ascent` below that box's top. xterm's DOM renderer+ * is a stack of divs with `line-height` set to the cell height, so this is literally where its+ * glyphs land; deriving the same number is what keeps the shared renderer from drawing every row+ * a couple of pixels off from the renderer it replaces.+ *+ * `fontBoundingBox*` is optional in the spec, so the old fixed `0.8 * cellH` stays as the+ * fallback — it is within a pixel for the usual monospace faces, and a missing metric must not+ * mean "no text".+ *+ * Clamped into the cell: a font whose line box is much taller than the cell would otherwise put+ * the baseline outside the slot, and every draw is clipped to it (see below) — the glyph would+ * simply vanish.+ */+function baselineIn(ctx: OffscreenCanvasRenderingContext2D, font: RasterFont): number {+ ctx.font = `${font.sizePx}px ${font.family}`+ const m = ctx.measureText('W')+ const asc = m.fontBoundingBoxAscent+ const desc = m.fontBoundingBoxDescent+ const fallback = Math.round(font.cellH * 0.8)+ if (!Number.isFinite(asc) || !Number.isFinite(desc) || asc + desc <= 0) return fallback+ const baseline = Math.round((font.cellH - (asc + desc)) / 2 + asc)+ return Math.max(1, Math.min(Math.ceil(font.cellH), baseline))+}+/** Draws WHITE glyphs (the shader tints); baseline-centered in the cell like xterm's renderers.* Returns null when OffscreenCanvas 2D is unavailable — caller keeps the DOM renderer.*@@ -28,7 +60,7 @@ export function createCanvasRasterizer(if (!ctx) return nullctx.textBaseline = 'alphabetic'ctx.fillStyle = '#ffffff'- const baseline = Math.round(font.cellH * 0.8) // near xterm's metric; harness-verified+ const baseline = baselineIn(ctx, font)return {cellW: font.cellW,cellH: font.cellH,diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex b89b18acc..7169ab20b 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -350,14 +350,39 @@ function hostPadding(el: HTMLElement): Insets {* renderer it already has.*/function cssCellOf(term: Terminal): { cellW: number; cellH: number } | null {+ return cellOf(term, 'css')+}++/**+ * xterm's DEVICE cell — the number of physical pixels one cell occupies at zoom 1, which is what+ * the shared ATLAS must rasterize into.+ *+ * The engine draws a cell as `css.cell × zoom` onto a dpr-scaled buffer, so at zoom 1 the quad is+ * exactly this many device pixels; an atlas slot measured any other way is stretched over it and+ * every glyph is resampled (see `DeviceCell` in the shared layer). Fractional by nature+ * (`charWidth * dpr`) and deliberately handed over UNROUNDED — the atlas rounds only its slot+ * PITCH, never the sampled extent.+ */+function deviceCellOf(term: Terminal): { cellW: number; cellH: number } | null {+ return cellOf(term, 'device')+}++/** The guarded read behind both cell accessors. Private API, fully guarded: null simply means+ * "don't register", i.e. this terminal keeps the renderer it already has. */+function cellOf(term: Terminal, space: 'css' | 'device'): { cellW: number; cellH: number } | null {try {- const cell = (+ const dims = (term as unknown as {_core?: {- _renderService?: { dimensions?: { css?: { cell?: { width: number; height: number } } } }+ _renderService?: {+ dimensions?: Partial<+ Record<'css' | 'device', { cell?: { width: number; height: number } }>+ >+ }}}- )._core?._renderService?.dimensions?.css?.cell+ )._core?._renderService?.dimensions+ const cell = dims?.[space]?.cellif (!cell) return nullreturn validCellSize(cell.width, cell.height)} catch {@@ -1115,7 +1140,13 @@ export function TerminalNode({// failed, and a context that actually exists — no WebGL2/OffscreenCanvas returns null here// and this terminal simply stays where it is.if (!sharedGlyphActive()) return- const ctx = getSharedGlyphContext()+ // The shared atlas rasterizes at xterm's DEVICE cell, and this is where that number enters+ // the layer: the FIRST terminal to ask builds the context and fixes the atlas geometry for+ // its lifetime (font settings are global, so every terminal computes the same cell). Passing+ // it is not optional — with no live context and no cell there is nothing to build an atlas+ // 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) returnconst host = term.elementconst cell = forcedCell ?? cssCellOf(term)diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 678bf5d0f..e67c8db8e 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -1624,10 +1624,12 @@ body,The class is on the root only while a grid is ACTUALLY attached, so collapse, the ⌘M view, afailed attach and every default renderer mode leave the node opaque exactly as today.- Nothing else needs restoring: every child that covers ground outside the plate already paints its- own background (`.term-node__header` var(--panel-header), `.node-tags` var(--panel),- `.term-node__find` #2a2a2a, and the body's own overlays). The selection ring and the unread glow- are border-color + box-shadow, both independent of the background.+ Every child that covers ground outside the plate must therefore paint its OWN background:+ `.term-node__header` var(--panel-header), `.term-node__labelrow` var(--panel),+ `.term-node__find` #2a2a2a, plus the body's own overlays. That list is a contract, not an+ observation — the label row was missing from it (it replaced the old `.node-tags`, which had a+ background) and the strip under the header showed the raw canvas through the node. The selection+ ring and the unread glow are border-color + box-shadow, both independent of the background.Accepted degradations, all plate GEOMETRY, all Phase 2's call (a rounded / stencilled plate, ora plate sized to the BODY rect instead of the grid rect) and all judged on the device checklist.@@ -7493,6 +7495,17 @@ body,align-items: center;gap: 4px;padding: 2px 8px 5px;+ /* Its OWN background, not one inherited from the node root. Visually identical to what it had+ before (the root is var(--panel) too) — but the shared glyph renderer makes that root+ TRANSPARENT so the GPU canvas can show through the body (`.term-node--glyphgrid`), while this+ row sits ABOVE the grid's opaque plate, which only starts at the terminal screen. Without a+ background of its own the whole strip between the header and the terminal became a window onto+ the canvas: the reported "gap under the header, in the label row", which also made the+ terminal's text look like it began well below where the DOM renderer put it. Every other child+ of the node paints its own background for exactly this reason (`.term-node__header`,+ `.term-node__find`); this one was missed because it replaced the old `.node-tags` row, which+ had one. */+ background: var(--panel);}.term-node__labeladd {background: rgba(255, 255, 255, 0.06);