Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(terminal): fit the cell grid to the font the panes actually draw with

Ruben Lütkea07b7adf72bb
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index 6290128e17..0f0520fe42 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -32,8 +32,10 @@
* * **Measuring before the font is ready.** FitAddon derives the column count
* from one measured character. Run before the web font loads, it measures
* the fallback font, computes the wrong column count, and the agent then
- * formats for a width the pane does not have. Hence the re-fit once
- * `document.fonts.ready` resolves.
+ * formats for a width the pane does not have. Worse, xterm keeps drawing the
+ * real font's wider glyphs into that too-narrow grid, so the text smears
+ * across its own columns. Neither `document.fonts.ready` nor a re-fit fixes
+ * this — see `@/lib/terminalFont`, which does.
* * **Renderer.** The DOM renderer draws each cell as an element; with a TUI
* redrawing on every keystroke that is both slow and subtly misaligned. The
* canvas renderer draws on a grid, which is what a terminal actually is.
@@ -76,6 +78,11 @@ import { attachToTerminal } from "@/lib/agenticIdeApi";
import type { RecapReason, RecapSource } from "@/lib/agenticIdeApi";
import { attachTerminalBridge } from "@/lib/editActions";
import { robustPaste } from "@/lib/clipboard";
+import {
+ TERMINAL_FONT_STACK,
+ alignTerminalCells,
+ syncTerminalFont,
+} from "@/lib/terminalFont";
import { installPasteBridge } from "./terminalPaste";
import { createKeyEventChain } from "./terminalKeyChain";
import { installNewlineBridge } from "./terminalNewline";
@@ -365,8 +372,10 @@ export function AgenticTerminal({
const term = new Terminal({
convertEol: false,
- fontFamily:
- "'JetBrains Mono', 'Fira Code', 'SF Mono', Consolas, 'Courier New', monospace",
+ // Shared with the measurement in ./../../lib/terminalFont: a pane that
+ // measured a different stack from the one it draws with is the bug that
+ // module exists to prevent.
+ fontFamily: TERMINAL_FONT_STACK,
fontSize: initialRef.current.fontSize,
// Roomier than a console default — the single biggest readability win for
// an agent that prints prose, diffs and file trees rather than log lines.
@@ -756,22 +765,17 @@ export function AgenticTerminal({
});
// The mount-time fit measured whatever font was loaded at that moment. If
- // the display font arrives afterwards the cell width changes underneath the
- // already-computed column count, and the agent then formats its output for a
- // width the pane does not have — text wrapping in the wrong places, which is
- // exactly the reported symptom. Re-fit once fonts settle.
- let fontsSettled = false;
- const refitOnFonts = () => {
- if (disposed || fontsSettled) return;
- fontsSettled = true;
+ // the display font arrives afterwards, the cell width changes underneath the
+ // already-computed column count: the agent formats its output for a width
+ // the pane does not have, and every glyph is painted wider than the cell it
+ // owns until the line has drifted a full column out of its grid. Both are
+ // the reported symptom. See ./../../lib/terminalFont for why waiting on
+ // `document.fonts.ready` and re-fitting cannot fix either.
+ const disposeFontSync = syncTerminalFont(term, () => {
+ if (disposed) return;
term.clearTextureAtlas?.();
sendResize();
- };
- if (typeof document !== "undefined" && document.fonts?.ready) {
- void document.fonts.ready.then(refitOnFonts).catch(() => undefined);
- } else {
- refitOnFonts();
- }
+ });
// Resizes are coalesced: dragging a split or the window fires the observer
// dozens of times a second, and every fit both reflows xterm's buffer and
@@ -873,6 +877,7 @@ export function AgenticTerminal({
}
ro.disconnect();
io?.disconnect();
+ disposeFontSync();
disposePasteBridge();
disposeNewlineBridge();
disposeQuerySuppression();
@@ -904,6 +909,10 @@ export function AgenticTerminal({
const term = termRef.current;
if (!term) return;
term.options.fontSize = fontSize;
+ // A new size is a new glyph advance, and so a new fraction of a pixel for
+ // the canvas renderer to floor away. Re-align before the fit below, or the
+ // pane spends this size with its glyphs overhanging their cells.
+ alignTerminalCells(term);
term.clearTextureAtlas?.();
// Changing the font size changes the COLUMN COUNT. Fitting locally without
// telling the terminal process leaves the agent formatting for the old
diff --git a/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.tsx b/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.tsx
index 9bf74d46f8..5bf883f4dc 100644
--- a/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.tsx
@@ -21,6 +21,7 @@ import "@xterm/xterm/css/xterm.css";
import { AlertCircle, Terminal as TerminalIcon } from "lucide-react";
import { useT } from "@/i18n";
import { buildMissionSocketUrl, fetchMissionToken } from "@/lib/missionAuth";
+import { TERMINAL_FONT_STACK, syncTerminalFont } from "@/lib/terminalFont";
import {
disposeTerminal,
getTerminal,
@@ -72,8 +73,7 @@ export function PtyTerminal({ workerId }: PtyTerminalProps) {
if (!term) {
term = new Terminal({
convertEol: true,
- fontFamily:
- "'JetBrains Mono', 'Fira Code', Consolas, 'Courier New', monospace",
+ fontFamily: TERMINAL_FONT_STACK,
fontSize: 12,
lineHeight: 1.2,
cursorBlink: false,
@@ -112,6 +112,14 @@ export function PtyTerminal({ workerId }: PtyTerminalProps) {
};
window.addEventListener("resize", handleResize);
+ // The fit above measured whatever font had loaded by then; if the display
+ // font arrives later, the cell grid keeps the fallback's width while the
+ // wider real glyphs are drawn into it — see ../../lib/terminalFont.
+ const disposeFontSync = syncTerminalFont(term, () => {
+ termRef.current?.clearTextureAtlas?.();
+ handleResize();
+ });
+
let ws: WebSocket | null = null;
let disposed = false;
const openSocket = (token: string) => {
@@ -195,6 +203,7 @@ export function PtyTerminal({ workerId }: PtyTerminalProps) {
return () => {
disposed = true;
window.removeEventListener("resize", handleResize);
+ disposeFontSync();
try {
wsRef.current?.close(1000, "unmount");
} catch {
diff --git a/jarvis/ui/web/frontend/src/components/workspace/WorkspaceTerminal.tsx b/jarvis/ui/web/frontend/src/components/workspace/WorkspaceTerminal.tsx
index 771b01655c..291675d914 100644
--- a/jarvis/ui/web/frontend/src/components/workspace/WorkspaceTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/workspace/WorkspaceTerminal.tsx
@@ -14,6 +14,7 @@ import { WebLinksAddon } from "@xterm/addon-web-links";
import "@xterm/xterm/css/xterm.css";
import { Terminal as TerminalIcon, AlertCircle } from "lucide-react";
import { installNewlineBridge } from "../agentic/terminalNewline";
+import { TERMINAL_FONT_STACK, syncTerminalFont } from "@/lib/terminalFont";
type Status = "connecting" | "live" | "exited" | "error";
@@ -52,7 +53,7 @@ export function WorkspaceTerminal({
const term = new Terminal({
convertEol: false,
- fontFamily: "'JetBrains Mono', 'Fira Code', Consolas, 'Courier New', monospace",
+ fontFamily: TERMINAL_FONT_STACK,
fontSize: 12,
lineHeight: 1.15,
cursorBlink: true,
@@ -94,6 +95,16 @@ export function WorkspaceTerminal({
}
};
+ // The fit above measured whatever font had loaded by then. If the display
+ // font lands afterwards, the grid keeps the fallback's cell width while the
+ // real glyphs are drawn wider, and the text smears out of its columns — see
+ // ../../lib/terminalFont.
+ const disposeFontSync = syncTerminalFont(term, () => {
+ if (disposed) return;
+ term.clearTextureAtlas?.();
+ sendResize();
+ });
+
{
const params: Record<string, string> = {
cols: String(term.cols || 80),
@@ -169,6 +180,7 @@ export function WorkspaceTerminal({
disposed = true;
window.removeEventListener("resize", sendResize);
ro.disconnect();
+ disposeFontSync();
disposeNewlineBridge();
try {
ws?.close();
diff --git a/jarvis/ui/web/frontend/src/lib/terminalFont.test.ts b/jarvis/ui/web/frontend/src/lib/terminalFont.test.ts
new file mode 100644
index 0000000000..7634a3d4b2
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/terminalFont.test.ts
@@ -0,0 +1,330 @@
+/**
+ * Guards the terminal grid against the font it is actually drawn with.
+ *
+ * The bug these pin (browser panes, 2026-07-28): xterm measured the fallback
+ * font, built a 7px cell grid from it, and then drew JetBrains Mono's 7.80px
+ * glyphs into that grid — text smeared a full column out of place within nine
+ * characters, and each pane told its pty ~8 columns more than it had.
+ *
+ * The two traps have their own tests below, because both LOOK fixed while
+ * doing nothing: waiting on `document.fonts.ready` (which resolves before a
+ * never-yet-rendered font is even requested) and re-fitting (which re-reads the
+ * cached, wrong cell width instead of measuring again).
+ */
+import { describe, it, expect, vi } from "vitest";
+import {
+ TERMINAL_FONT_STACK,
+ alignTerminalCells,
+ syncTerminalFont,
+} from "./terminalFont";
+
+/** A stand-in for the xterm options this module is allowed to touch. */
+function fakeTerm(fontSize = 13) {
+ const options: {
+ fontFamily: string;
+ fontSize: number;
+ letterSpacing?: number;
+ } = { fontFamily: TERMINAL_FONT_STACK, fontSize };
+ return { options };
+}
+
+/**
+ * A FontFaceSet whose `load()` and `ready` resolve only when the test says so —
+ * the whole point is what happens BETWEEN mount and the font arriving.
+ */
+function fakeFonts() {
+ const listeners = new Set<() => void>();
+ let releaseLoad: () => void = () => {};
+ const loaded = new Promise<void>((resolve) => {
+ releaseLoad = resolve;
+ });
+ return {
+ set: {
+ load: vi.fn(() => loaded),
+ ready: loaded,
+ addEventListener: (type: string, fn: () => void) => {
+ if (type === "loadingdone") listeners.add(fn);
+ },
+ removeEventListener: (_type: string, fn: () => void) => {
+ listeners.delete(fn);
+ },
+ } as unknown as FontFaceSet,
+ /** The display font finished downloading. */
+ arrive: async () => {
+ releaseLoad();
+ for (const fn of listeners) fn();
+ await Promise.resolve();
+ await Promise.resolve();
+ },
+ listenerCount: () => listeners.size,
+ };
+}
+
+/** Consolas and JetBrains Mono at 13px, as measured in Chrome on the live app. */
+const FALLBACK_ADVANCE = 7.147;
+const DISPLAY_ADVANCE = 7.8;
+
+describe("alignTerminalCells", () => {
+ it("gives back the fraction of a pixel the canvas renderer floors away", () => {
+ const term = fakeTerm();
+
+ // JetBrains Mono at 13px advances 7.80px; the canvas renderer floors that to
+ // a 7px cell and then draws the full 7.80px glyph into it, so every
+ // character overhangs its neighbour by 0.8px. That is the smear.
+ const changed = alignTerminalCells(term, {
+ measureAdvance: () => DISPLAY_ADVANCE,
+ devicePixelRatio: 1,
+ });
+
+ expect(changed).toBe(true);
+ expect(term.options.letterSpacing).toBe(1);
+ });
+
+ it("leaves a font whose advance is already a whole pixel alone", () => {
+ const term = fakeTerm();
+
+ const changed = alignTerminalCells(term, {
+ measureAdvance: () => 8,
+ devicePixelRatio: 1,
+ });
+
+ // Nothing is floored away, so spacing would only push the glyphs apart.
+ expect(changed).toBe(false);
+ expect(term.options.letterSpacing ?? 0).toBe(0);
+ });
+
+ it("measures the overhang in DEVICE pixels, not css pixels", () => {
+ // At dpr 2 a 7.5px advance is 15 device px — a whole number, nothing floored.
+ const retina = fakeTerm();
+ expect(
+ alignTerminalCells(retina, {
+ measureAdvance: () => 7.5,
+ devicePixelRatio: 2,
+ }),
+ ).toBe(false);
+
+ // The same advance at dpr 1 does lose a half pixel per cell.
+ const standard = fakeTerm();
+ expect(
+ alignTerminalCells(standard, {
+ measureAdvance: () => 7.5,
+ devicePixelRatio: 1,
+ }),
+ ).toBe(true);
+ });
+
+ it("reports no change on a second call, so callers do not re-fit forever", () => {
+ const term = fakeTerm();
+ const deps = { measureAdvance: () => DISPLAY_ADVANCE, devicePixelRatio: 1 };
+
+ expect(alignTerminalCells(term, deps)).toBe(true);
+ expect(alignTerminalCells(term, deps)).toBe(false);
+ });
+
+ it("survives a terminal that exposes no options at all", () => {
+ // This runs inside a mount effect: a throw here does not misalign a grid,
+ // it takes the whole pane down. Stubs and older engines both hit this.
+ const stub = {} as unknown as Parameters<typeof alignTerminalCells>[0];
+
+ expect(() =>
+ alignTerminalCells(stub, {
+ measureAdvance: () => DISPLAY_ADVANCE,
+ devicePixelRatio: 1,
+ }),
+ ).not.toThrow();
+ expect(() =>
+ syncTerminalFont(stub, vi.fn(), {
+ fonts: fakeFonts().set,
+ measureAdvance: () => DISPLAY_ADVANCE,
+ devicePixelRatio: 1,
+ })(),
+ ).not.toThrow();
+ });
+
+ it("does not touch a terminal it cannot measure", () => {
+ const term = fakeTerm();
+
+ const changed = alignTerminalCells(term, {
+ measureAdvance: () => null,
+ devicePixelRatio: 1,
+ });
+
+ expect(changed).toBe(false);
+ expect(term.options.letterSpacing).toBeUndefined();
+ });
+});
+
+describe("syncTerminalFont", () => {
+ it("aligns the grid at mount, before any font arrives", () => {
+ const term = fakeTerm();
+ const onChanged = vi.fn();
+
+ const dispose = syncTerminalFont(term, onChanged, {
+ fonts: fakeFonts().set,
+ measureAdvance: () => DISPLAY_ADVANCE,
+ devicePixelRatio: 1,
+ });
+
+ // The overhang does not wait for a late font: a cell floored at mount is
+ // already drawing glyphs over their neighbours on the first frame.
+ expect(term.options.letterSpacing).toBe(1);
+ expect(onChanged).toHaveBeenCalledTimes(1);
+
+ dispose();
+ });
+
+ it("re-aligns the grid to the font that actually arrived", async () => {
+ const term = fakeTerm();
+ const fonts = fakeFonts();
+ // A fallback that happens to land on a whole pixel needs no spacing...
+ let advance = 7;
+ const onChanged = vi.fn();
+
+ const dispose = syncTerminalFont(term, onChanged, {
+ fonts: fonts.set,
+ measureAdvance: () => advance,
+ devicePixelRatio: 1,
+ });
+ expect(term.options.letterSpacing ?? 0).toBe(0);
+
+ // ...but the display font that replaces it does.
+ advance = DISPLAY_ADVANCE;
+ await fonts.arrive();
+
+ expect(term.options.letterSpacing).toBe(1);
+ expect(onChanged).toHaveBeenCalled();
+
+ dispose();
+ });
+
+ it("re-measures and reports once the display font replaces the fallback", async () => {
+ const term = fakeTerm();
+ const fonts = fakeFonts();
+ let advance = FALLBACK_ADVANCE;
+ const onRemeasured = vi.fn();
+
+ const dispose = syncTerminalFont(term, onRemeasured, {
+ fonts: fonts.set,
+ measureAdvance: () => advance,
+ devicePixelRatio: 1,
+ });
+
+ // The mount-time alignment may already have reported once (7.147 overhangs
+ // its floored cell too); what this test is about is the SECOND report, the
+ // one the font swap owes.
+ const beforeSwap = onRemeasured.mock.calls.length;
+
+ const stackBefore = term.options.fontFamily;
+ advance = DISPLAY_ADVANCE;
+ await fonts.arrive();
+
+ expect(onRemeasured.mock.calls.length).toBe(beforeSwap + 1);
+ // xterm re-measures ONLY on a fontFamily/fontSize change and ignores a
+ // write of the identical string, so a sync that left this untouched would
+ // have reported a change xterm never acted on.
+ expect(term.options.fontFamily).not.toBe(stackBefore);
+ // ...and it must still resolve to the same font.
+ expect(term.options.fontFamily).toContain("JetBrains Mono");
+
+ dispose();
+ });
+
+ it("stays quiet when the measurement never changes (offline, no web font)", async () => {
+ const term = fakeTerm();
+ const fonts = fakeFonts();
+ const onRemeasured = vi.fn();
+
+ // An advance that lands on a whole device pixel, so the mount-time
+ // alignment has nothing to give back and this test sees the font path alone.
+ const dispose = syncTerminalFont(term, onRemeasured, {
+ fonts: fonts.set,
+ measureAdvance: () => 7,
+ devicePixelRatio: 1,
+ });
+ await fonts.arrive();
+
+ // The fallback IS the font being drawn: the grid was right all along.
+ expect(onRemeasured).not.toHaveBeenCalled();
+ expect(term.options.fontFamily).toBe(TERMINAL_FONT_STACK);
+
+ dispose();
+ });
+
+ it("asks for the display font BY NAME rather than trusting fonts.ready", () => {
+ const term = fakeTerm();
+ const fonts = fakeFonts();
+
+ const dispose = syncTerminalFont(term, vi.fn(), {
+ fonts: fonts.set,
+ measureAdvance: () => FALLBACK_ADVANCE,
+ });
+
+ // `fonts.ready` resolves as soon as nothing is PENDING, and a font nothing
+ // has rendered yet was never requested — so it reports "ready" while the
+ // terminal font is still absent. Only an explicit request starts it.
+ const asked = (fonts.set.load as unknown as ReturnType<typeof vi.fn>).mock
+ .calls;
+ expect(asked.length).toBeGreaterThan(0);
+ expect(asked.every((c) => String(c[0]).includes("JetBrains Mono"))).toBe(
+ true,
+ );
+
+ dispose();
+ });
+
+ it("keeps watching after a late arrival, and stops on dispose", async () => {
+ const term = fakeTerm();
+ const fonts = fakeFonts();
+ // Starts on a whole pixel so the mount-time alignment is silent and every
+ // count below belongs to a font change.
+ let advance = 7;
+ const onRemeasured = vi.fn();
+
+ const dispose = syncTerminalFont(term, onRemeasured, {
+ fonts: fonts.set,
+ measureAdvance: () => advance,
+ devicePixelRatio: 1,
+ });
+
+ advance = DISPLAY_ADVANCE;
+ await fonts.arrive();
+ expect(onRemeasured).toHaveBeenCalledTimes(1);
+
+ // A second genuine change (a font swapped in later) is still caught: the
+ // sync must not burn itself out on the first signal, which is precisely how
+ // the previous implementation lost its one chance to fix the grid.
+ advance = 9.1;
+ await fonts.arrive();
+ expect(onRemeasured).toHaveBeenCalledTimes(2);
+
+ dispose();
+ expect(fonts.listenerCount()).toBe(0);
+ advance = 12;
+ await fonts.arrive();
+ expect(onRemeasured).toHaveBeenCalledTimes(2);
+ });
+
+ it("is a no-op where nothing can be measured or no font API exists", async () => {
+ const onRemeasured = vi.fn();
+
+ // Headless/jsdom: no 2D context, so no advance can be measured. Reporting a
+ // change here would reflow every pane on a number that means nothing.
+ const unmeasurable = syncTerminalFont(fakeTerm(), onRemeasured, {
+ fonts: fakeFonts().set,
+ measureAdvance: () => null,
+ });
+ unmeasurable();
+
+ // An engine without FontFaceSet: what was measured at mount is the font, and
+ // on a whole-pixel advance there is nothing to align either.
+ const noApi = syncTerminalFont(fakeTerm(), onRemeasured, {
+ fonts: null,
+ measureAdvance: () => 7,
+ devicePixelRatio: 1,
+ });
+ noApi();
+
+ await Promise.resolve();
+ expect(onRemeasured).not.toHaveBeenCalled();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/terminalFont.ts b/jarvis/ui/web/frontend/src/lib/terminalFont.ts
new file mode 100644
index 0000000000..dc6e6b2875
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/terminalFont.ts
@@ -0,0 +1,285 @@
+/**
+ * Keep xterm's cell grid in step with the font it actually draws with.
+ *
+ * A terminal is a grid: xterm measures ONE glyph, calls that the cell width,
+ * and lays out every column from it. Measure it before the display font has
+ * loaded and the whole grid is built on the fallback's metrics — at 13px,
+ * Consolas advances 7.15px where JetBrains Mono advances 7.80px, a 9% error.
+ * Every glyph is then painted 0.65px wider than the cell it owns, so nine
+ * characters in, the text sits a full column off its grid. That is the smeared,
+ * overlapping terminal output reported in the browser on 2026-07-28: measured
+ * live in Chrome, all six panes had a 7px cell while JetBrains Mono was loaded
+ * and drawing at 7.80px, and each pane had told its pty ~102 columns where only
+ * ~94 fit.
+ *
+ * Two things make this easy to get wrong, and both were:
+ *
+ * * **`document.fonts.ready` does not mean "the terminal font is here."** It
+ * resolves once nothing is PENDING, and a font no element has rendered yet
+ * was never requested, so it is not pending. Measured in Chrome on the live
+ * app: `document.fonts.status === "loaded"` while
+ * `document.fonts.check('400 13px "JetBrains Mono"') === false`. Waiting on
+ * it therefore re-fits at a moment that proves nothing — and, worse, retires
+ * the one chance to fix the grid. The font has to be asked for BY NAME.
+ * * **A re-fit does not re-measure.** xterm re-measures only when `fontFamily`
+ * or `fontSize` CHANGE (`CharSizeService` subscribes to exactly those two),
+ * and its options setter ignores a write of the identical string. `fit()`
+ * reads the cached, wrong cell width and faithfully recomputes the same wrong
+ * grid, so clearing the texture atlas and re-fitting cannot repair this on
+ * its own.
+ *
+ * Hence: ask for the font by name, then WATCH — the only signal that cannot lie
+ * is the measurement itself, so a font that arrives late (slow CDN, an @import
+ * whose stylesheet had not been parsed when it was first asked for) is still
+ * caught. Offline, where the font never arrives, the fallback IS the font being
+ * drawn, the measurement never changes, and nothing happens.
+ */
+
+/**
+ * The one monospace stack every terminal in the app draws with.
+ *
+ * Shared rather than repeated per component so that the measurement here and
+ * the glyphs on screen can never describe different fonts.
+ */
+export const TERMINAL_FONT_STACK =
+ "'JetBrains Mono', 'Fira Code', 'SF Mono', Consolas, 'Courier New', monospace";
+
+/** The display font at the head of the stack — the one that arrives late. */
+const DISPLAY_FAMILY = '"JetBrains Mono"';
+
+/** The weights xterm paints with: body text, and the bold spans a TUI uses. */
+const WEIGHTS = [400, 700] as const;
+
+/** Measured over a run of glyphs so per-character rounding cannot dominate. */
+const SAMPLE = "W".repeat(32);
+
+/**
+ * Sub-pixel noise floor. Well under the ~0.65px error this exists to catch, and
+ * comfortably above the jitter of repeating the same measurement.
+ */
+const ADVANCE_EPSILON = 0.05;
+
+/**
+ * Appended to force a re-measure, and harmless: the stack already ends in
+ * `monospace`, so a second one changes the STRING without changing which font
+ * resolves. Toggled rather than appended forever so repeated syncs stay stable.
+ */
+const REMEASURE_SUFFIX = ", monospace";
+
+/**
+ * The slice of xterm's API this needs — kept tiny so tests need no terminal.
+ * The fields are optional because xterm declares them so; in practice every
+ * terminal in this app sets font family and size at construction.
+ */
+export interface TerminalFontTarget {
+ options: { fontFamily?: string; fontSize?: number; letterSpacing?: number };
+}
+
+/**
+ * xterm's own default size, used only when a terminal left `fontSize` unset.
+ * The comparison here is a BEFORE/AFTER delta at one fixed size, and advance
+ * width scales linearly with it, so any consistent yardstick detects the same
+ * change — this never has to match what is on screen.
+ */
+const FALLBACK_FONT_SIZE = 15;
+
+export interface TerminalFontDeps {
+ /** Advance width, in px, of one cell in `stack` at `fontSize`. */
+ measureAdvance: (fontSize: number, stack: string) => number | null;
+ /** The document's font set; `null` where the API does not exist. */
+ fonts: FontFaceSet | null;
+ /** Device pixel ratio; the canvas renderer rounds in device pixels. */
+ devicePixelRatio: number;
+}
+
+function currentDpr(): number {
+ if (typeof window === "undefined") return 1;
+ return window.devicePixelRatio || 1;
+}
+
+/**
+ * Give each cell back the sliver of a pixel xterm's canvas renderer floors away.
+ *
+ * The canvas renderer builds its grid on `Math.floor(advance * dpr)` device
+ * pixels per cell, but keeps drawing the font's real, unfloored glyphs into it.
+ * JetBrains Mono at 13px advances 7.80px, so at dpr 1 every cell is 7px wide and
+ * every glyph overhangs its own cell by 0.8px — a tenth of a character, painted
+ * over its neighbour, compounding across the line into the smeared text this
+ * whole module exists to stop. The overhang is invisible on a font whose advance
+ * happens to land on a whole pixel, which is why the fallback font looked fine.
+ *
+ * `letterSpacing` is added to the cell width in whole device pixels, so handing
+ * back the floored fraction as one pixel of spacing makes the cell at least as
+ * wide as the glyph it holds. Integral by construction: a fractional value would
+ * be rounded away by the renderer and, worse, would land box-drawing characters
+ * and the text beneath them on different sub-pixel offsets.
+ *
+ * Returns whether anything changed — a caller that re-fits and resizes its pty
+ * should do so only then.
+ */
+export function alignTerminalCells(
+ term: TerminalFontTarget,
+ deps: Partial<TerminalFontDeps> = {},
+): boolean {
+ const measure = deps.measureAdvance ?? measureAdvance;
+ const dpr = deps.devicePixelRatio ?? currentDpr();
+ // Nothing here is worth a pane for. This module only makes glyphs sit
+ // straight, so anything it does not recognise — a stubbed terminal, an engine
+ // that exposes its options differently — leaves the terminal exactly as it is
+ // rather than throwing out of a mount effect and taking the pane with it.
+ const options = term?.options;
+ if (!options) return false;
+ const size = options.fontSize ?? FALLBACK_FONT_SIZE;
+ const advance = measure(size, options.fontFamily || TERMINAL_FONT_STACK);
+ // Unmeasurable (jsdom, no 2D context): leave the terminal exactly as it is.
+ if (advance === null) return false;
+
+ const device = advance * dpr;
+ // The epsilon keeps a hair over a whole pixel (7.0000001) from being treated
+ // as an overhang and buying a pixel of spacing nothing needed.
+ const overhangs = device - Math.floor(device) > ADVANCE_EPSILON;
+ const wanted = overhangs ? 1 : 0;
+ if ((options.letterSpacing ?? 0) === wanted) return false;
+ options.letterSpacing = wanted;
+ return true;
+}
+
+/**
+ * One cell's advance width, or `null` where it cannot be measured — jsdom has
+ * no 2D context, and an environment that cannot measure must not be told the
+ * font changed.
+ */
+export function measureAdvance(
+ fontSize: number,
+ stack: string = TERMINAL_FONT_STACK,
+): number | null {
+ if (typeof document === "undefined") return null;
+ let ctx: CanvasRenderingContext2D | null = null;
+ try {
+ ctx = document.createElement("canvas").getContext?.("2d") ?? null;
+ } catch {
+ return null;
+ }
+ if (!ctx) return null;
+ ctx.font = `${fontSize}px ${stack}`;
+ const width = ctx.measureText(SAMPLE).width;
+ if (!Number.isFinite(width) || width <= 0) return null;
+ return width / SAMPLE.length;
+}
+
+function browserFonts(): FontFaceSet | null {
+ if (typeof document === "undefined") return null;
+ return document.fonts ?? null;
+}
+
+/**
+ * Ask for the terminal's display font, align the cell grid to it, and keep both
+ * honest for as long as the pane lives.
+ *
+ * `onChanged` runs after the terminal has been adjusted and fires only on a REAL
+ * change, so the caller can do the expensive half — invalidate the glyph atlas,
+ * re-fit, and tell the pty its new size — without rate-limiting. It fires
+ * synchronously during this call if the grid needed aligning at mount, which is
+ * the ordinary case: the floored cell is wrong from the first frame, whether or
+ * not a font arrives later.
+ *
+ * Returns a dispose function; calling it stops all watching.
+ */
+export function syncTerminalFont(
+ term: TerminalFontTarget,
+ onChanged: () => void,
+ deps: Partial<TerminalFontDeps> = {},
+): () => void {
+ const measure = deps.measureAdvance ?? measureAdvance;
+ const fonts = deps.fonts !== undefined ? deps.fonts : browserFonts();
+
+ let disposed = false;
+ let cleanup = () => {};
+ const dispose = () => {
+ if (disposed) return;
+ disposed = true;
+ cleanup();
+ };
+
+ // Align to the font that is on screen RIGHT NOW, before anything is awaited:
+ // the overhang does not need a late font to appear, only a font whose advance
+ // is not a whole number of device pixels.
+ if (alignTerminalCells(term, deps)) onChanged();
+
+ // A terminal whose options this cannot read is one to leave alone, not one to
+ // throw over — this runs inside a mount effect, where an exception costs the
+ // whole pane. See the same guard in `alignTerminalCells`.
+ const options = term?.options;
+ if (!options) return dispose;
+
+ // No font API to wait on: whatever is measured now is the font that will be
+ // drawn, and the grid above is already aligned to it.
+ if (!fonts) return dispose;
+
+ // The size the baseline was taken at, held separately: the user can change
+ // the font size while the font is still in flight, and comparing the new
+ // size's advance against the old size's would report a change that is only
+ // the zoom the caller already handled.
+ const baseSize = options.fontSize ?? FALLBACK_FONT_SIZE;
+ const stackOf = () => options.fontFamily || TERMINAL_FONT_STACK;
+ let baseline = measure(baseSize, stackOf());
+ // Nothing measurable here (jsdom, a headless canvas-less runtime). Watching
+ // would compare null to null forever.
+ if (baseline === null) return dispose;
+
+ // The stack as this pane was built with it. Re-measures alternate between it
+ // and a padded copy, so the string always differs from the one xterm holds
+ // (its setter drops an identical write, and that write is the re-measure)
+ // without the padding accumulating across a long-lived pane.
+ const originalStack = stackOf();
+ let remeasures = 0;
+
+ const settle = () => {
+ if (disposed) return;
+ const now = measure(baseSize, stackOf());
+ if (now === null || baseline === null) return;
+ if (Math.abs(now - baseline) < ADVANCE_EPSILON) return;
+ baseline = now;
+ // Force the re-measure xterm will not do on its own — see the file header.
+ // Both forms keep the generic fallback the original stack ends with, so a
+ // terminal still waiting on every named font always has one to fall back to.
+ remeasures += 1;
+ options.fontFamily =
+ remeasures % 2 === 1 ? originalStack + REMEASURE_SUFFIX : originalStack;
+ // The new font has a new advance, so the cell has a new fraction to give
+ // back. Order matters: align AFTER the re-measure, never before.
+ alignTerminalCells(term, deps);
+ onChanged();
+ };
+
+ // Ask for the font BY NAME — the request `document.fonts.ready` was waiting
+ // for and would never see, because until something renders in it, nobody has
+ // asked. A rejection is ordinary (offline, or the @font-face rule has not
+ // been parsed yet); the listener below covers the late arrival either way.
+ for (const weight of WEIGHTS) {
+ try {
+ void fonts
+ .load(`${weight} ${baseSize}px ${DISPLAY_FAMILY}`)
+ .then(settle, () => undefined);
+ } catch {
+ /* older FontFaceSet, or a family it refuses to parse — the watch covers it */
+ }
+ }
+
+ // Everything the explicit request cannot cover: a stylesheet that lands after
+ // it, a font swapped in later, a second family finishing after the first.
+ const onLoadingDone = () => settle();
+ try {
+ fonts.addEventListener?.("loadingdone", onLoadingDone);
+ cleanup = () => fonts.removeEventListener?.("loadingdone", onLoadingDone);
+ } catch {
+ /* no event target here — the explicit request above still settles */
+ }
+ try {
+ void fonts.ready?.then(settle, () => undefined);
+ } catch {
+ /* no `ready` in this engine */
+ }
+
+ return dispose;
+}