Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(glyphgrid): rebuild the atlas when the display's pixel ratio changes

enes3c12ec61add1
diff --git a/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md b/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md
index 876413861..0b8eeb518 100644
--- a/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md
+++ b/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md
@@ -387,9 +387,19 @@ Auto after you switched builds, that is why: re-select Shared and carry on.
duplicate grid, no transparent-but-empty body.
- [ ] **4.14 Alt-screen transitions.** Enter and leave a fullscreen TUI (`htop`, an agent CLI) a
few times: no flicker of a doubled screen, no leftover rows from the previous screen.
-- [ ] **4.15 dpr change.** Drag the window between the retina display and an external 1x monitor
- (both directions): geometry stays correct (the drawing buffer follows), text may soften
- slightly (atlas is not rebuilt — Phase 2), and nothing re-registers or fails.
+- [ ] **4.15 dpr change — the atlas is now REBUILT.** Drag the window between the retina display
+ and an external 1x monitor, **both directions, and then back again**. Expected: geometry
+ stays correct (the drawing buffer follows), and the text on the new display is as sharp as a
+ terminal opened there fresh. Soft or over-sharp text after the move is now a FAILURE, not the
+ documented behaviour — that was L10, and this item is what closes it.
+ **What the rebuild costs, so it is not mis-filed as a bug.** It is the font-change path: the
+ shared context is disposed and every terminal re-registers its grid. One repaint of the whole
+ canvas at the moment of the move is expected, and a brief flash of DOM-rendered text is fine.
+ A terminal left blank, transparent-but-empty, or stuck on the DOM renderer is not.
+ **Report specifically:** any `[glyphgrid] atlas cell … does not match …` line in the console
+ after a move — that is a grid registering against a measurement taken on the display we left
+ (see `deviceCellOf`), and it means the rebuild adopted the OLD cell — and whether the SECOND
+ move rebuilds again or the fix latches after the first one.
- [ ] **4.16 Kanban board.** Open the board over a shared-mode project: the board is fully opaque
(no glyphs showing through), and the idle rAF cost is not noticeable (check CPU/GPU while
the board is up with terminals idle).
@@ -507,9 +517,6 @@ Auto after you switched builds, that is why: re-select Shared and carry on.
- **L9 — A failure is permanent for the session.** A GL error or a lost context disables the shared
renderer until the app is relaunched; there is no restore path in Phase 1b (deliberate — a retry
loop on a bad driver is how you turn one failure into a flicker).
-- **L10 — The atlas is not rebuilt on a dpr change.** Moving the window to a display with a
- different dpr leaves the glyphs rasterized for the old one (slightly soft or over-sampled).
- Geometry is unaffected — the drawing buffer follows the dpr on every resize.
- **L11 — Grids keep drawing while the kanban board covers the canvas.** The board overlay is
opaque, so nothing is visible; it is wasted work, measured by item 4.16 and closed in Phase 2 if
it shows up.
@@ -521,15 +528,15 @@ Auto after you switched builds, that is why: re-select Shared and carry on.
- **L14 — The atlas cell and the baseline latch to the FIRST terminal's usable measurement.** The
atlas is rasterized into xterm's own `dimensions.device.cell`, handed over by whichever terminal
builds the shared context first, and the baseline is derived from that same font at that moment.
- Two consequences. A **webfont that resolves later** leaves the atlas on the fallback face's
- metrics for the life of the context — the text is measured and placed correctly, just against the
- wrong face's cell — until something disposes the context (a font-family/size change in Settings;
- L10's dpr change does not). And a terminal whose device cell **diverges** from the atlas's (a dpr
- change under a live context, a per-terminal letterSpacing) has its glyphs resampled against the
- quad they are drawn onto, i.e. slightly soft — never misplaced. Both are announced:
- `warnOnCellDrift` logs one `[glyphgrid] atlas cell … does not match …` line per context lifetime,
- so a soft terminal can be told apart from a soft display. Phase 2 (re-rasterize on
- `document.fonts.ready` / per-cell atlas pages).
+ A **webfont that resolves later** therefore leaves the atlas on the fallback face's metrics for
+ the life of the context — the text is measured and placed correctly, just against the wrong
+ face's cell — until something disposes the context (a font-family/size change in Settings, or the
+ dpr rebuild of item 4.15). A terminal whose device cell **diverges** from the atlas's for any
+ other reason (a per-terminal letterSpacing) has its glyphs resampled against the quad they are
+ drawn onto, i.e. slightly soft — never misplaced. Both are announced: `warnOnCellDrift` logs one
+ `[glyphgrid] atlas cell … does not match …` line per context lifetime, so a soft terminal can be
+ told apart from a soft display. Phase 2 (re-rasterize on `document.fonts.ready` / per-cell atlas
+ pages).
**Phase 1c narrows what is latched.** The FACE never was: `ctx.font` is set per draw, so any slot
rasterized after a webfont resolves already uses the real face. What used to make that invisible is
diff --git a/src/renderer/canvas/SharedGlyphLayer.test.ts b/src/renderer/canvas/SharedGlyphLayer.test.ts
index d30392373..26fa010cd 100644
--- a/src/renderer/canvas/SharedGlyphLayer.test.ts
+++ b/src/renderer/canvas/SharedGlyphLayer.test.ts
@@ -14,6 +14,7 @@ import {
nodeStackZ,
nodeZFor,
opaqueNodeIds,
+ pixelRatioChanged,
primeOpaqueNodeIds,
setNodeZOrder,
setOpaqueNodeIds,
@@ -22,6 +23,7 @@ import {
sharedGlyphAvailable,
subscribeNodeZOrder,
subscribeOpaqueSet,
+ syncAtlasPixelRatio,
useSharedGlyph,
type AtlasResetSource,
type StackedNode,
@@ -960,6 +962,87 @@ describe('sharedGlyphAvailable', () => {
})
})
+/**
+ * The dpr rebuild. The atlas cell and the baseline are latched at construction, so a window that
+ * moves between a retina and a 1x display keeps a page rasterized for the display it LEFT — soft on
+ * one, over-sharp on the other, for the life of the context. Nothing downstream rescues it: the
+ * grids register with the CSS cell, which is dpr-invariant, so no re-registration is triggered by
+ * the move. Only a rebuild re-rasterizes, and the rebuild is the FONT change's funnel with a
+ * different trigger.
+ */
+describe('pixelRatioChanged', () => {
+ it('is false for the ratio the atlas was built at', () => {
+ expect(pixelRatioChanged(2, 2)).toBe(false)
+ })
+
+ it('is true in both directions — retina to 1x and back', () => {
+ expect(pixelRatioChanged(2, 1)).toBe(true)
+ expect(pixelRatioChanged(1, 2)).toBe(true)
+ })
+
+ it('ignores float noise — a rebuild costs every grid on the canvas', () => {
+ expect(pixelRatioChanged(2, 2 + 1e-9)).toBe(false)
+ })
+
+ it('sees the fractional ratios a scaled display reports', () => {
+ expect(pixelRatioChanged(2, 1.5)).toBe(true)
+ expect(pixelRatioChanged(1.25, 1.5)).toBe(true)
+ })
+
+ it('treats an unreadable ratio as unchanged, never as a reason to rebuild', () => {
+ // 0 / NaN come out of a detached window or a broken shim. The atlas we have is the one the
+ // display we are on asked for; throwing it away on a bad reading is strictly worse than
+ // keeping it.
+ expect(pixelRatioChanged(2, 0)).toBe(false)
+ expect(pixelRatioChanged(2, NaN)).toBe(false)
+ expect(pixelRatioChanged(2, -1)).toBe(false)
+ expect(pixelRatioChanged(2, Infinity)).toBe(false)
+ })
+})
+
+describe('syncAtlasPixelRatio', () => {
+ /** The structural stand-in for a live context — the same trick `AtlasResetSource` uses, so the
+ * rebuild decision is exercisable without a GPU. In production `disposed` is flipped by
+ * `disposeContext()` itself, which is what makes the re-entry guard below real. */
+ const ctx = (dpr: number, disposed = false): { dpr: number; disposed: boolean } => ({
+ dpr,
+ disposed
+ })
+
+ it('does nothing while the display has not changed', () => {
+ expect(syncAtlasPixelRatio(2, ctx(2))).toBe(false)
+ expect(useSharedGlyph.getState().generation).toBe(0)
+ })
+
+ it('rebuilds on a change, bumping the generation EXACTLY once', () => {
+ // One bump, because that is the signal every mounted terminal re-registers on. Two would run
+ // the teardown/setup pair twice for one display change.
+ expect(syncAtlasPixelRatio(1, ctx(2))).toBe(true)
+ expect(useSharedGlyph.getState().generation).toBe(1)
+ })
+
+ it('bumps twice for two distinct changes (2 → 1 → 2), each against the FRESH context', () => {
+ // The second context is a different object because the first was disposed: a display change
+ // that goes there and back must rebuild both times, not latch after the first.
+ expect(syncAtlasPixelRatio(1, ctx(2))).toBe(true)
+ expect(syncAtlasPixelRatio(2, ctx(1))).toBe(true)
+ expect(useSharedGlyph.getState().generation).toBe(2)
+ })
+
+ it('is inert on a context that is already disposed — the re-entry guard', () => {
+ // `pushViewport` runs from the ResizeObserver AND the window `resize` listener, and a display
+ // change fires both. The first disposes; the rest must not bump the epoch again before the
+ // effect has re-run with the fresh context.
+ expect(syncAtlasPixelRatio(1, ctx(2, true))).toBe(false)
+ expect(useSharedGlyph.getState().generation).toBe(0)
+ })
+
+ it('does not rebuild on an unreadable ratio', () => {
+ expect(syncAtlasPixelRatio(0, ctx(2))).toBe(false)
+ expect(useSharedGlyph.getState().generation).toBe(0)
+ })
+})
+
describe('installAtlasResetLog', () => {
/** The atlas surface the log reads, with a manual trigger. */
function fakeAtlas(): {
diff --git a/src/renderer/canvas/SharedGlyphLayer.tsx b/src/renderer/canvas/SharedGlyphLayer.tsx
index 204ceac24..1ad7538be 100644
--- a/src/renderer/canvas/SharedGlyphLayer.tsx
+++ b/src/renderer/canvas/SharedGlyphLayer.tsx
@@ -644,6 +644,9 @@ interface LiveContext extends SharedGlyphContext {
resetLog: GlyphAtlasSubscription
/** Font settings this context was rasterized for — a change tears it down. */
fontKey: string
+ /** The display pixel ratio the atlas was rasterized at — a change tears it down too, through the
+ * SAME funnel, because the atlas cell is device-sized and latched at construction. */
+ dpr: number
/** Set by `disposeContext`, read by the rAF driver, which holds this object across a frame.
* Teardown is SYNCHRONOUS (a settings change, the mode being switched off) and can land
* between a scheduled tick and its callback — a frame submitted after `gl.dispose()` would
@@ -667,6 +670,12 @@ function fontKeyOf(fontFamily: string, fontSize: number): string {
return `${fontFamily}|${fontSize}`
}
+/** The display's pixel ratio, guarded for the environments that have no `window` (the test suite)
+ * or report nothing useful. */
+function currentDpr(): number {
+ return typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1
+}
+
/** 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. */
@@ -815,14 +824,15 @@ export function installAtlasResetLog(
function createContext(cell: DeviceCell): LiveContext | null {
if (typeof document === 'undefined' || typeof OffscreenCanvas === 'undefined') return null
const { fontFamily, fontSize } = useSettings.getState().settings
- const dpr = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1
+ const dpr = currentDpr()
// The atlas is rasterized at DEVICE resolution: the addon reports device-pixel cells, and a
- // CSS-sized atlas would be visibly soft on every retina display. The dpr is read ONCE, and
- // deliberately does not join the font key: moving the window to a monitor with a different dpr
- // leaves the glyphs rasterized for the old one (slightly soft or slightly over-sampled), which
- // is a Phase-2 sharpness question — rebuilding the atlas there would drop and re-register every
- // 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.
+ // CSS-sized atlas would be visibly soft on every retina display. The dpr is read ONCE and LATCHED
+ // (below, on the context) precisely because it cannot be changed afterwards — the cell, the
+ // baseline and every slot already in the page were rasterized for it. Moving the window to a
+ // display with a different ratio therefore disposes this context and rebuilds it, exactly as a
+ // font change does; `syncAtlasPixelRatio` is the trigger and `rebuildSharedContext` is the shared
+ // funnel. The drawing BUFFER follows the dpr independently, on every resize (see the component's
+ // `pushViewport`), so geometry is never wrong even in the frames before the rebuild lands.
const devicePx = Math.max(1, fontSize * dpr)
const { cellW, cellH } = cell
// Rasterizer FIRST: it needs no GPU, so a missing OffscreenCanvas bails out before a WebGL
@@ -851,6 +861,7 @@ function createContext(cell: DeviceCell): LiveContext | null {
gl,
resetLog: installAtlasResetLog(atlas),
fontKey: fontKeyOf(fontFamily, fontSize),
+ dpr,
disposed: false
}
}
@@ -899,6 +910,22 @@ export function failSharedGlyph(reason: string, err?: unknown): void {
useSharedGlyph.setState({ failed: true, generation: useSharedGlyph.getState().generation + 1 })
}
+/**
+ * THE re-rasterize path: drop the context and tell every registered terminal to re-evaluate its
+ * participation, which is how they end up re-registering their grids against a freshly built atlas.
+ *
+ * ONE function, because there is now more than one trigger — a font change and a display pixel
+ * ratio change — and they must be the same event. The order is load-bearing and is the same
+ * contract `setEnabled(false)` and `failSharedGlyph` honour: dispose FIRST, announce SECOND, never
+ * dispose without announcing (every registered grid is holding an inert handle until the bump
+ * arrives) and never announce before disposing (a terminal that re-asked for the context in
+ * between would adopt the very context we are about to delete).
+ */
+function rebuildSharedContext(): void {
+ disposeContext()
+ useSharedGlyph.getState().bumpGeneration()
+}
+
/** Rebuild on a terminal font change: the atlas is rasterized for one font, so a new one means a
* new atlas — and the engine's grids are re-registered by their owners on the generation bump.
*
@@ -910,11 +937,66 @@ function ensureSettingsSubscription(): void {
settingsUnsub = useSettings.subscribe((s) => {
if (!live) return
if (live.fontKey === fontKeyOf(s.settings.fontFamily, s.settings.fontSize)) return
- disposeContext()
- useSharedGlyph.getState().bumpGeneration()
+ rebuildSharedContext()
})
}
+/** Below this, a difference between two pixel ratios is float noise. Real values are far apart
+ * (1, 1.25, 1.5, 2, 3) and nothing legitimately moves one by a thousandth, while a rebuild costs a
+ * dropped and re-registered grid on every terminal on the canvas. */
+const DPR_EPS = 0.001
+
+/**
+ * Has the display's pixel ratio moved away from the one the atlas was rasterized at?
+ *
+ * `current` is `window.devicePixelRatio`, which is not a trustworthy number in every environment
+ * (0 on a detached window, NaN through a hostile shim). An unreadable ratio answers "unchanged":
+ * the atlas we hold is the one the display we are on asked for, and throwing it away on a bad
+ * reading is strictly worse than keeping it.
+ */
+export function pixelRatioChanged(builtAt: number, current: number): boolean {
+ if (!Number.isFinite(current) || current <= 0) return false
+ return Math.abs(builtAt - current) > DPR_EPS
+}
+
+/** The context surface the dpr reconciliation reads. Structural rather than `LiveContext` — the
+ * same trick `AtlasResetSource` uses — so the rebuild decision is exercisable without a GPU. */
+export interface PixelRatioContext {
+ /** The ratio the atlas was rasterized at. */
+ dpr: number
+ /** Already torn down. */
+ disposed: boolean
+}
+
+/**
+ * Rebuild the atlas when the window has moved to a display with a different pixel ratio.
+ *
+ * WHY A REBUILD, AND WHY NOTHING ELSE FIXES IT. The atlas cell IS xterm's DEVICE cell (see
+ * `DeviceCell`) and the baseline is derived from the same font at the same moment — both latched at
+ * construction, along with every slot already rasterized into the page. So a retina window dragged
+ * onto a 1x display keeps a page drawn at twice the resolution its quads are now sampled at, and
+ * the reverse leaves it soft. Nothing downstream rescues that: the grids are registered with the
+ * CSS cell, which is dpr-invariant, so the move triggers no re-registration at all and the page
+ * stays wrong for the life of the context.
+ *
+ * It goes through the font change's funnel deliberately (`rebuildSharedContext`): a dpr change is
+ * the same event with a different trigger, and a second dispose-and-re-register path is a second
+ * place to get the both-renderers invariant wrong.
+ *
+ * Returns whether it rebuilt, so the caller can skip pushing a viewport into a context it has just
+ * disposed.
+ */
+export function syncAtlasPixelRatio(current: number, ctx: PixelRatioContext): boolean {
+ // Re-entry guard. `pushViewport` runs from the ResizeObserver AND the window `resize` listener,
+ // and a display change fires both; `disposeContext()` flips this flag on the context the closure
+ // still holds, so the second call is a no-op instead of a second epoch bump — which would run
+ // teardown/setup twice on every terminal for one display change.
+ if (ctx.disposed) return false
+ if (!pixelRatioChanged(ctx.dpr, current)) return false
+ rebuildSharedContext()
+ return true
+}
+
/** 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
@@ -1047,13 +1129,16 @@ export function SharedGlyphLayer(): JSX.Element {
host.appendChild(canvas)
const pushViewport = (): void => {
+ const dpr = currentDpr()
+ // A display change (the window dragged onto a monitor with a different pixel ratio) arrives
+ // HERE — it fires `resize` with the CSS box unchanged — and it is the one viewport input the
+ // engine cannot absorb, because the ATLAS was rasterized for the old ratio. So it is checked
+ // before the push: on a rebuild the context this closure holds is already gone, and the fresh
+ // one gets its viewport from the re-run effect's own `pushViewport()`.
+ if (syncAtlasPixelRatio(dpr, ctx) || ctx.disposed) return
// The engine change-gates all three inputs, so calling this from every observer tick is
// free when nothing actually moved.
- ctx.engine.setViewport(
- host.clientWidth,
- host.clientHeight,
- typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1
- )
+ ctx.engine.setViewport(host.clientWidth, host.clientHeight, dpr)
}
pushViewport()
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 0484e96f0..6c7048b5c 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -367,9 +367,35 @@ function cssCellOf(term: Terminal): { cellW: number; cellH: number } | null {
* 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.
+ *
+ * **Why this is not simply `dimensions.device.cell`.** The one moment this number is asked for is
+ * the moment it is hardest to read: the shared layer rebuilds its atlas when the window moves to a
+ * display with a different pixel ratio (`syncAtlasPixelRatio`), and the epoch bump that makes this
+ * node re-register rides the window `resize` — while xterm re-measures off its OWN `matchMedia`
+ * dpr listener. Nothing orders those two, so `dimensions.device.cell` can still be the cell of the
+ * display we just LEFT, and an atlas built from it would be rebuilt at the old resolution: the very
+ * defect the rebuild exists to fix, reintroduced one layer down and invisible except as a
+ * `warnOnCellDrift` line.
+ *
+ * The CSS cell is the one that can be trusted across that window, because xterm derives it BY
+ * DIVIDING the device cell by the same dpr (`css.cell.width = device.cell.width / dpr`) — so it is
+ * dpr-invariant, `css × dpr` reproduces the device cell exactly whenever xterm is up to date, and
+ * it is the CORRECT cell when xterm is not. Hence: prefer xterm's own number, and fall back to the
+ * scaled CSS cell only when the two disagree, which is exactly the stale-measurement window.
*/
function deviceCellOf(term: Terminal): { cellW: number; cellH: number } | null {
- return cellOf(term, 'device')
+ const device = cellOf(term, 'device')
+ const css = cellOf(term, 'css')
+ if (!css) return device
+ const dpr = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1
+ const scaled = validCellSize(css.cellW * dpr, css.cellH * dpr)
+ if (!device || !scaled) return device ?? scaled
+ // The slack is a CSS-pixel epsilon carried into device space, so the comparison means the same
+ // thing at every ratio: below it the two readings are the same measurement.
+ const eps = CELL_SIZE_EPS * dpr
+ const agree =
+ Math.abs(device.cellW - scaled.cellW) <= eps && Math.abs(device.cellH - scaled.cellH) <= eps
+ return agree ? device : scaled
}
/** The guarded read behind both cell accessors. Private API, fully guarded: null simply means