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.

feat(agentic-ide): remember the terminal text size across restarts

Ruben Lütke92191e1d46ec
diff --git a/jarvis/agentic_ide/ui_prefs.py b/jarvis/agentic_ide/ui_prefs.py
new file mode 100644
index 0000000000..89709b67cb
--- /dev/null
+++ b/jarvis/agentic_ide/ui_prefs.py
@@ -0,0 +1,134 @@
+"""Display preferences of the Agentic-IDE workspace, remembered per machine.
+
+Only ONE thing lives here today — how large the terminal text is — but it earns
+a backend store rather than a line of ``localStorage`` for a reason that applies
+to every display preference the workspace will ever have: **the desktop window
+does not keep browser storage between runs.** It is an embedded WebView started
+in private mode, so everything the page writes to ``localStorage`` is thrown
+away when the app closes. A preference kept only there is set again after every
+single restart, which reads to the user as "the option is gone".
+
+The store is therefore the source of truth and the page's ``localStorage`` is a
+first-paint cache: the panes open at the remembered size instead of opening at
+the default and visibly resizing a moment later.
+
+Storage is one small JSON file under the per-user data directory (never in the
+repo, never in ``jarvis.toml`` — this is a per-screen preference, not
+configuration). Writes are atomic (temp file + ``os.replace``), reads are
+defensive: a truncated or hand-edited file degrades to the defaults instead of
+breaking the workspace, and unknown keys written by a newer version are carried
+through untouched so an older one cannot silently drop them.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+from typing import Any
+
+from loguru import logger
+
+#: Terminal text size, in pixels. The bounds are not taste — below the floor
+#: xterm's glyphs stop being legible on a normal display, above the ceiling a
+#: pane holds too few columns for a coding agent's output to stay readable.
+#: Mirrored in the grid's toolbar (``AgenticGrid.tsx``) and pinned by
+#: ``tests/unit/agentic_ide/test_ui_prefs.py`` so the two cannot drift.
+FONT_MIN = 10
+FONT_MAX = 20
+FONT_DEFAULT = 13
+
+_FONT_KEY = "terminal_font_size"
+
+
+def _store_path() -> Path:
+ from jarvis.core.paths import user_data_dir
+
+ return user_data_dir() / "agentic_ide" / "ui_prefs.json"
+
+
+def _load_raw() -> dict[str, Any]:
+ path = _store_path()
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ return {}
+ except (OSError, ValueError) as exc:
+ logger.warning("Agentic IDE: unreadable UI preferences, using defaults: {}", exc)
+ return {}
+ return data if isinstance(data, dict) else {}
+
+
+def _save_raw(data: dict[str, Any]) -> bool:
+ """Write the whole preference file atomically. False when it could not be."""
+ target = _store_path()
+ try:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ tmp = target.with_suffix(".json.tmp")
+ tmp.write_text(json.dumps(data, indent=2), encoding="utf-8")
+ os.replace(tmp, target)
+ return True
+ except OSError as exc:
+ logger.warning("Agentic IDE: could not persist UI preferences: {}", exc)
+ return False
+
+
+def clamp_font_size(value: Any) -> int:
+ """The nearest usable text size to ``value``, or the default for nonsense.
+
+ Clamped rather than rejected: this is a preference, and a caller that asks
+ for 40 (a CLI typo, an older client with wider bounds) is better served with
+ the largest size that works than with an error and no change at all. The
+ effective value is always returned to the caller, so nothing has to guess
+ what was stored.
+ """
+ try:
+ size = int(value)
+ except (TypeError, ValueError):
+ return FONT_DEFAULT
+ return max(FONT_MIN, min(FONT_MAX, size))
+
+
+def has_terminal_font_size() -> bool:
+ """True when a size was actually chosen, as opposed to never set.
+
+ The difference matters exactly once: a workspace that has been used before
+ this store existed carries the user's choice in the page's ``localStorage``
+ and nowhere else. The UI reads this flag to know it may hand that older
+ choice over instead of overwriting it with the default.
+ """
+ return isinstance(_load_raw().get(_FONT_KEY), (int, float))
+
+
+def terminal_font_size() -> int:
+ """The remembered terminal text size, or the default when none was set."""
+ raw = _load_raw().get(_FONT_KEY)
+ if not isinstance(raw, (int, float)):
+ return FONT_DEFAULT
+ return clamp_font_size(raw)
+
+
+def set_terminal_font_size(value: Any) -> int:
+ """Remember a terminal text size. Returns the value that was stored.
+
+ Best-effort against the disk: a workspace must keep working on a read-only
+ or full data directory, so a failed write is logged (never silent) and the
+ clamped value is still returned — the panes resize now, they just will not
+ remember it next time.
+ """
+ size = clamp_font_size(value)
+ data = _load_raw()
+ data[_FONT_KEY] = size
+ _save_raw(data)
+ return size
+
+
+def reset() -> None:
+ """Forget every stored preference. For tests and a clean-slate reinstall."""
+ path = _store_path()
+ try:
+ path.unlink()
+ except FileNotFoundError:
+ return
+ except OSError as exc:
+ logger.warning("Agentic IDE: could not clear UI preferences: {}", exc)
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index c7aac61401..81d23f6f09 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -23,6 +23,8 @@ Endpoints (prefix ``/api/agentic-ide``):
* ``GET /interrupted`` → panes that came back and were never restarted
* ``POST /interrupted/continue`` → tell them to carry on ("continue")
* ``PUT /mode`` → focused coding mode on/off
+* ``GET /ui-preferences`` → remembered terminal text size
+* ``PUT /ui-preferences`` → remember another one (survives restarts)
* ``GET /accounts`` → which subscription new terminals use
* ``PUT /accounts/active`` → switch it (open panes keep theirs)
* ``POST /terminals`` → open one more pane (split)
@@ -286,6 +288,18 @@ class ModeRequest(BaseModel):
)
+class TerminalTextSizeRequest(BaseModel):
+ """How large the text in the workspace's terminals should be, in pixels."""
+
+ terminal_font_size: int = Field(
+ description=(
+ "Terminal text size in pixels. Values outside the supported range "
+ "are clamped to the nearest usable one rather than rejected; the "
+ "response says what was actually stored."
+ )
+ )
+
+
class ActiveAccountRequest(BaseModel):
"""Which subscription new terminals of one coding CLI should open on."""
@@ -1720,6 +1734,53 @@ async def set_mode(request: Request, req: ModeRequest) -> dict:
return {"ok": True, "focus_mode": enabled}
[email protected]("/ui-preferences", summary="Remembered workspace display preferences")
+async def get_ui_preferences() -> dict:
+ """How the workspace should look, as this machine last left it.
+
+ Today that is one thing: the size of the terminal text. It is answered by
+ the backend rather than read from the page's own storage because the desktop
+ window is an embedded WebView that starts each run with an empty one — a
+ preference kept only in the browser is forgotten on every restart.
+
+ ``stored`` says whether a size was ever chosen here. A client that still
+ holds an older, browser-only choice uses it to hand that choice over instead
+ of letting the default overwrite it.
+ """
+ from jarvis.agentic_ide import ui_prefs
+
+ return {
+ "ok": True,
+ "terminal_font_size": await asyncio.to_thread(ui_prefs.terminal_font_size),
+ "stored": await asyncio.to_thread(ui_prefs.has_terminal_font_size),
+ "min": ui_prefs.FONT_MIN,
+ "max": ui_prefs.FONT_MAX,
+ "default": ui_prefs.FONT_DEFAULT,
+ }
+
+
[email protected]("/ui-preferences", summary="Remember a workspace display preference")
+async def set_ui_preferences(req: TerminalTextSizeRequest) -> dict:
+ """Remember the terminal text size until it is changed again.
+
+ Survives closing the workspace, closing the app and restarting the machine,
+ and applies to every terminal in every workspace — one person reads at one
+ size. Open panes are re-rendered by the UI immediately; nothing is restarted
+ and no agent is interrupted by the change.
+ """
+ from jarvis.agentic_ide import ui_prefs
+
+ size = await asyncio.to_thread(ui_prefs.set_terminal_font_size, req.terminal_font_size)
+ return {
+ "ok": True,
+ "terminal_font_size": size,
+ "stored": True,
+ "min": ui_prefs.FONT_MIN,
+ "max": ui_prefs.FONT_MAX,
+ "default": ui_prefs.FONT_DEFAULT,
+ }
+
+
@router.get("/accounts", summary="Which subscription new terminals use")
async def get_accounts() -> dict:
"""The active subscription of every coding CLI, with its display name.
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
index 74708bbc1c..3fdda7e0f5 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
@@ -69,6 +69,23 @@ vi.mock("@/lib/agenticIdeApi", () => ({
})),
markPaneNotificationsRead: vi.fn(async () => 0),
clearPaneNotifications: vi.fn(async () => undefined),
+ // The remembered terminal text size, read once per mounted workspace.
+ // Answers "nothing chosen yet" by default so these tests see the default
+ // size; the text-size tests give it a stored one.
+ fetchTerminalUiPreferences: vi.fn(async () => ({
+ terminal_font_size: 13,
+ stored: false,
+ min: 10,
+ max: 20,
+ default: 13,
+ })),
+ saveTerminalFontSize: vi.fn(async (size: number) => ({
+ terminal_font_size: size,
+ stored: true,
+ min: 10,
+ max: 20,
+ default: 13,
+ })),
}));
// The grid follows the app theme for its terminal colours; these tests render
@@ -105,6 +122,7 @@ vi.mock("./AgenticTerminal", () => ({
onArrangeStart,
arranging,
layoutBusy,
+ fontSize,
}: {
name: string;
maximized?: boolean;
@@ -121,6 +139,7 @@ vi.mock("./AgenticTerminal", () => ({
onArrangeStart?: (event: PointerEventLike) => void;
arranging?: boolean;
layoutBusy?: boolean;
+ fontSize?: number;
}) => {
paneRenders.set(name, (paneRenders.get(name) ?? 0) + 1);
return (
@@ -138,6 +157,9 @@ vi.mock("./AgenticTerminal", () => ({
// The real pane stops refitting its terminal while this is on. Read here
// because it is the grid's job to say WHEN the geometry is in motion.
data-layout-busy={layoutBusy ? "yes" : "no"}
+ // The size the terminal text is drawn at. Read here because the point of
+ // remembering it is that the PANES come back at that size.
+ data-font-size={String(fontSize ?? "")}
>
{name}
{/* Stands for the pane header, which is the grip in the real component. */}
@@ -2409,3 +2431,83 @@ describe("chat view", () => {
);
});
});
+
+describe("terminal text size", () => {
+ const FONT_KEY = "jarvis.agenticIde.terminalFontSize";
+
+ beforeEach(() => {
+ // Restated per test: `clearAllMocks` empties the call list but keeps the
+ // implementation, so a size one test stores would still be answered to the
+ // next one.
+ vi.mocked(api.fetchTerminalUiPreferences).mockResolvedValue({
+ terminal_font_size: 13,
+ stored: false,
+ min: 10,
+ max: 20,
+ default: 13,
+ });
+ });
+
+ afterEach(() => {
+ window.localStorage.removeItem(FONT_KEY);
+ });
+
+ const openViewMenu = () =>
+ fireEvent.click(screen.getByTestId("agentic-view-menu"));
+
+ it("opens the panes at the size the backend remembers", async () => {
+ // The reason this comes from the backend and not from localStorage: the
+ // desktop window is a WebView that starts every run with empty browser
+ // storage, so a size kept only in the page is gone after each restart.
+ vi.mocked(api.fetchTerminalUiPreferences).mockResolvedValue({
+ terminal_font_size: 17,
+ stored: true,
+ min: 10,
+ max: 20,
+ default: 13,
+ });
+ renderGrid();
+
+ await waitFor(() =>
+ expect(screen.getByTestId("pane-Mika").getAttribute("data-font-size")).toBe("17"),
+ );
+ openViewMenu();
+ expect(screen.getByTestId("agentic-view-menu-panel").textContent).toContain("17");
+ });
+
+ it("hands a newly chosen size to the backend", async () => {
+ renderGrid();
+ await waitFor(() => expect(api.fetchTerminalUiPreferences).toHaveBeenCalled());
+
+ openViewMenu();
+ fireEvent.click(screen.getByLabelText("Larger text"));
+
+ await waitFor(() => expect(api.saveTerminalFontSize).toHaveBeenCalledWith(14));
+ expect(screen.getByTestId("pane-Mika").getAttribute("data-font-size")).toBe("14");
+ });
+
+ it("adopts a size chosen before the backend remembered them", async () => {
+ // Upgrade path. Somebody who set 16 in an older build has that number in
+ // this window's storage and nowhere else; the first read must hand it over
+ // rather than let the default quietly replace it.
+ window.localStorage.setItem(FONT_KEY, "16");
+ renderGrid();
+
+ await waitFor(() => expect(api.saveTerminalFontSize).toHaveBeenCalledWith(16));
+ expect(screen.getByTestId("pane-Mika").getAttribute("data-font-size")).toBe("16");
+ });
+
+ it("keeps working when the size cannot be read", async () => {
+ // An older backend, or a request that failed. The panes still open and the
+ // buttons still resize them — only the memory is missing.
+ vi.mocked(api.fetchTerminalUiPreferences).mockRejectedValue(new Error("404"));
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ renderGrid();
+
+ await waitFor(() => expect(warn).toHaveBeenCalled());
+ openViewMenu();
+ fireEvent.click(screen.getByLabelText("Smaller text"));
+ expect(screen.getByTestId("pane-Mika").getAttribute("data-font-size")).toBe("12");
+ warn.mockRestore();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
index f514171a4c..3d02158c73 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
@@ -401,6 +401,13 @@ function writePosition(node: HTMLElement, style: React.CSSProperties): void {
*
* localStorage rather than config: this is a per-screen display preference of
* this browser profile, not something worth a round-trip and a config write.
+ *
+ * The text size is the exception and is kept by the BACKEND as well (see
+ * `fetchTerminalUiPreferences`). The desktop window is an embedded WebView that
+ * starts every run with empty browser storage, so a size kept only here is
+ * forgotten on each restart — which reads as the control having stopped
+ * working. Its localStorage entry stays as the first-paint cache so the panes
+ * open at the remembered size instead of visibly resizing a moment later.
*/
const APPEARANCE_KEY = "jarvis.agenticIde.terminalAppearance";
const FONT_KEY = "jarvis.agenticIde.terminalFontSize";
@@ -529,6 +536,44 @@ export function AgenticGrid({
const setFontSize = useCallback((next: number) => {
setFontSizeState(next);
writeStored(FONT_KEY, String(next));
+ // The backend is what makes the choice survive a restart; the line above is
+ // only this window's cache. A failed write is reported rather than
+ // swallowed — the panes still resize, they just would not remember it.
+ void saveTerminalFontSize(next).catch((err) => {
+ console.warn("Agentic IDE: terminal text size not remembered:", err);
+ });
+ }, []);
+
+ // Pick the remembered size back up. Runs once per mounted workspace: the size
+ // is one person's reading preference, not a property of a project, so it is
+ // the same in every workspace and never re-read on a switch.
+ useEffect(() => {
+ let alive = true;
+ fetchTerminalUiPreferences()
+ .then((prefs) => {
+ if (!alive) return;
+ if (prefs.stored) {
+ setFontSizeState(prefs.terminal_font_size);
+ writeStored(FONT_KEY, String(prefs.terminal_font_size));
+ return;
+ }
+ // Nothing stored yet, but this window still holds a size chosen before
+ // the backend kept them. Hand that choice over instead of letting the
+ // default silently replace it — otherwise upgrading resets it once.
+ const local = storedFontSize();
+ if (local === null) return;
+ void saveTerminalFontSize(local).catch((err) => {
+ console.warn("Agentic IDE: terminal text size not remembered:", err);
+ });
+ })
+ .catch((err) => {
+ // Older backend or a request that failed: keep the cached size and say
+ // why it may not stick, rather than looking like it worked.
+ console.warn("Agentic IDE: could not read the stored terminal text size:", err);
+ });
+ return () => {
+ alive = false;
+ };
}, []);
const [target, setTarget] = useState(
session.terminals.find(takesPrompts)?.name ?? "",
diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
index 84d49391e5..5e82eb2080 100644
--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
@@ -1109,6 +1109,46 @@ export async function setFocusMode(enabled: boolean): Promise<boolean> {
return body.focus_mode;
}
+/**
+ * The workspace display preferences the backend remembers for this machine.
+ *
+ * `stored` is false until a size has actually been chosen — the difference
+ * between "the user picked 13" and "nobody ever picked anything", which is what
+ * lets an older choice living only in this page's `localStorage` be handed over
+ * rather than overwritten by the default.
+ */
+export interface TerminalUiPreferences {
+ terminal_font_size: number;
+ stored: boolean;
+ min: number;
+ max: number;
+ default: number;
+}
+
+/**
+ * Read the remembered terminal text size.
+ *
+ * Deliberately a backend read: the desktop window is an embedded WebView that
+ * starts every run with empty browser storage, so a preference kept only in
+ * `localStorage` is forgotten on each restart.
+ */
+export function fetchTerminalUiPreferences(): Promise<TerminalUiPreferences> {
+ return getJson<TerminalUiPreferences>("/api/agentic-ide/ui-preferences");
+}
+
+/** Remember a terminal text size until it is changed again. */
+export async function saveTerminalFontSize(
+ size: number,
+): Promise<TerminalUiPreferences> {
+ const res = await fetch("/api/agentic-ide/ui-preferences", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ terminal_font_size: size }),
+ });
+ if (!res.ok) throw new Error(await detail(res));
+ return (await res.json()) as TerminalUiPreferences;
+}
+
/**
* One dropped file after the backend has read what is actually in it.
*
diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
index b156808f53..2b2f538c2f 100644
--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
@@ -89,6 +89,21 @@ vi.mock("@/lib/agenticIdeApi", () => ({
workspace_id: null,
terminals: [],
})),
+ // The remembered terminal text size, read once when the grid mounts.
+ fetchTerminalUiPreferences: vi.fn(async () => ({
+ terminal_font_size: 13,
+ stored: false,
+ min: 10,
+ max: 20,
+ default: 13,
+ })),
+ saveTerminalFontSize: vi.fn(async (size: number) => ({
+ terminal_font_size: size,
+ stored: true,
+ min: 10,
+ max: 20,
+ default: 13,
+ })),
}));
import { AgenticIdeView } from "./AgenticIdeView";
diff --git a/tests/unit/agentic_ide/conftest.py b/tests/unit/agentic_ide/conftest.py
index 8a96a0a4da..3c007cc3c9 100644
--- a/tests/unit/agentic_ide/conftest.py
+++ b/tests/unit/agentic_ide/conftest.py
@@ -26,6 +26,9 @@ guarantee that only holds until somebody writes the next test.
4. **The agent-account store.** Panes now record which subscription they run on,
which means opening one reads (and resuming one could write) the developer's
real account list. Same store, same failure class as 1 and 2.
+5. **The workspace display preferences.** The remembered terminal text size is
+ kept outside the repo too, so an unredirected test would resize the panes of
+ whoever ran it.
"""
from __future__ import annotations
@@ -48,6 +51,22 @@ def _resume_store_in_tmp(
return target
[email protected](autouse=True)
+def _ui_prefs_in_tmp(
+ tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch
+) -> Path:
+ """Point the workspace display preferences at a throwaway file.
+
+ Same store, same failure class as 1 and 2 above: a test that writes a text
+ size would change the size of the developer's own terminals.
+ """
+ from jarvis.agentic_ide import ui_prefs
+
+ target = tmp_path_factory.mktemp("ui-prefs") / "ui_prefs.json"
+ monkeypatch.setattr(ui_prefs, "_store_path", lambda: target)
+ return target
+
+
@pytest.fixture(autouse=True)
def _never_touch_real_agent_configs(monkeypatch: pytest.MonkeyPatch) -> None:
"""Keep the trust pre-seed away from the developer's own CLI configuration."""
diff --git a/tests/unit/agentic_ide/test_ui_prefs.py b/tests/unit/agentic_ide/test_ui_prefs.py
new file mode 100644
index 0000000000..9047f7e67a
--- /dev/null
+++ b/tests/unit/agentic_ide/test_ui_prefs.py
@@ -0,0 +1,146 @@
+"""The terminal text size, and the one property that matters about it: it stays.
+
+The control itself has existed for a long time. What did not exist was memory —
+the size lived in the desktop window's browser storage, and that window is an
+embedded WebView started with an empty one on every run, so the panes were back
+at the default after each restart. To the person using it that is not "a cache
+was cleared", it is "the option is gone".
+
+These tests therefore pin the store rather than the widget: a size that was set
+is still the size a fresh process reads, nonsense does not break the workspace,
+and the bounds the toolbar enforces are the bounds the backend enforces.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.agentic_ide import ui_prefs
+
+
+def client() -> TestClient:
+ from jarvis.ui.web.agentic_ide_routes import router
+
+ app = FastAPI()
+ app.include_router(router)
+ return TestClient(app)
+
+
+def test_a_workspace_that_was_never_touched_reads_the_default() -> None:
+ """No file, no error — the default size and an honest "nobody chose this"."""
+ assert ui_prefs.terminal_font_size() == ui_prefs.FONT_DEFAULT
+ assert ui_prefs.has_terminal_font_size() is False
+
+
+def test_a_chosen_size_is_still_there_afterwards() -> None:
+ """The whole feature: set once, read back the same, without setting it again."""
+ assert ui_prefs.set_terminal_font_size(17) == 17
+
+ assert ui_prefs.terminal_font_size() == 17
+ assert ui_prefs.has_terminal_font_size() is True
+
+
+def test_the_stored_size_outlives_the_process_that_set_it(_ui_prefs_in_tmp: Path) -> None:
+ """Written to disk, not held in a module-level variable.
+
+ Read back through the file rather than through the module, because an
+ in-memory cache would pass a plain round-trip test and still lose the size
+ on the restart this feature exists for.
+ """
+ ui_prefs.set_terminal_font_size(18)
+
+ on_disk = json.loads(_ui_prefs_in_tmp.read_text(encoding="utf-8"))
+
+ assert on_disk["terminal_font_size"] == 18
+
+
+def test_a_size_nobody_can_read_is_clamped_rather_than_refused() -> None:
+ """A CLI typo resizes the terminals; it does not fail the request.
+
+ Both directions, and the returned value always says what was really stored
+ so no caller has to guess.
+ """
+ assert ui_prefs.set_terminal_font_size(400) == ui_prefs.FONT_MAX
+ assert ui_prefs.set_terminal_font_size(1) == ui_prefs.FONT_MIN
+ assert ui_prefs.set_terminal_font_size("not a number") == ui_prefs.FONT_DEFAULT
+
+
+def test_a_damaged_preference_file_degrades_to_the_default(_ui_prefs_in_tmp: Path) -> None:
+ """A half-written or hand-edited file must not take the workspace down."""
+ _ui_prefs_in_tmp.parent.mkdir(parents=True, exist_ok=True)
+ _ui_prefs_in_tmp.write_text("{ this is not json", encoding="utf-8")
+
+ assert ui_prefs.terminal_font_size() == ui_prefs.FONT_DEFAULT
+ assert ui_prefs.has_terminal_font_size() is False
+ # And it heals: the next write replaces the damaged file rather than
+ # failing against it forever.
+ assert ui_prefs.set_terminal_font_size(15) == 15
+ assert ui_prefs.terminal_font_size() == 15
+
+
+def test_a_preference_written_by_a_newer_version_is_kept(_ui_prefs_in_tmp: Path) -> None:
+ """Unknown keys survive a write from an older build.
+
+ Two installs sharing one data directory (a synced home, a rollback) must not
+ silently drop each other's preferences.
+ """
+ _ui_prefs_in_tmp.parent.mkdir(parents=True, exist_ok=True)
+ _ui_prefs_in_tmp.write_text(json.dumps({"future_preference": "keep me"}), encoding="utf-8")
+
+ ui_prefs.set_terminal_font_size(14)
+
+ on_disk = json.loads(_ui_prefs_in_tmp.read_text(encoding="utf-8"))
+ assert on_disk["future_preference"] == "keep me"
+ assert on_disk["terminal_font_size"] == 14
+
+
+def test_the_route_answers_with_the_size_and_its_bounds(client: TestClient) -> None:
+ """The CLI-first half: the toolbar is one client of this, a terminal another."""
+ body = client.get("/api/agentic-ide/ui-preferences").json()
+
+ assert body["terminal_font_size"] == ui_prefs.FONT_DEFAULT
+ assert body["stored"] is False
+ assert (body["min"], body["max"]) == (ui_prefs.FONT_MIN, ui_prefs.FONT_MAX)
+
+
+def test_the_route_remembers_a_size(client: TestClient) -> None:
+ """PUT it, and every later reader — UI, CLI, next boot — sees that size."""
+ saved = client.put(
+ "/api/agentic-ide/ui-preferences", json={"terminal_font_size": 16}
+ ).json()
+
+ assert saved["terminal_font_size"] == 16
+ assert saved["stored"] is True
+ assert client.get("/api/agentic-ide/ui-preferences").json()["terminal_font_size"] == 16
+
+
+def test_the_route_clamps_instead_of_erroring(client: TestClient) -> None:
+ """An out-of-range size is a 200 with the effective value, not a 422."""
+ res = client.put("/api/agentic-ide/ui-preferences", json={"terminal_font_size": 99})
+
+ assert res.status_code == 200
+ assert res.json()["terminal_font_size"] == ui_prefs.FONT_MAX
+
+
+def test_the_toolbar_and_the_backend_agree_on_the_bounds() -> None:
+ """Anti-drift: the same three numbers live in Python and in the grid.
+
+ The toolbar clamps what its buttons offer and the backend clamps what it
+ stores. If those drift apart, the ``+`` button stops at one number while the
+ stored value stops at another, and the size silently changes on the next
+ restart — the exact class of bug this store was added to end.
+ """
+ grid = (
+ Path(__file__).resolve().parents[3]
+ / "jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx"
+ ).read_text(encoding="utf-8")
+
+ assert f"const FONT_MIN = {ui_prefs.FONT_MIN};" in grid
+ assert f"const FONT_MAX = {ui_prefs.FONT_MAX};" in grid
+ assert f"storedFontSize() ?? {ui_prefs.FONT_DEFAULT}" in grid