Skip to content

The agent that grows with you

fix(desktop): the preferences store never drops keys on a bad read or a fresh seed

Teknium2eec5f3632c2
diff --git a/apps/desktop/electron/ui-preferences.test.ts b/apps/desktop/electron/ui-preferences.test.ts
index 7909b207fa0..37020cc6e34 100644
--- a/apps/desktop/electron/ui-preferences.test.ts
+++ b/apps/desktop/electron/ui-preferences.test.ts
@@ -8,7 +8,7 @@ import { promisify } from 'node:util'
import { afterEach, test } from 'vitest'
import { resolveDesktopHermesHome } from './data-paths'
-import { readUiPreferences, uiPreferencesPath, writeUiPreferences } from './ui-preferences'
+import { readUiPreferences, uiPreferencesPath, uiPreferencesRoot, writeUiPreferences } from './ui-preferences'
// Native Desktop (this module) and the Webapp's Python server must land on ONE
// file and merge into it without losing each other's keys (#145213).
@@ -35,13 +35,17 @@ function pythonEnv(home: string, hermesHome: string): NodeJS.ProcessEnv {
const PY_PATH = 'from hermes_cli.ui_preferences import store_path; print(store_path())'
+/** The file main's IPC registers for this HERMES_HOME (registerUiPreferencesIpc). */
+const electronStorePath = (home: string, hermesHome: string) =>
+ uiPreferencesPath(uiPreferencesRoot(resolveDesktopHermesHome({ env: { HERMES_HOME: hermesHome }, home })))
+
test('native Desktop and the Webapp server resolve the same store from a profile home', () => {
const home = scratchHome()
const root = path.join(home, 'custom-root')
const profileHome = path.join(root, 'profiles', 'coder')
fs.mkdirSync(profileHome, { recursive: true })
- const electronFile = uiPreferencesPath(resolveDesktopHermesHome({ env: { HERMES_HOME: profileHome }, home }))
+ const electronFile = electronStorePath(home, profileHome)
const pythonFile = execFileSync(python, ['-c', PY_PATH], {
cwd: repo,
@@ -49,16 +53,38 @@ test('native Desktop and the Webapp server resolve the same store from a profile
env: pythonEnv(home, profileHome)
}).trim()
- assert.equal(electronFile, path.join(root, 'ui-preferences.json'))
+ assert.equal(electronFile, path.join(fs.realpathSync(root), 'ui-preferences.json'))
assert.equal(pythonFile, electronFile)
})
+test.skipIf(process.platform === 'win32')(
+ 'a symlinked profile directory still resolves its root, the same store on both sides',
+ () => {
+ const home = scratchHome()
+ const root = path.join(home, '.hermes')
+ const elsewhere = path.join(home, 'elsewhere', 'coder')
+ fs.mkdirSync(path.join(root, 'profiles'), { recursive: true })
+ fs.mkdirSync(elsewhere, { recursive: true })
+ fs.symlinkSync(elsewhere, path.join(root, 'profiles', 'coder'))
+ const profileHome = path.join(root, 'profiles', 'coder')
+
+ const pythonFile = execFileSync(python, ['-c', PY_PATH], {
+ cwd: repo,
+ encoding: 'utf8',
+ env: pythonEnv(home, profileHome)
+ }).trim()
+
+ assert.equal(electronStorePath(home, profileHome), path.join(fs.realpathSync(root), 'ui-preferences.json'))
+ assert.equal(pythonFile, electronStorePath(home, profileHome))
+ }
+)
+
test('a custom home inside the default home resolves the same store on both sides', () => {
const home = scratchHome()
const sandbox = path.join(home, '.hermes', 'sandbox')
fs.mkdirSync(sandbox, { recursive: true })
- const electronFile = uiPreferencesPath(resolveDesktopHermesHome({ env: { HERMES_HOME: sandbox }, home }))
+ const electronFile = electronStorePath(home, sandbox)
const pythonFile = execFileSync(python, ['-c', PY_PATH], {
cwd: repo,
@@ -66,7 +92,7 @@ test('a custom home inside the default home resolves the same store on both side
env: pythonEnv(home, sandbox)
}).trim()
- assert.equal(electronFile, path.join(sandbox, 'ui-preferences.json'))
+ assert.equal(electronFile, path.join(fs.realpathSync(sandbox), 'ui-preferences.json'))
assert.equal(fs.realpathSync(path.dirname(pythonFile)), fs.realpathSync(path.dirname(electronFile)))
})
@@ -103,13 +129,46 @@ for n in range(25):
assert.equal(fs.existsSync(`${file}.lock`), false)
})
-test('the one-time localStorage import never overwrites a store that exists', async () => {
+test('a client’s localStorage import only adds the keys a store lacks', async () => {
const root = scratchHome()
const file = uiPreferencesPath(root)
await writeUiPreferences(file, { values: { 'hermes-desktop-mode-v1': 'dark' } })
- const seeded = await writeUiPreferences(file, { seed: true, values: { 'hermes-desktop-mode-v1': 'light' } })
- assert.deepEqual(seeded, { exists: true, revision: 1, values: { 'hermes-desktop-mode-v1': 'dark' } })
- assert.deepEqual(readUiPreferences(file).values, { 'hermes-desktop-mode-v1': 'dark' })
+ const seeded = await writeUiPreferences(file, {
+ seed: true,
+ values: { 'hermes-desktop-mode-v1': 'light', 'hermes-desktop-theme-v2': 'nous' }
+ })
+
+ assert.deepEqual(seeded.values, { 'hermes-desktop-mode-v1': 'dark', 'hermes-desktop-theme-v2': 'nous' })
+ assert.deepEqual(readUiPreferences(file).values, seeded.values)
})
+
+// Only a missing file is "no store": merging over a store that exists but
+// cannot be read (EACCES, a Windows AV lock, EMFILE) dropped every other key.
+test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(
+ 'neither writer merges over a store it cannot read',
+ async () => {
+ const home = scratchHome()
+ const file = uiPreferencesPath(home)
+ await writeUiPreferences(file, { values: { 'hermes-desktop-theme-v2': 'nous', 'hermes.desktop.keybinds': '{}' } })
+ const before = fs.readFileSync(file, 'utf8')
+ fs.chmodSync(file, 0)
+
+ try {
+ await assert.rejects(writeUiPreferences(file, { values: { 'hermes-desktop-mode-v1': 'dark' } }), /unreadable/)
+
+ const pythonWrite = promisify(execFile)(
+ python,
+ ['-c', 'from hermes_cli.ui_preferences import write_preferences as w; w({"hermes-desktop-mode-v1": "dark"})'],
+ { cwd: repo, env: pythonEnv(home, home) }
+ )
+
+ await assert.rejects(pythonWrite, /PreferencesBusy: preferences store is unreadable/)
+ } finally {
+ fs.chmodSync(file, 0o600)
+ }
+
+ assert.equal(fs.readFileSync(file, 'utf8'), before)
+ }
+)
diff --git a/apps/desktop/electron/ui-preferences.ts b/apps/desktop/electron/ui-preferences.ts
index d88e28ca7b2..b0cbe91d542 100644
--- a/apps/desktop/electron/ui-preferences.ts
+++ b/apps/desktop/electron/ui-preferences.ts
@@ -6,10 +6,14 @@
// still reads and writes ITS OWN machine's file.
//
// On-disk contract, kept in lockstep with the Python writer:
-// { "version": 1, "revision": <int>, "values": { <key>: <string> } }
+// { "version": 1, "generation": <str>, "revision": <int>, "values": { <key>: <string> } }
// A write merges per key under the `<store>.lock` directory lock (mkdir is
// atomic on every OS and in Python), bumps `revision`, and lands by temp file +
-// rename. A null value deletes; a `seed` write applies only with no store yet.
+// rename. A null value deletes. A `seed` write (a client's first contact with a
+// generation) only adds the keys the store lacks. A write that finds no
+// readable store (missing, or corrupt and kept aside as `<store>.corrupt-<ms>`)
+// starts a new generation, which every window rejoins. Only a missing file
+// reads as no store: any other read failure refuses the write.
import { randomBytes } from 'node:crypto'
import fs from 'node:fs'
import path from 'node:path'
@@ -27,6 +31,8 @@ const WATCH_INTERVAL_MS = 1500
export interface UiPreferencesSnapshot {
exists: boolean
+ /** One store's lifetime; a replaced (deleted or corrupt) store gets a new one. */
+ generation?: string
revision: number
values: Record<string, string>
}
@@ -38,6 +44,17 @@ export interface UiPreferencesWrite {
export const uiPreferencesPath = (hermesHome: string) => path.join(hermesHome, UI_PREFERENCES_FILE)
+/** The store's directory for main's root home, through symlinks, as the Python
+ * writer's `store_path()` resolves it: a symlinked root or profile directory
+ * must not split the machine into two stores. */
+export function uiPreferencesRoot(hermesHome: string): string {
+ try {
+ return fs.realpathSync.native(hermesHome)
+ } catch {
+ return path.resolve(hermesHome)
+ }
+}
+
const sanitize = (values: unknown): Record<string, string> =>
values && typeof values === 'object' && !Array.isArray(values)
? Object.fromEntries(
@@ -45,33 +62,86 @@ const sanitize = (values: unknown): Record<string, string> =>
)
: {}
-/** Synchronous so the preload can hand the first paint a hydrated snapshot. */
-export function readUiPreferences(file: string): UiPreferencesSnapshot {
+interface StoreRead {
+ corrupt: boolean
+ snapshot: UiPreferencesSnapshot
+}
+
+function readStore(file: string): StoreRead {
let raw: string
try {
raw = fs.readFileSync(file, 'utf8')
- } catch {
- return { exists: false, revision: 0, values: {} }
+ } catch (error) {
+ // Only a missing file is no store. EACCES, EBUSY, EMFILE… say nothing about
+ // the content, and a write merging over them would drop every key.
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+ return { corrupt: false, snapshot: { exists: false, revision: 0, values: {} } }
+ }
+
+ throw new Error(`preferences store is unreadable: ${(error as Error).message}`)
}
- let doc: { revision?: unknown; values?: unknown } = {}
+ let doc: unknown = null
try {
- const parsed = JSON.parse(raw.replace(/^\uFEFF/, '')) as unknown
-
- doc = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
+ doc = JSON.parse(raw.replace(/^\uFEFF/, '')) as unknown
} catch {
- // A corrupt file reads as an empty existing store; the next write replaces it whole.
+ // Corrupt: no store, so clients re-import into a fresh generation.
+ }
+
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)) {
+ return { corrupt: true, snapshot: { exists: false, revision: 0, values: {} } }
}
+ const { generation, revision, values } = doc as { generation?: unknown; revision?: unknown; values?: unknown }
+
return {
- exists: true,
- revision: Number.isInteger(doc.revision) ? (doc.revision as number) : 0,
- values: sanitize(doc.values)
+ corrupt: false,
+ snapshot: {
+ exists: true,
+ generation: typeof generation === 'string' ? generation : '',
+ revision: Number.isInteger(revision) ? (revision as number) : 0,
+ values: sanitize(values)
+ }
}
}
+/** Synchronous so the preload can hand the first paint a hydrated snapshot.
+ * Throws when the file exists but cannot be read. */
+export function readUiPreferences(file: string): UiPreferencesSnapshot {
+ return readStore(file).snapshot
+}
+
+/** For the paths that must never throw (the preload's first paint, the
+ * watcher): an unreadable store is simply not known yet. */
+function tryReadUiPreferences(file: string): null | UiPreferencesSnapshot {
+ try {
+ return readUiPreferences(file)
+ } catch {
+ return null
+ }
+}
+
+function mergeValues(current: Record<string, string>, write: UiPreferencesWrite): Record<string, string> {
+ const values = { ...current }
+
+ for (const [key, value] of Object.entries(write.values)) {
+ if (write.seed) {
+ // A client's first contact: fill what the store lacks, never overwrite or delete.
+ if (value !== null && !(key in values)) {
+ values[key] = value
+ }
+ } else if (value === null) {
+ delete values[key]
+ } else {
+ values[key] = value
+ }
+ }
+
+ return values
+}
+
/** The IPC payload, validated: anything else from a renderer is refused whole. */
export function parseUiPreferencesWrite(payload: unknown): UiPreferencesWrite {
const { seed, values } = (payload && typeof payload === 'object' ? payload : {}) as {
@@ -182,21 +252,8 @@ export function writeUiPreferences(file: string, write: UiPreferencesWrite): Pro
await fs.promises.mkdir(path.dirname(file), { recursive: true })
return withStoreLock(file, async stillOurs => {
- const current = readUiPreferences(file)
-
- if (write.seed && current.exists) {
- return current
- }
-
- const values = { ...current.values }
-
- for (const [key, value] of Object.entries(write.values)) {
- if (value === null) {
- delete values[key]
- } else {
- values[key] = value
- }
- }
+ const { corrupt, snapshot: current } = readStore(file)
+ const values = mergeValues(current.values, write)
const entries = Object.entries(values)
@@ -207,11 +264,12 @@ export function writeUiPreferences(file: string, write: UiPreferencesWrite): Pro
throw new Error('preferences store is full')
}
- if (current.exists && JSON.stringify(values) === JSON.stringify(current.values)) {
+ if (JSON.stringify(values) === JSON.stringify(current.values) && (current.exists || entries.length === 0)) {
return current
}
const revision = current.revision + 1
+ const generation = current.generation || randomBytes(8).toString('hex')
if (!(await stillOurs())) {
// Held past the stale limit and broken by another writer: replacing the
@@ -219,9 +277,14 @@ export function writeUiPreferences(file: string, write: UiPreferencesWrite): Pro
throw new Error('preferences store is busy')
}
- await replaceAtomically(file, `${JSON.stringify({ version: 1, revision, values }, null, 2)}\n`)
+ if (corrupt) {
+ // Kept aside, never silently replaced: it may hold preferences worth recovering.
+ await fs.promises.copyFile(file, `${file}.corrupt-${Date.now()}`)
+ }
+
+ await replaceAtomically(file, `${JSON.stringify({ version: 1, generation, revision, values }, null, 2)}\n`)
- return { exists: true, revision, values }
+ return { exists: true, generation, revision, values }
})
})
@@ -249,18 +312,24 @@ export interface UiPreferencesIpcDeps {
* a cheap stat poll), is pushed to every window so open ones follow live.
*/
export function registerUiPreferencesIpc({ ipcMain, hermesHome, broadcast }: UiPreferencesIpcDeps): () => void {
- const file = uiPreferencesPath(hermesHome)
- let lastRevision = readUiPreferences(file).revision
+ const file = uiPreferencesPath(uiPreferencesRoot(hermesHome))
+
+ const stamp = (snapshot: null | UiPreferencesSnapshot) =>
+ snapshot ? `${snapshot.generation ?? ''}:${snapshot.revision}:${snapshot.exists}` : null
+
+ let last = stamp(tryReadUiPreferences(file))
+
+ const publish = (snapshot: null | UiPreferencesSnapshot) => {
+ const next = stamp(snapshot)
- const publish = (snapshot: UiPreferencesSnapshot) => {
- if (snapshot.revision !== lastRevision) {
- lastRevision = snapshot.revision
+ if (snapshot && next !== last) {
+ last = next
broadcast(snapshot)
}
}
ipcMain.on('hermes:ui-preferences:snapshot', event => {
- event.returnValue = readUiPreferences(file)
+ event.returnValue = tryReadUiPreferences(file)
})
ipcMain.handle('hermes:ui-preferences:read', () => readUiPreferences(file))
ipcMain.handle('hermes:ui-preferences:write', async (_event, payload) => {
@@ -271,7 +340,7 @@ export function registerUiPreferencesIpc({ ipcMain, hermesHome, broadcast }: UiP
return snapshot
})
- const onStat = () => publish(readUiPreferences(file))
+ const onStat = () => publish(tryReadUiPreferences(file))
fs.watchFile(file, { interval: WATCH_INTERVAL_MS, persistent: false }, onStat)
diff --git a/hermes_cli/ui_preferences.py b/hermes_cli/ui_preferences.py
index 749bb4996a7..b412aa9cfef 100644
--- a/hermes_cli/ui_preferences.py
+++ b/hermes_cli/ui_preferences.py
@@ -11,7 +11,13 @@ Both writers share the on-disk contract, so keep the two in lockstep:
* document ``{"version": 1, "revision": <int>, "values": {<key>: <string>}}``;
* a write merges per key under the ``<store>.lock`` directory lock (``mkdir`` is atomic on every
OS and in Node), bumps ``revision`` and lands by temp file + rename; a ``None`` value deletes;
-* a ``seed`` write (the one-time localStorage import) applies only when no document exists.
+* ``generation`` names one store's lifetime: a write that finds no readable store (missing, or
+ corrupt and kept aside as ``<store>.corrupt-<ms>``) starts a new one, and every window rejoins it
+ (re-imports its own values, then follows it) whatever its revision high-water mark was;
+* a ``seed`` write (a client's first contact with a generation) only ADDS the keys the store lacks,
+ so the client that has data fills a store an empty client created, and nothing is overwritten;
+* only a missing file reads as "no store": any other read failure refuses the write
+ (:class:`PreferencesBusy`) instead of merging over nothing.
Values are opaque strings the renderer already kept in localStorage. Only keys under the Desktop
prefixes are accepted; the renderer's allowlist decides which of those are preferences and keeps
@@ -20,15 +26,17 @@ credentials, grants and per-window state out.
from __future__ import annotations
+import json
import os
import secrets
+import shutil
import threading
import time
from contextlib import contextmanager
from pathlib import Path
from typing import Callable, Iterator, Mapping, Optional
-from utils import atomic_json_write, read_json_or_empty
+from utils import atomic_json_write
STORE_NAME = "ui-preferences.json"
KEY_PREFIXES = ("hermes.desktop.", "hermes-desktop-")
@@ -53,14 +61,16 @@ class PreferencesBusy(RuntimeError):
def store_path(root: Optional[Path] = None) -> Path:
"""The machine's preferences file, resolved by the same rule native Desktop applies to its
- ``HERMES_HOME`` (``resolveDesktopHermesHome``): a profile home (``<root>/profiles/<name>``)
- names its root, any other home is its own root. Every profile one process serves maps to the
- same root, so this read is profile-independent by design (not a launch-profile leak)."""
+ ``HERMES_HOME`` (``resolveDesktopHermesHome`` + ``uiPreferencesRoot``): a profile home
+ (``<root>/profiles/<name>``, judged on the path as given, so a symlinked profile directory
+ still names its root) names its root, any other home is its own root, and that root is then
+ resolved through symlinks on both sides. Every profile one process serves maps to the same
+ root, so this read is profile-independent by design (not a launch-profile leak)."""
if root is None:
from hermes_constants import get_hermes_home
- home = Path(get_hermes_home()).resolve()
- root = home.parent.parent if home.parent.name.lower() == "profiles" else home
+ home = Path(os.path.abspath(get_hermes_home()))
+ root = (home.parent.parent if home.parent.name.lower() == "profiles" else home).resolve()
return Path(root) / STORE_NAME
@@ -70,20 +80,40 @@ def _sanitize(values: object) -> dict[str, str]:
return {k: v for k, v in values.items() if isinstance(k, str) and isinstance(v, str)}
-def _snapshot(path: Path) -> dict:
- exists = path.is_file()
- doc = read_json_or_empty(path) if exists else {}
+_MISSING = {"exists": False, "revision": 0, "values": {}}
+
+
+def _read(path: Path) -> tuple[dict, bool]:
+ """``(snapshot, corrupt)``. A missing file is no store; an unparseable one is no store too
+ (``corrupt``), so clients re-import into a fresh generation. Any other read failure (EACCES,
+ EBUSY, EMFILE…) raises :class:`PreferencesBusy`: it says nothing about the content, and
+ merging over it would drop every key."""
+ try:
+ raw = path.read_text(encoding="utf-8-sig")
+ except FileNotFoundError:
+ return dict(_MISSING, values={}), False
+ except OSError as exc:
+ raise PreferencesBusy(f"preferences store is unreadable: {exc}") from exc
+ try:
+ doc = json.loads(raw)
+ except ValueError:
+ doc = None
+ if not isinstance(doc, dict):
+ return dict(_MISSING, values={}), True
revision = doc.get("revision")
+ generation = doc.get("generation")
return {
- "exists": exists,
+ "exists": True,
"revision": revision if isinstance(revision, int) else 0,
"values": _sanitize(doc.get("values")),
- }
+ "generation": generation if isinstance(generation, str) else "",
+ }, False
def read_preferences(path: Optional[Path] = None) -> dict:
- """``{"exists", "revision", "values"}`` for the store at *path* (the machine's by default)."""
- return _snapshot(path or store_path())
+ """``{"exists", "revision", "values"[, "generation"]}`` for the store at *path* (the
+ machine's by default). Raises :class:`PreferencesBusy` when the file exists but cannot be read."""
+ return _read(path or store_path())[0]
def _validate(changes: Mapping[str, Optional[str]]) -> None:
@@ -157,34 +187,47 @@ def _store_lock(path: Path) -> Iterator[Callable[[], bool]]:
_release(lock_dir, token)
+def _merge(current: Mapping[str, str], changes: Mapping[str, Optional[str]], seed: bool) -> dict[str, str]:
+ values = dict(current)
+ for key, value in changes.items():
+ if seed:
+ # A client's first contact: fill what the store lacks, never overwrite or delete.
+ if value is not None:
+ values.setdefault(key, value)
+ elif value is None:
+ values.pop(key, None)
+ else:
+ values[key] = value
+ return values
+
+
def write_preferences(changes: Mapping[str, Optional[str]], *, seed: bool = False,
path: Optional[Path] = None) -> dict:
"""Merge *changes* per key (``None`` deletes) and return the resulting snapshot.
- ``seed=True`` is the one-time import of a window's existing localStorage: it writes only when
- the store does not exist yet and otherwise returns the existing store untouched.
+ ``seed=True`` is a client's first contact with this store generation: it only adds the keys
+ the store lacks (and creates no store from nothing), so a client that has data fills a store
+ an empty client created and no client's values are overwritten or deleted.
"""
_validate(changes)
path = path or store_path()
path.parent.mkdir(parents=True, exist_ok=True)
with _store_lock(path) as still_ours:
- current = _snapshot(path)
- if seed and current["exists"]:
- return current
- values = dict(current["values"])
- for key, value in changes.items():
- if value is None:
- values.pop(key, None)
- else:
- values[key] = value
+ current, corrupt = _read(path)
+ values = _merge(current["values"], changes, seed)
if len(values) > MAX_KEYS or sum(len(k) + len(v) for k, v in values.items()) > MAX_TOTAL_CHARS:
raise PreferencesError("preferences store is full")
- if current["exists"] and values == current["values"]:
+ if values == current["values"] and (current["exists"] or not values):
return current
revision = current["revision"] + 1
+ generation = current.get("generation") or secrets.token_hex(8)
if not still_ours():
# Held past the stale limit and broken by another writer: replacing the file now
# could drop the keys that writer merged meanwhile.
raise PreferencesBusy("preferences store lock was taken over")
- atomic_json_write(path, {"version": 1, "revision": revision, "values": values}, mode=0o600)
- return {"exists": True, "revision": revision, "values": values}
+ if corrupt:
+ # Kept aside, never silently replaced: it may hold preferences worth recovering.
+ shutil.copy2(path, path.with_name(f"{path.name}.corrupt-{int(time.time() * 1000)}"))
+ atomic_json_write(path, {"version": 1, "generation": generation, "revision": revision,
+ "values": values}, mode=0o600)
+ return {"exists": True, "revision": revision, "values": values, "generation": generation}
diff --git a/hermes_cli/web_routers/ui_preferences.py b/hermes_cli/web_routers/ui_preferences.py
index 5190a740322..c3271076db5 100644
--- a/hermes_cli/web_routers/ui_preferences.py
+++ b/hermes_cli/web_routers/ui_preferences.py
@@ -22,14 +22,17 @@ router = APIRouter()
class PreferencesPatch(BaseModel):
#: Per-key changes; ``null`` deletes the key (the renderer's "back to default").
values: dict[str, Optional[str]] = Field(default_factory=dict)
- #: The one-time import of this browser's existing localStorage: applies only while no store
- #: exists, and otherwise answers the existing store untouched.
+ #: This browser's first contact with the store generation: adds only the keys the store
+ #: lacks, never overwriting or deleting one.
seed: bool = False
@router.get("/api/ui-preferences")
def get_ui_preferences() -> dict:
- return ui_preferences.read_preferences()
+ try:
+ return ui_preferences.read_preferences()
+ except ui_preferences.PreferencesBusy as exc:
+ raise HTTPException(status_code=503, detail=str(exc)) from exc
@router.patch("/api/ui-preferences")
diff --git a/tests/hermes_cli/test_ui_preferences.py b/tests/hermes_cli/test_ui_preferences.py
index a9b63d261ec..9bfc575c3af 100644
--- a/tests/hermes_cli/test_ui_preferences.py
+++ b/tests/hermes_cli/test_ui_preferences.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import json
import multiprocessing
+import os
import pytest
from fastapi.testclient import TestClient
@@ -40,16 +41,51 @@ def test_a_custom_home_under_the_native_home_is_its_own_root(monkeypatch, tmp_pa
assert ui_preferences.store_path() == sandbox.resolve() / "ui-preferences.json"
-def test_the_seed_import_never_overwrites_an_existing_store(tmp_path):
+def test_the_seed_import_only_adds_keys_and_never_creates_an_empty_store(tmp_path):
+ """A client's first contact fills what the store lacks: the client that has data fills a
+ store an empty client reached first, and nothing already stored is overwritten."""
path = tmp_path / "ui-preferences.json"
+ empty = ui_preferences.write_preferences({}, seed=True, path=path)
first = ui_preferences.write_preferences({"hermes.desktop.sessionListDensity": "detailed"},
seed=True, path=path)
second = ui_preferences.write_preferences({"hermes.desktop.sessionListDensity": "compact",
"hermes-desktop-mode-v1": "dark"}, seed=True, path=path)
- assert first == second == {"exists": True, "revision": 1,
- "values": {"hermes.desktop.sessionListDensity": "detailed"}}
- assert json.loads(path.read_text())["values"] == {"hermes.desktop.sessionListDensity": "detailed"}
+ assert empty == {"exists": False, "revision": 0, "values": {}}
+ assert first["values"] == {"hermes.desktop.sessionListDensity": "detailed"}
+ assert second["values"] == {"hermes.desktop.sessionListDensity": "detailed", "hermes-desktop-mode-v1": "dark"}
+ assert second["generation"] == first["generation"]
+ assert json.loads(path.read_text())["values"] == second["values"]
+
+
[email protected]("linux", "macos")
+def test_an_unreadable_or_corrupt_store_is_never_merged_over(tmp_path):
+ """Only a missing file is no store. An unreadable one refuses the write (the client retries)
+ and stays intact; a corrupt one is kept aside and replaced by a NEW generation, which every
+ open window follows whatever revision it had seen."""
+ path = tmp_path / "ui-preferences.json"
+ kept = ui_preferences.write_preferences({"hermes-desktop-theme-v2": "nous", "hermes.desktop.keybinds": "{}"},
+ path=path)
+ before = path.read_bytes()
+ path.chmod(0)
+ try:
+ if os.access(path, os.R_OK):
+ pytest.skip("running as a user that reads mode-000 files (root)")
+ with pytest.raises(ui_preferences.PreferencesBusy):
+ ui_preferences.write_preferences({"hermes-desktop-mode-v1": "dark"}, path=path)
+ finally:
+ path.chmod(0o600)
+ assert path.read_bytes() == before
+
+ torn = before[:-5]
+ path.write_bytes(torn)
+ assert ui_preferences.read_preferences(path)["exists"] is False
+ after = ui_preferences.write_preferences({"hermes-desktop-mode-v1": "dark"}, path=path)
+
+ backups = list(tmp_path.glob("ui-preferences.json.corrupt-*"))
+ assert [backup.read_bytes() for backup in backups] == [torn]
+ assert after["values"] == {"hermes-desktop-mode-v1": "dark"}
+ assert after["generation"] != kept["generation"]
def test_writes_merge_per_key_and_concurrent_writers_keep_each_others_keys(tmp_path):
diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.md
index 5019cfd57ee..ad3447960b8 100644
--- a/website/docs/user-guide/desktop.md
+++ b/website/docs/user-guide/desktop.md
@@ -410,7 +410,7 @@ First-run onboarding has been redesigned on a unified overlay design system, and
Display preferences (theme and light/dark mode, session-list density and sidebar layout, status-bar readouts, transcript and tool display, sounds, keybinds, saved layouts, and model-picker favourites) are stored once per computer, in `ui-preferences.json` in the root Hermes home (`~/.hermes/ui-preferences.json` by default; with a custom `HERMES_HOME`, the root of that home, never a profile folder). The desktop app on that computer and every browser that opens the [Webapp](#use-the-desktop-workspace-from-a-browser) it serves read and write the same file. A change in one reaches the others: the desktop app's windows get it within a couple of seconds and Webapp tabs when they regain focus or within about ten seconds. Theme, mode, density and the other settings an open window already follows across windows repaint at once; the rest apply the next time a window or tab loads. This includes another device, a private window, and another address for the same Webapp (`127.0.0.1`, the LAN address, `webapp.public_url`).
-The file belongs to the computer, not to a gateway connection or a profile. A desktop app connected to a remote gateway, or to several gateways, keeps its own computer's preferences. Settings that are already per profile, such as the theme picked for one profile, stay per profile inside the file. Credentials, sign-ins, permission grants, drafts and per-window state (open tabs, pane layout, scroll position, zoom) are never written to it and stay in each window or browser. The first time an app or browser finds no file, it copies its existing settings into a new one. After that it never overwrites the file; it adopts the values already there.
+The file belongs to the computer, not to a gateway connection or a profile. A desktop app connected to a remote gateway, or to several gateways, keeps its own computer's preferences. Settings that are already per profile, such as the theme picked for one profile, stay per profile inside the file. Credentials, sign-ins, permission grants, drafts and per-window state (open tabs, pane layout, scroll position, zoom) are never written to it and stay in each window or browser. The first time an app or browser meets the file (or finds none), it copies in the settings it has that the file lacks, and adopts the values already there; it never overwrites them, and nothing it has is removed just because the file lacks it. If the file is ever damaged, it is kept beside the new one as `ui-preferences.json.corrupt-<timestamp>`, and every open window and tab copies its settings back into the new file. If the file exists but cannot be read (for example, its permissions changed), changes wait in each window and are saved once it is readable again.
#### Per-profile settings: the "Applies to" scope