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(terminal): re-derive DOM renderer row spacing on reattach

Bas Milius9e450603000b
diff --git a/CLAUDE.md b/CLAUDE.md
index b03bac958..49048e288 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -395,6 +395,16 @@ Lifecycle, by intent:
and `handle.dispose()`s on unmount (which releases + cancels timers). A parked terminal is
off-screen so it holds no context. Permanent-delete paths call `disposeTerminalOnUnmount(id)` so a
deleted node disposes instead of parking.
+ **A renderer released while the node is unmeasurable mismeasures its own row spacing**
+ (`terminal/dom-renderer-spacing.ts`): `WebglAddon.dispose()` is also the back-to-DOM-renderer
+ path, and it runs from the lifecycle effect's CLEANUP — after React detached the element — so the
+ fresh DOM renderer derives `letter-spacing` from a width cache whose `offsetWidth` is **0** and
+ bakes in a whole extra cell per character. That is the "letters drift apart for a split second
+ after a project switch": the adopting mount paints wide until the WebGL grant lands 150 ms later.
+ Focus mode's `display:none` wrapper is the same shape. xterm re-derives the spacing on a char-size
+ / dpr / options change and **not on a resize**, so nothing in the reattach path heals it —
+ `applyFit` calls the change-gated `resyncDomRendererSpacing(term)`, which bails while the
+ measurement is still 0 rather than re-baking the wrong number.
**Which renderer a terminal uses** is `settings.terminalGpuRendering`, resolved by the single
resolver `resolveTerminalRenderer(value)` (`src/shared/webgl.ts`) to `dom | webgl | shared`:
`'off'` = xterm's DOM renderer, `'on'` = one budgeted WebGL context per terminal (everything the
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 4318c8a5d..dc3bce5b7 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -66,6 +66,7 @@ import { useXtermVisualSettings } from '../terminal/useXtermVisualSettings'
import { ensureProjectLaunchInfo } from '../state/projectLaunchInfo'
import { loseWebglContexts, registerWebglClient, type WebglClientHandle } from '../terminal/webgl-budget'
import { quantizeCharSize } from '../terminal/char-size-quantize'
+import { resyncDomRendererSpacing } from '../terminal/dom-renderer-spacing'
import {
PARK_MAX,
armParkExpiry,
@@ -2050,6 +2051,11 @@ export function TerminalNode({
*/
const applyFit = () => {
try {
+ // A DOM renderer built while this node was unmeasurable — the park (its cleanup releases
+ // the webgl grant AFTER React detached the element) or a display:none wrapper — measured a
+ // 0-wide 'W' and baked a full extra cell into its row spacing. This is the first moment it
+ // can be re-derived; a no-op whenever the spacing already agrees. See the helper.
+ if (resyncDomRendererSpacing(term)) fullRepaint()
// Board up → this canvas terminal is hidden behind the overlay. Report "not viewing" (null)
// so a card-modal viewer of the same session drives the grid instead of being clamped to our
// (possibly zoomed-tiny) canvas size. No modal viewer → no size vote at all → the pty simply
diff --git a/src/renderer/terminal/dom-renderer-spacing.test.ts b/src/renderer/terminal/dom-renderer-spacing.test.ts
new file mode 100644
index 000000000..e3b2485cd
--- /dev/null
+++ b/src/renderer/terminal/dom-renderer-spacing.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from 'vitest'
+import type { Terminal } from '@xterm/xterm'
+import { resyncDomRendererSpacing } from './dom-renderer-spacing'
+
+/**
+ * A structural fake of exactly the xterm internals the helper reaches for (the guarded-internals
+ * style `quantizeCharSize` and `restoreDomRenderer` are tested against). `measuredW` is what the
+ * width cache reports: 0 stands for the element not being in the rendered tree — the park /
+ * display:none case the whole helper exists for.
+ */
+function fakeTerm(opts: { cellWidth?: number; defaultSpacing: number; measuredW: number }) {
+ const calls = { charSizeChanged: 0, cacheReads: 0 }
+ const renderer = {
+ dimensions: { css: { cell: { width: opts.cellWidth ?? 8 } } },
+ _rowFactory: { defaultSpacing: opts.defaultSpacing },
+ _widthCache: {
+ get() {
+ calls.cacheReads++
+ return opts.measuredW
+ }
+ },
+ handleCharSizeChanged() {
+ calls.charSizeChanged++
+ renderer._rowFactory.defaultSpacing =
+ renderer.dimensions.css.cell.width - renderer._widthCache.get()
+ }
+ }
+ const term = {
+ _core: { _renderService: { _renderer: { value: renderer } } }
+ } as unknown as Terminal
+ return { term, renderer, calls }
+}
+
+describe('resyncDomRendererSpacing', () => {
+ it('re-derives the spacing a detached renderer baked in (a whole cell too wide)', () => {
+ // Built while unmeasurable: cell.width - 0 = a full cell of letter-spacing.
+ const { term, renderer, calls } = fakeTerm({ cellWidth: 8, defaultSpacing: 8, measuredW: 8.43 })
+ expect(resyncDomRendererSpacing(term)).toBe(true)
+ expect(calls.charSizeChanged).toBe(1)
+ expect(renderer._rowFactory.defaultSpacing).toBeCloseTo(-0.43, 5)
+ })
+
+ it('leaves a terminal whose spacing already agrees completely alone', () => {
+ const { term, calls } = fakeTerm({ cellWidth: 8, defaultSpacing: -0.43, measuredW: 8.43 })
+ expect(resyncDomRendererSpacing(term)).toBe(false)
+ expect(calls.charSizeChanged).toBe(0)
+ })
+
+ it('bails while the element is still unmeasurable, rather than baking the wrong number again', () => {
+ const { term, calls } = fakeTerm({ cellWidth: 8, defaultSpacing: 8, measuredW: 0 })
+ expect(resyncDomRendererSpacing(term)).toBe(false)
+ expect(calls.charSizeChanged).toBe(0)
+ })
+
+ it('bails on a renderer without a width cache (WebGL, the shared glyph addon)', () => {
+ const term = {
+ _core: {
+ _renderService: { _renderer: { value: { handleCharSizeChanged() {}, dimensions: {} } } }
+ }
+ } as unknown as Terminal
+ expect(resyncDomRendererSpacing(term)).toBe(false)
+ })
+
+ it('fails open on missing internals', () => {
+ expect(resyncDomRendererSpacing({} as unknown as Terminal)).toBe(false)
+ expect(
+ resyncDomRendererSpacing({ _core: { _renderService: {} } } as unknown as Terminal)
+ ).toBe(false)
+ })
+
+ it('bails when the cell width is not known yet', () => {
+ const { term, calls } = fakeTerm({ cellWidth: 0, defaultSpacing: 8, measuredW: 8.43 })
+ expect(resyncDomRendererSpacing(term)).toBe(false)
+ expect(calls.charSizeChanged).toBe(0)
+ })
+})
diff --git a/src/renderer/terminal/dom-renderer-spacing.ts b/src/renderer/terminal/dom-renderer-spacing.ts
new file mode 100644
index 000000000..a3655ce37
--- /dev/null
+++ b/src/renderer/terminal/dom-renderer-spacing.ts
@@ -0,0 +1,70 @@
+import type { Terminal } from '@xterm/xterm'
+
+/**
+ * Re-derive the DOM renderer's row spacing once the terminal element is measurable again.
+ *
+ * xterm's DOM renderer does not lay glyphs out on a grid — it pins the advance with CSS
+ * `letter-spacing`, computed ONCE per renderer instance as `cell.width - widthCache('W')`
+ * (`DomRenderer._setDefaultSpacing`). The width cache measures with `offsetWidth`, which is **0**
+ * for an element that is not in the rendered tree — so a DOM renderer built while the node is
+ * detached or `display:none` bakes in `letter-spacing: <a whole cell>` and every character sits a
+ * space too far apart.
+ *
+ * That is not hypothetical: `releaseWebgl` runs from the lifecycle effect's cleanup, i.e. AFTER
+ * React has removed the node's DOM, and `WebglAddon.dispose()` is also the put-xterm-back-on-a-DOM-
+ * renderer path. A project switch therefore parks every terminal with a mismeasured renderer, and
+ * the adopting mount paints it wide until the WebGL grant lands (`WEBGL_ACQUIRE_DEBOUNCE_MS`) —
+ * the visible "letters drift apart for a split second". Focus mode's `display:none` wrapper
+ * reclaims hidden grants the same way.
+ *
+ * xterm recomputes the spacing on a char-size / dpr / options change and NOT on a resize, so
+ * nothing in the normal reattach path heals it. `handleCharSizeChanged()` is the narrowest lever
+ * that does (re-measure, clear the width cache, re-derive the spacing).
+ *
+ * Change-gated, because this runs on every fit: the comparison costs one cached cache read, and a
+ * terminal whose spacing already agrees is left completely alone. A measurement of 0 means the
+ * element is still not rendered — nothing can be derived, so it bails rather than re-baking the
+ * same wrong number. Guarded internals in the same fail-open style as `quantizeCharSize` and
+ * TerminalNode's `restoreDomRenderer`: a future xterm that renames a field silently keeps its
+ * stock behaviour. Only xterm's DOM renderer carries a width cache, so the WebGL renderer and the
+ * shared glyph addon bail on the first gate.
+ *
+ * Returns whether the spacing was actually re-derived (the caller owes a repaint).
+ */
+const SPACING_EPS = 0.01
+
+interface WidthCacheLike {
+ get(char: string, bold: boolean, italic: boolean): number
+}
+interface DomRendererLike {
+ _widthCache?: WidthCacheLike
+ _rowFactory?: { defaultSpacing: number }
+ dimensions?: { css?: { cell?: { width?: number } } }
+ handleCharSizeChanged?(): void
+}
+
+export function resyncDomRendererSpacing(term: Terminal): boolean {
+ try {
+ const renderer = (
+ term as unknown as {
+ _core?: { _renderService?: { _renderer?: { value?: DomRendererLike } } }
+ }
+ )._core?._renderService?._renderer?.value
+ const cache = renderer?._widthCache
+ const factory = renderer?._rowFactory
+ if (!renderer || !cache || !factory || typeof renderer.handleCharSizeChanged !== 'function') {
+ return false
+ }
+ const cellWidth = renderer.dimensions?.css?.cell?.width
+ if (!Number.isFinite(cellWidth) || !cellWidth) return false
+ const measured = cache.get('W', false, false)
+ if (!(measured > 0)) return false
+ if (Math.abs((cellWidth as number) - measured - factory.defaultSpacing) <= SPACING_EPS) {
+ return false
+ }
+ renderer.handleCharSizeChanged()
+ return true
+ } catch {
+ return false
+ }
+}