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(agentic-ide): a pane waits for its font before it tells the agent a width, and an unmeasured tile says so

rubenluetke10-beepa33bc20517bb
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 9e615581a7..3d3d9e11c2 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -13963,3 +13963,165 @@ skipped check protects nothing. The gate that survives a shared tree is the
one that fails only on what is certainly broken — here, the one class of
type error that is a `ReferenceError` in disguise — and lets everything
merely disputed pass.
+
+---
+
+## BUG-198: the Spend section's coding-CLI total went DOWN from one day to the next — $12 300 became $8 000 without a filter changing, and "Agentic IDE" showed more than "Overall" (HIGH, FIXED 2026-08-27)
+
+**Symptom.** The maintainer read a 30-day total of roughly $12 300 one
+day and about $8 000 the next, on the same range. Two screenshots two
+seconds apart showed the *Agentic IDE* area at $8 857 / 1 310 calls and
+*Overall* — which contains it — at $7 994 / 1 582 calls; `claude-cli` alone
+had 1 154 calls in the subset and 838 in the whole. Days in the middle of
+the range had no bar at all.
+
+**Root cause.** Three separate ways the coding-CLI index
+(`jarvis/costs/cli_usage_index.py`) said less than the transcripts:
+
+1. *The index was a cache, and it was being rebuilt.* Schema version 4 (the
+ kimi/Antigravity split) dropped both tables and re-read 1.8 GB of Claude
+ Code, 9.5 GB of Codex and 370 MB of Grok Build at twenty seconds per
+ minute. The screenshots were taken forty minutes into that: the index
+ held 40 199 of an eventual 76 000+ turns, newest files first, and nothing
+ on the page said so. The two views disagreed because the browser held an
+ *Overall* answer from an earlier poll and fetched *Agentic IDE* fresh a
+ few thousand turns later. Measured on the live API an hour on: the same
+ 30 days read $13 642.
+2. *Deleted transcripts took their turns with them.* `_prune_vanished`
+ removed the rows of any file no longer on disk — introduced 2026-08-25
+ to keep the index honest about rotated files. Claude Code deletes
+ sessions after `cleanupPeriodDays` (25 in the maintainer's
+ `settings.json`), so every night the oldest day's spend left the ledger.
+ The lifetime ("All") total on this machine begins on 1 August because
+ everything before it is gone.
+3. *Subagent transcripts were never read.* Discovery matched
+ `projects/*/*.jsonl` only; the Agent tool writes
+ `projects/<slug>/<session>/subagents/agent-<id>.jsonl` and a workflow
+ `…/subagents/workflows/<run>/agent-<id>.jsonl`. Comparing every transcript
+ on disk with the index: 68 937 Claude responses on disk, 39 339 indexed;
+ 14 466 of the missing lived in subagent files (one fifth of all calls,
+ 14.2 billion cached tokens on disk against 8.5 indexed).
+
+**Fix.**
+
+- The index is a ledger. `_forget_vanished` drops only a vanished file's
+ resume row; its turns stay. A schema bump (`_SCHEMA_VERSION` 5,
+ `_REREAD_BELOW`) never drops a table: `_migrate` fixes what it can in
+ place (the kimi rename by path), then clears the file bookkeeping so every
+ transcript still on disk is read again, and `_INSERT_TURN` overwrites a
+ row re-read FROM ITS OWN FILE while a copy in another file (a Codex
+ replay, a resumed Claude session) still only fills in a missing model.
+ Rows whose transcript is gone keep their old values. `turns_added` counts
+ rows a file newly owns, not SQLite change counts.
+- Discovery gained `projects/*/*/subagents/**/*.jsonl`; a subagent record
+ carries the parent's `sessionId`, so its spend lands on that conversation.
+- `/api/costs/summary` carries `index` (`files_known`, `files_indexed`,
+ `files_pending`, `bytes_pending`, `turns`, `complete`), and the Spend
+ section shows "Still counting the coding CLIs: {n} of {m} transcripts
+ read, {x} MB to go" while it is false. The background refresher runs
+ every 3 s instead of every 60 s until a run reaches the end of every file.
+
+Tests: `tests/unit/costs/test_cli_usage_index.py` —
+`test_a_transcript_that_disappeared_keeps_its_rows`,
+`test_a_transcript_that_comes_back_overwrites_its_own_rows`,
+`test_a_schema_bump_keeps_the_rows_of_a_transcript_that_is_gone`,
+`test_a_reread_corrects_a_row_but_a_copy_in_another_file_does_not`,
+`test_subagent_transcripts_are_indexed_under_their_parent_session`;
+`tests/unit/ui/web/test_costs_routes.py` —
+`test_summary_says_whether_the_cli_index_is_still_counting`.
+
+**Not recoverable.** Transcripts Claude Code already deleted before this fix
+are gone, and so is their spend — the ledger starts on the oldest transcript
+still on disk (1 August here). From now on it only grows.
+
+**Lesson.** A store that is rebuilt from its source is a cache, and a cache
+can be asked at any moment — so either it is never empty (rebuild in place)
+or it says how full it is. And a source that deletes itself on a timer
+(`cleanupPeriodDays`) cannot be the ledger; the index has to be.
+
+## BUG-199: after a restart every Agentic IDE pane came back shredded — rows of one transcript cut through by fragments of another ("●nRead 1 file, ran 3 shell commands ll commands"), and nothing the agent did afterwards repaired it (HIGH, FIXED 2026-08-27)
+
+**Symptom.** The desktop app was restarted at 18:32 (`data/jarvis_desktop.
+2026-08-27_18-32-26_041573.log` is the rotated log). A minute later a
+screenshot of the "Jarvis Web UI" workspace showed all six re-joined panes
+garbled the same way: each row held the agent's current text with the tail of
+an OLDER row still standing at its end (`… ran 3 shell commands ll commands`),
+one-letter fragments down the left edge (`-P`, `ne`, `ri`, `ur`, `st`), and
+rules drawn twice at different lengths. The live status line was affected too
+(`* Bunning…must b16s`). Every glyph sat squarely on the cell grid — this was
+not a renderer fault, it was two layouts of the same transcript in one buffer.
+Claude Code only ever redraws its own live rows, so the scrollback above them
+stayed like that for the rest of the session.
+
+**Cause.** A width bounce on a running agent, twice through ConPTY.
+
+1. `AgenticTerminal` builds its xterm grid from one measured glyph and hands
+ the agent that grid's column count in the socket handshake, which the
+ server applies at once (`SessionRegistry._attach_locked`: a re-join at a
+ size other than the transcript's resizes the PTY, rebases the replay and
+ nudges a repaint). The app's display font is `@import`ed from Google Fonts
+ (`index.css`), so after a restart it is routinely a moment late, and the
+ glyph measured was Consolas's. At the workspace's 20px text: Consolas
+ advances 11px, JetBrains Mono 12px; a 744px tile was announced as 67
+ columns. The agent re-wrapped for 67.
+2. `syncTerminalFont` (the 2026-07-28 fix) then saw the real font arrive,
+ re-measured, re-fitted and sent 62. The agent re-wrapped again — and on
+ Windows ConPTY answers every width change by re-flowing its whole screen
+ buffer, so the rows written for 67 were folded into 62-column rows and the
+ agent's next relative-cursor repaint finished into rows that now held other
+ text. The crop of the screenshot shows it exactly: 62-character rows whose
+ overflow (` nur men.`) sits on the row below.
+
+ The July fix was enough for a pane whose agent STARTS with it, because a
+ fresh CLI has no transcript to shred. It was never enough for a pane that
+ re-joins a running one, and every restart re-joins every pane.
+3. The same bounce, from the other side: a pane that mounts hidden (the chat
+ stage) cannot measure its tile, keeps xterm's constructed 80x24, and — since
+ BUG-190 that morning — handed THAT to the server as if a tile had measured
+ it. A running agent was re-wrapped for 80 columns no tile had, and for the
+ real ones the moment the pane was shown.
+
+**Fix.**
+
+- `lib/terminalFont.ts` — `terminalFontSettled(size)` says whether the display
+ font can be measured right now, and it needs two things, not one:
+ `FontFaceSet.check()` answers "yes" for a family it has never heard of, and
+ until the `@import`ed stylesheet lands no face is declared, so a face has to
+ EXIST and be loaded. `whenTerminalFontReady(size)` resolves once it is —
+ asking by name, re-asking on a poll (a face that is not declared yet cannot
+ be loaded yet), listening for `loadingdone` — or after `FONT_WAIT_MS`
+ (1.5 s), whichever comes first. Offline the fallback IS the font, the
+ measurement is right, and the agent hears one size.
+- `AgenticTerminal.tsx` — the connect effect does not run until `fontReady`,
+ so the grid's first measurement is of the font it draws with. Settled
+ synchronously where it can be, so a pane whose font is already here mounts
+ exactly as before (the tests' jsdom, which has no font API, counts as
+ settled).
+- `AgenticTerminal.tsx` — the handshake carries the tile's measurement only
+ when there was one. An unmeasured pane sends `UNMEASURED_SIZE` (1x1),
+ deliberately under the server's viewer floor: that is the wire's spelling of
+ "not measured yet", which the server already answered by keeping the PTY's
+ geometry for a live agent (and the transcript's default, 100x30, for a fresh
+ spawn) and reporting it back so the grid follows. Zero would not do —
+ `_safe_int` reads it as absent and substitutes 80x24.
+
+Tests: `src/lib/terminalFont.test.ts` — `terminalFontSettled` (3),
+`whenTerminalFontReady` (4: already here, declared-then-loaded with the
+listener released, the bounded wait, no font API);
+`src/components/agentic/AgenticTerminal.test.tsx` — "pane font readiness"
+(does not build before the font is measurable, builds on the fallback once
+the wait runs out, mounts at once when the font is here), "does not shrink a
+pane that mounts hidden to the floors" now also pins the handshake to
+`UNMEASURED_SIZE`, and "hands over the tile's own measurement when there was
+one".
+
+**Not recoverable.** A transcript ConPTY has already re-flowed stays
+re-flowed in that pane's scrollback; only a fresh pane (or the agent's next
+full-screen redraw) shows clean rows. The fix stops it happening on the next
+restart.
+
+**Lesson.** Repairing a measurement after the fact is not the same as not
+publishing the wrong one. The grid was corrected within a second — but the
+column count had already left the pane, and on Windows a size the agent has
+heard cannot be unheard. Anything that goes to the PTY on the strength of a
+measurement has to wait for the thing being measured to exist.
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx
index 4c659df4a2..a887981e6d 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx
@@ -14,6 +14,8 @@ const terminalHarness = vi.hoisted(() => ({
resize: vi.fn<(cols: number, rows: number) => void>(),
/** The live socket's handlers, so a test can play a reconnect. */
handlers: { current: null as Record<string, (...args: never[]) => void> | null },
+ /** What the pane opened its socket WITH — the handshake size among it. */
+ opened: { current: null as Record<string, unknown> | null },
/** Everything the pane types into the terminal on the user's behalf. */
input: vi.fn<(data: string) => void>(),
/** xterm's single custom key handler, so a test can press a key. */
@@ -165,9 +167,10 @@ vi.mock("@xterm/addon-unicode11", () => ({ Unicode11Addon: class {} }));
vi.mock("./paneSocket", () => ({
openPaneSocket: (
- _options: unknown,
+ options: unknown,
handlers: Record<string, (...args: never[]) => void>,
) => {
+ terminalHarness.opened.current = options as Record<string, unknown>;
terminalHarness.handlers.current = handlers;
return {
send: (payload: unknown) => terminalHarness.send(payload),
@@ -189,7 +192,9 @@ import {
DRAG_REFIT_MS,
REBUILD_QUIET_MS,
RESIZE_PARSE_WAIT_MS,
+ UNMEASURED_SIZE,
} from "./AgenticTerminal";
+import { FONT_WAIT_MS } from "@/lib/terminalFont";
import { PANE_CHROME } from "./terminalThemes";
/**
@@ -1565,6 +1570,13 @@ describe("pane refit", () => {
* clamped to the floors that was a 10x4 terminal — which the handshake then
* spawned the agent at (T11, 2026-08-27). Unmeasured, the terminal keeps
* its constructed size and the agent starts in one it can draw in.
+ *
+ * And the handshake says "unmeasured" rather than passing that constructed
+ * size off as a measurement. Handed 80x24, the server re-wrapped a RUNNING
+ * agent for 80 columns no tile had, and again for the tile's real width the
+ * moment the pane was shown — twice through ConPTY's re-flow, which is how
+ * a workspace came back from a restart with every transcript cut through by
+ * fragments of its own earlier layout (2026-08-27).
*/
it("does not shrink a pane that mounts hidden to the floors", () => {
Reflect.deleteProperty(HTMLElement.prototype, "clientWidth");
@@ -1579,6 +1591,30 @@ describe("pane refit", () => {
expect(terminalHarness.send).not.toHaveBeenCalledWith(
expect.objectContaining({ cols: 10, rows: 4 }),
);
+ expect(terminalHarness.opened.current).toEqual(
+ expect.objectContaining(UNMEASURED_SIZE),
+ );
+ });
+
+ it("hands over the tile's own measurement when there was one", () => {
+ Object.defineProperty(HTMLElement.prototype, "clientWidth", {
+ configurable: true,
+ value: 600,
+ });
+ Object.defineProperty(HTMLElement.prototype, "clientHeight", {
+ configurable: true,
+ value: 400,
+ });
+ terminalHarness.size = { cols: 72, rows: 20 };
+ render(pane(false));
+ settle();
+
+ expect(terminalHarness.fit).toHaveBeenCalled();
+ expect(terminalHarness.opened.current).toEqual(
+ expect.objectContaining({ cols: 72, rows: 20 }),
+ );
+ Reflect.deleteProperty(HTMLElement.prototype, "clientWidth");
+ Reflect.deleteProperty(HTMLElement.prototype, "clientHeight");
});
it("gives xterm and the agent the same number, always", () => {
@@ -2522,3 +2558,106 @@ describe("pane status", () => {
expect(screen.queryByTestId("pane-notice-Dana")).toBeNull();
});
});
+
+/*
+ * The grid is built from ONE measured glyph, and the agent hears that grid's
+ * column count in the pane's first message. Measured before the display font
+ * has arrived — it is `@import`ed from the network, so after a restart it is
+ * routinely a moment late — the glyph is the fallback's and the count is
+ * wrong: on the desktop (2026-08-27, 20px text) a 744px tile was announced as
+ * 67 columns, then as 62 once JetBrains Mono landed, and ConPTY re-flowed a
+ * running agent's whole transcript through both. So a pane waits for the font
+ * before it builds anything — and not for longer than the bounded wait.
+ */
+describe("pane font readiness", () => {
+ /** A FontFaceSet the test controls: which faces exist, and whether they loaded. */
+ function fakeFonts() {
+ const faces: { family: string }[] = [];
+ let loaded = false;
+ const listeners = new Set<() => void>();
+ const set = {
+ check: vi.fn(() => loaded),
+ load: vi.fn(() => Promise.resolve(loaded ? faces : [])),
+ addEventListener: (type: string, fn: () => void) => {
+ if (type === "loadingdone") listeners.add(fn);
+ },
+ removeEventListener: (_type: string, fn: () => void) => {
+ listeners.delete(fn);
+ },
+ [Symbol.iterator]: () => faces[Symbol.iterator](),
+ };
+ return {
+ set,
+ /** The @import landed: the face is declared, and it has loaded. */
+ arrive: () => {
+ faces.push({ family: '"JetBrains Mono"' });
+ loaded = true;
+ for (const fn of listeners) fn();
+ },
+ };
+ }
+
+ const pane = () => (
+ <AgenticTerminal
+ name="Dana"
+ displayName="Claude Code"
+ appearance="dark"
+ fontSize={20}
+ />
+ );
+
+ let fonts: ReturnType<typeof fakeFonts>;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ globalThis.ResizeObserver = ResizeObserverHarness;
+ terminalHarness.open.mockClear();
+ terminalHarness.opened.current = null;
+ fonts = fakeFonts();
+ Object.defineProperty(document, "fonts", {
+ configurable: true,
+ value: fonts.set,
+ });
+ });
+
+ afterEach(() => {
+ Reflect.deleteProperty(document, "fonts");
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ it("does not build its grid before the display font can be measured", async () => {
+ render(pane());
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(200);
+ });
+ expect(terminalHarness.open).not.toHaveBeenCalled();
+ expect(terminalHarness.opened.current).toBeNull();
+
+ fonts.arrive();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(100);
+ });
+ expect(terminalHarness.open).toHaveBeenCalledTimes(1);
+ expect(terminalHarness.opened.current).not.toBeNull();
+ });
+
+ it("builds on the font that is there once the wait runs out", async () => {
+ render(pane());
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(FONT_WAIT_MS - 100);
+ });
+ expect(terminalHarness.open).not.toHaveBeenCalled();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(200);
+ });
+ expect(terminalHarness.open).toHaveBeenCalledTimes(1);
+ });
+
+ it("mounts at once when the font is already here", () => {
+ fonts.arrive();
+ render(pane());
+ expect(terminalHarness.open).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index efd5f852a3..8cb493499e 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -104,6 +104,8 @@ import {
TERMINAL_FONT_STACK,
alignTerminalCells,
syncTerminalFont,
+ terminalFontSettled,
+ whenTerminalFontReady,
} from "@/lib/terminalFont";
import {
createTerminalLinkActivator,
@@ -308,6 +310,20 @@ const MAX_TERMINAL_NAME = 40;
const MIN_REAL_COLS = 10;
const MIN_REAL_ROWS = 4;
+/**
+ * The size a pane hands over when it could not measure its tile at mount.
+ *
+ * Deliberately UNDER the server's viewer floor (`MIN_VIEWER_COLS` /
+ * `MIN_VIEWER_ROWS` in `jarvis/agentic_ide/session.py`): that is the wire's
+ * spelling of "not measured yet". The server answers it by keeping the
+ * geometry the pane already has — a running agent is not re-wrapped for a
+ * size no tile ever had, a fresh one is spawned at the transcript's default —
+ * and reports that geometry back, so the grid here follows it until the tile
+ * is shown and measured. Zero would not do: the server reads it as absent and
+ * substitutes 80x24, which is precisely a size no tile had.
+ */
+export const UNMEASURED_SIZE = { cols: 1, rows: 1 } as const;
+
/*
* A pane never argues about its own width any more.
*
@@ -709,8 +725,37 @@ export function AgenticTerminal({
return bindTerminalScrollRegion(region);
}, []);
+ /*
+ * Is the font this pane will draw with here to be measured?
+ *
+ * The connect effect below builds the grid from ONE measured glyph and hands
+ * the agent that grid's column count in its first message. Measured before
+ * the display font has arrived — it comes through a stylesheet the app
+ * `@import`s from the network, so after a restart it is routinely a moment
+ * late — that glyph is the fallback's, the count is wrong, and a RUNNING
+ * agent is re-wrapped for it and then re-wrapped again when the real font
+ * lands (see `whenTerminalFontReady` for what that did to every pane of a
+ * workspace on 2026-08-27). So the pane does not build until the font is
+ * measurable, or until the bounded wait says it is not coming. Settled
+ * synchronously where it can be, so a pane whose font is already here
+ * mounts exactly as it always did.
+ */
+ const [fontReady, setFontReady] = useState(() =>
+ terminalFontSettled(fontSizeRef.current),
+ );
+ useEffect(() => {
+ if (fontReady) return;
+ let cancelled = false;
+ void whenTerminalFontReady(fontSizeRef.current).then(() => {
+ if (!cancelled) setFontReady(true);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [fontReady]);
+
useEffect(() => {
- if (!geometryReady) return;
+ if (!geometryReady || !fontReady) return;
const container = containerRef.current;
if (!container) return;
@@ -883,6 +928,8 @@ export function AgenticTerminal({
/** Is this pane's tile something that can honestly be measured right now? */
const measurable = () =>
container.clientWidth >= 8 && container.clientHeight >= 8;
+ /** Did the grid below come from the tile, or is it still the constructed default? */
+ let mountMeasured = false;
try {
// Taken BEFORE the handshake below reads the terminal's geometry — so
@@ -918,6 +965,7 @@ export function AgenticTerminal({
Math.max(proposed.rows, MIN_REAL_ROWS),
);
}
+ mountMeasured = true;
}
} catch {
/* not measured yet — the ResizeObserver below will fit */
@@ -1556,16 +1604,22 @@ export function AgenticTerminal({
{
name,
workspaceId,
- // The connect-time size is a best effort. The mount-time fit above
- // already clamped the grid to the floors, so the terminal's own
- // geometry is normally safe to hand over as-is — the guards here are
- // for the one case that fit could not run at all (a grid cell still
- // mid-layout measures as nothing), where the terminal still holds
- // whatever it was constructed with. A size under a floor is treated
- // as "not measured yet"; the real one follows from `onOpen`'s fit as
- // soon as the cell settles.
- cols: term.cols >= MIN_REAL_COLS ? term.cols : 80,
- rows: term.rows >= MIN_REAL_ROWS ? term.rows : 24,
+ // The connect-time size is the tile's own measurement when there was
+ // one. The mount-time fit above already clamped the grid to the
+ // floors, so the terminal's geometry is safe to hand over as-is.
+ // When that fit could not run at all — a grid cell still mid-layout,
+ // a pane mounted hidden on the chat stage — the terminal still holds
+ // what it was constructed with, and THAT must not go out as if a tile
+ // had measured it: a running agent would be re-wrapped for 80
+ // columns no tile has, and again for the real ones a moment later
+ // (ConPTY re-flows the whole screen on each). `UNMEASURED_SIZE` says
+ // so on the wire instead; the real size follows from `onOpen`'s fit
+ // as soon as the cell settles.
+ ...(mountMeasured &&
+ term.cols >= MIN_REAL_COLS &&
+ term.rows >= MIN_REAL_ROWS
+ ? { cols: term.cols, rows: term.rows }
+ : UNMEASURED_SIZE),
appearance: appearanceRef.current,
claimOwner: openedWithClaim,
},
@@ -1897,7 +1951,7 @@ export function AgenticTerminal({
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- see file header:
// appearance/fontSize must NOT rebuild the pane (it would kill the agent).
- }, [name, workspaceId, restartToken, geometryReady]);
+ }, [name, workspaceId, restartToken, geometryReady, fontReady]);
/*
* A chat-stage switch changes a pane from `display:none` to the full canvas
diff --git a/jarvis/ui/web/frontend/src/lib/terminalFont.test.ts b/jarvis/ui/web/frontend/src/lib/terminalFont.test.ts
index 7634a3d4b2..c09f619178 100644
--- a/jarvis/ui/web/frontend/src/lib/terminalFont.test.ts
+++ b/jarvis/ui/web/frontend/src/lib/terminalFont.test.ts
@@ -13,9 +13,12 @@
*/
import { describe, it, expect, vi } from "vitest";
import {
+ FONT_WAIT_MS,
TERMINAL_FONT_STACK,
alignTerminalCells,
syncTerminalFont,
+ terminalFontSettled,
+ whenTerminalFontReady,
} from "./terminalFont";
/** A stand-in for the xterm options this module is allowed to touch. */
@@ -328,3 +331,127 @@ describe("syncTerminalFont", () => {
expect(onRemeasured).not.toHaveBeenCalled();
});
});
+
+/**
+ * A FontFaceSet whose declared faces and loaded state the test controls.
+ *
+ * Both halves matter separately: `check()` is true for a family the set has
+ * never heard of, and the app's fonts are declared by a stylesheet fetched
+ * from the network — so at start-up there is a window in which the face is
+ * not declared yet and `check()` says "loaded" for the wrong reason.
+ */
+function controlledFonts() {
+ const faces: { family: string }[] = [];
+ let loaded = false;
+ const listeners = new Set<() => void>();
+ const set = {
+ check: vi.fn(() => loaded),
+ load: vi.fn(() => Promise.resolve(loaded ? faces : [])),
+ addEventListener: (type: string, fn: () => void) => {
+ if (type === "loadingdone") listeners.add(fn);
+ },
+ removeEventListener: (_type: string, fn: () => void) => {
+ listeners.delete(fn);
+ },
+ [Symbol.iterator]: () => faces[Symbol.iterator](),
+ } as unknown as FontFaceSet;
+ return {
+ set,
+ declare: () => {
+ faces.push({ family: '"JetBrains Mono"' });
+ },
+ finishLoading: () => {
+ loaded = true;
+ for (const fn of listeners) fn();
+ },
+ listenerCount: () => listeners.size,
+ };
+}
+
+describe("terminalFontSettled", () => {
+ it("is settled where there is no font API — whatever is measured is what is drawn", () => {
+ expect(terminalFontSettled(13, { fonts: null })).toBe(true);
+ });
+
+ it("is not settled on a check() that is true only because no face is declared", () => {
+ const fonts = controlledFonts();
+ fonts.finishLoading(); // check() now answers true — for a family it does not have
+ expect(terminalFontSettled(13, { fonts: fonts.set })).toBe(false);
+ fonts.declare();
+ expect(terminalFontSettled(13, { fonts: fonts.set })).toBe(true);
+ });
+
+ it("is not settled while the declared face is still loading", () => {
+ const fonts = controlledFonts();
+ fonts.declare();
+ expect(terminalFontSettled(13, { fonts: fonts.set })).toBe(false);
+ });
+});
+
+describe("whenTerminalFontReady", () => {
+ it("resolves at once when the font is already measurable", async () => {
+ const fonts = controlledFonts();
+ fonts.declare();
+ fonts.finishLoading();
+ let resolved = false;
+ void whenTerminalFontReady(13, { fonts: fonts.set }).then(() => {
+ resolved = true;
+ });
+ await Promise.resolve();
+ expect(resolved).toBe(true);
+ });
+
+ it("waits for the face to be declared AND loaded, then resolves and stops listening", async () => {
+ vi.useFakeTimers();
+ try {
+ const fonts = controlledFonts();
+ let resolved = false;
+ void whenTerminalFontReady(13, { fonts: fonts.set }).then(() => {
+ resolved = true;
+ });
+ await vi.advanceTimersByTimeAsync(300);
+ expect(resolved).toBe(false);
+ expect(fonts.set.load).toHaveBeenCalled(); // asked by name, not left to fonts.ready
+
+ fonts.declare();
+ await vi.advanceTimersByTimeAsync(100);
+ expect(resolved).toBe(false); // declared is not loaded
+
+ fonts.finishLoading();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(resolved).toBe(true);
+ expect(fonts.listenerCount()).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("gives up after the bounded wait, so an offline pane still opens", async () => {
+ vi.useFakeTimers();
+ try {
+ const fonts = controlledFonts();
+ let resolved = false;
+ void whenTerminalFontReady(13, { fonts: fonts.set, timeoutMs: FONT_WAIT_MS }).then(
+ () => {
+ resolved = true;
+ },
+ );
+ await vi.advanceTimersByTimeAsync(FONT_WAIT_MS - 1);
+ expect(resolved).toBe(false);
+ await vi.advanceTimersByTimeAsync(2);
+ expect(resolved).toBe(true);
+ expect(fonts.listenerCount()).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("resolves at once where there is no font API at all", async () => {
+ let resolved = false;
+ void whenTerminalFontReady(13, { fonts: null }).then(() => {
+ resolved = true;
+ });
+ await Promise.resolve();
+ expect(resolved).toBe(true);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/terminalFont.ts b/jarvis/ui/web/frontend/src/lib/terminalFont.ts
index dc6e6b2875..2dbccc03bd 100644
--- a/jarvis/ui/web/frontend/src/lib/terminalFont.ts
+++ b/jarvis/ui/web/frontend/src/lib/terminalFont.ts
@@ -167,6 +167,125 @@ export function measureAdvance(
return width / SAMPLE.length;
}
+/**
+ * How long a pane waits for the display font before building its grid on the
+ * font that is there. Long enough for a cached web font (milliseconds) and a
+ * cold fetch on an ordinary connection; short enough that an offline machine,
+ * where the font never comes, still gets its terminals inside two seconds.
+ */
+export const FONT_WAIT_MS = 1500;
+
+/** Is a face for the display family declared at all — has its @font-face been parsed? */
+function displayFaceDeclared(fonts: FontFaceSet): boolean {
+ try {
+ for (const face of fonts as unknown as Iterable<FontFace>) {
+ if (face.family.replace(/["']/g, "") === DISPLAY_FAMILY.replace(/"/g, "")) {
+ return true;
+ }
+ }
+ } catch {
+ /* a FontFaceSet that cannot be iterated — treated as undeclared */
+ }
+ return false;
+}
+
+/**
+ * Can the display font be measured at `fontSize` RIGHT NOW?
+ *
+ * Two conditions, because `FontFaceSet.check()` answers "yes" for a family it
+ * has never heard of — and the app's fonts arrive through a stylesheet
+ * `@import`ed from the network, so at start-up there is a window in which no
+ * face is declared yet and `check()` is true for the wrong reason. A face has
+ * to exist AND be loaded. No font API at all (jsdom, an old engine) counts as
+ * settled: whatever is measured is the font that will be drawn.
+ */
+export function terminalFontSettled(
+ fontSize: number,
+ deps: Pick<Partial<TerminalFontDeps>, "fonts"> = {},
+): boolean {
+ const fonts = deps.fonts !== undefined ? deps.fonts : browserFonts();
+ if (!fonts) return true;
+ try {
+ return displayFaceDeclared(fonts) && fonts.check(`400 ${fontSize}px ${DISPLAY_FAMILY}`);
+ } catch {
+ return true;
+ }
+}
+
+/**
+ * Resolve once the display font can be measured at `fontSize`, or once the
+ * wait runs out — whichever comes first. Never rejects.
+ *
+ * `syncTerminalFont` below repairs a grid AFTER the font arrives, and that is
+ * enough for a pane whose agent starts with it. It is not enough for a pane
+ * that RE-JOINS a running agent: the grid it builds on the fallback font is the
+ * size it hands that agent in the very first message. Measured on the desktop
+ * (2026-08-27, Windows, text at 20px): Consolas advances 11px where JetBrains
+ * Mono advances 12px, so a 744px tile was announced as 67 columns, the agent
+ * re-wrapped for 67, the font landed, the same tile was announced as 62, and
+ * the agent re-wrapped again — and ConPTY, which re-flows the whole screen on
+ * every width change, left the two layouts on top of each other: every pane of
+ * a six-pane workspace came back from a restart as rows of one transcript cut
+ * through by fragments of the other. Nothing repairs that afterwards, because
+ * a coding agent only ever redraws its own live rows.
+ *
+ * So the pane waits here, before it builds anything, and its first measurement
+ * is of the font it will draw with. The wait is bounded: offline, the fallback
+ * IS the font, the measurement is right, and the agent hears one size.
+ */
+export function whenTerminalFontReady(
+ fontSize: number,
+ deps: Partial<TerminalFontDeps & { timeoutMs: number }> = {},
+): Promise<void> {
+ const fonts = deps.fonts !== undefined ? deps.fonts : browserFonts();
+ if (!fonts || terminalFontSettled(fontSize, { fonts })) return Promise.resolve();
+ const timeoutMs = deps.timeoutMs ?? FONT_WAIT_MS;
+ const spec = `400 ${fontSize}px ${DISPLAY_FAMILY}`;
+ return new Promise<void>((resolve) => {
+ let done = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let poll: ReturnType<typeof setInterval> | undefined;
+ const finish = () => {
+ if (done) return;
+ done = true;
+ if (timer !== undefined) clearTimeout(timer);
+ if (poll !== undefined) clearInterval(poll);
+ try {
+ fonts.removeEventListener?.("loadingdone", onLoadingDone);
+ } catch {
+ /* no event target here */
+ }
+ resolve();
+ };
+ const settledNow = () => {
+ if (terminalFontSettled(fontSize, { fonts })) finish();
+ };
+ const onLoadingDone = () => settledNow();
+ timer = setTimeout(finish, timeoutMs);
+ // Ask by name — the request `fonts.ready` would never make on its own (see
+ // the file header) — and re-ask on a poll, because a face that is not
+ // declared yet cannot be loaded yet: the @import that declares it may land
+ // any time within the wait.
+ const request = () => {
+ try {
+ void fonts.load(spec).then(settledNow, () => undefined);
+ } catch {
+ /* a family the engine refuses to parse — the poll and timeout cover it */
+ }
+ };
+ try {
+ fonts.addEventListener?.("loadingdone", onLoadingDone);
+ } catch {
+ /* no event target here */
+ }
+ request();
+ poll = setInterval(() => {
+ settledNow();
+ if (!done) request();
+ }, 50);
+ });
+}
+
function browserFonts(): FontFaceSet | null {
if (typeof document === "undefined") return null;
return document.fonts ?? null;