The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): harden the machine preferences store (review round 1)
Tekniuma21e42ae5ccd
diff --git a/apps/desktop/electron/ui-preferences.test.ts b/apps/desktop/electron/ui-preferences.test.tsindex 90e5c4f55d7..7909b207fa0 100644--- a/apps/desktop/electron/ui-preferences.test.ts+++ b/apps/desktop/electron/ui-preferences.test.ts@@ -53,6 +53,23 @@ test('native Desktop and the Webapp server resolve the same store from a profileassert.equal(pythonFile, electronFile)})+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 pythonFile = execFileSync(python, ['-c', PY_PATH], {+ cwd: repo,+ encoding: 'utf8',+ env: pythonEnv(home, sandbox)+ }).trim()++ assert.equal(electronFile, path.join(sandbox, 'ui-preferences.json'))+ assert.equal(fs.realpathSync(path.dirname(pythonFile)), fs.realpathSync(path.dirname(electronFile)))+})+test('concurrent native and Webapp writers keep every key the other wrote', async () => {const home = scratchHome()const root = path.join(home, 'root')diff --git a/apps/desktop/electron/ui-preferences.ts b/apps/desktop/electron/ui-preferences.tsindex 9adf5df4ac9..d88e28ca7b2 100644--- a/apps/desktop/electron/ui-preferences.ts+++ b/apps/desktop/electron/ui-preferences.ts@@ -10,6 +10,7 @@// 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.+import { randomBytes } from 'node:crypto'import fs from 'node:fs'import path from 'node:path'@@ -97,8 +98,34 @@ export function parseUiPreferencesWrite(payload: unknown): UiPreferencesWrite {const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))-async function withStoreLock<T>(file: string, run: () => Promise<T>): Promise<T> {+const ownerFile = (lockDir: string) => path.join(lockDir, 'owner')++async function owns(lockDir: string, token: string): Promise<boolean> {+ return fs.promises.readFile(ownerFile(lockDir), 'utf8').then(+ owner => owner === token,+ () => false+ )+}++async function breakIfStale(lockDir: string): Promise<void> {+ const mtime = await fs.promises.stat(lockDir).then(+ stat => stat.mtimeMs,+ () => null+ )++ // A writer that died holding the lock must not wedge every later write.+ // Writes hold it for milliseconds; the data file is only ever replaced whole.+ if (mtime !== null && Date.now() - mtime > LOCK_STALE_MS) {+ await fs.promises.rm(lockDir, { force: true, recursive: true }).catch(() => undefined)+ }+}++/** Cross-process lock shared with the Python writer: the `<store>.lock`+ * directory, whose `owner` file names the holder. `run` gets a check that+ * the lock is still ours, for right before the file is replaced. */+async function withStoreLock<T>(file: string, run: (stillOurs: () => Promise<boolean>) => Promise<T>): Promise<T> {const lockDir = `${file}.lock`+ const token = `${process.pid}-${randomBytes(8).toString('hex')}`const deadline = Date.now() + LOCK_WAIT_MSfor (;;) {@@ -111,17 +138,7 @@ async function withStoreLock<T>(file: string, run: () => Promise<T>): Promise<T>throw error}- const mtime = await fs.promises.stat(lockDir).then(- stat => stat.mtimeMs,- () => null- )-- if (mtime !== null && Date.now() - mtime > LOCK_STALE_MS) {- // A writer that died holding the lock must not wedge every later write.- await fs.promises.rmdir(lockDir).catch(() => undefined)-- continue- }+ await breakIfStale(lockDir)if (Date.now() > deadline) {throw new Error('preferences store is busy')@@ -132,9 +149,15 @@ async function withStoreLock<T>(file: string, run: () => Promise<T>): Promise<T>}try {- return await run()+ await fs.promises.writeFile(ownerFile(lockDir), token, 'utf8')++ return await run(() => owns(lockDir, token))} finally {- await fs.promises.rmdir(lockDir).catch(() => undefined)+ // Only while still ours: a lock broken as stale and re-taken by another+ // writer must not be removed by the writer that lost it.+ if (await owns(lockDir, token)) {+ await fs.promises.rm(lockDir, { force: true, recursive: true }).catch(() => undefined)+ }}}@@ -158,7 +181,7 @@ export function writeUiPreferences(file: string, write: UiPreferencesWrite): Proconst next = writeChain.then(async () => {await fs.promises.mkdir(path.dirname(file), { recursive: true })- return withStoreLock(file, async () => {+ return withStoreLock(file, async stillOurs => {const current = readUiPreferences(file)if (write.seed && current.exists) {@@ -190,6 +213,12 @@ export function writeUiPreferences(file: string, write: UiPreferencesWrite): Proconst revision = current.revision + 1+ if (!(await stillOurs())) {+ // Held past the stale limit and broken by another writer: replacing the+ // file now could drop the keys that writer merged meanwhile.+ throw new Error('preferences store is busy')+ }+await replaceAtomically(file, `${JSON.stringify({ version: 1, revision, values }, null, 2)}\n`)return { exists: true, revision, values }diff --git a/apps/desktop/src/lib/persisted.ts b/apps/desktop/src/lib/persisted.tsindex 024d0a1006c..f06b510e7f9 100644--- a/apps/desktop/src/lib/persisted.ts+++ b/apps/desktop/src/lib/persisted.ts@@ -109,7 +109,9 @@ export function persistentAtom<T>(key: string, fallback: T, codec: Codec<T> = Coadopting = truetry {- $value.set(decodeOr(event.newValue, fallback, codec))+ // The stored value, not the event's: events from other windows queue,+ // and an older one must not undo a newer edit made here meanwhile.+ $value.set(decodeOr(readKey(key), fallback, codec))} finally {adopting = false}diff --git a/apps/desktop/src/lib/ui-preferences/boot.ts b/apps/desktop/src/lib/ui-preferences/boot.tsindex e323133a332..3bfeffb9481 100644--- a/apps/desktop/src/lib/ui-preferences/boot.ts+++ b/apps/desktop/src/lib/ui-preferences/boot.ts@@ -1,9 +1,33 @@-// Side-effect module, imported first by main.tsx: native Desktop's preload hands-// over this machine's shared preferences synchronously, so the localStorage-// cache matches the store before any store module reads it (no default flash).-// A browser has no synchronous door; its sync applies the store once fetched.-import { hydrateFromSnapshot } from './sync'+// Side-effect module, imported first by main.tsx, so the localStorage cache+// matches this machine's shared preferences before any store module reads it+// (no default flash, and no plain-atom store seeded from a stale cache).+// Native Desktop's preload hands the snapshot over synchronously. A browser+// asks the server that serves it, bounded so an unreachable host never holds+// the first paint for long: the top-level await delays the modules main.tsx+// imports after this one.+import { browserApi, browserBootstrap } from '@/lib/browser-transport'++import { hydrateFromSnapshot, type UiPreferencesSnapshot } from './sync'++const BROWSER_FIRST_READ_MS = 1500++async function browserSnapshot(): Promise<null | UiPreferencesSnapshot> {+ const bootstrap = browserBootstrap()++ if (!bootstrap) {+ return null+ }++ const read = browserApi<UiPreferencesSnapshot>(bootstrap, {+ path: '/api/ui-preferences',+ timeoutMs: BROWSER_FIRST_READ_MS+ }).catch(() => null)++ const late = new Promise<null>(resolve => setTimeout(() => resolve(null), BROWSER_FIRST_READ_MS))++ return Promise.race([read, late])+}if (typeof window !== 'undefined') {- hydrateFromSnapshot(window.hermesDesktop?.uiPreferences?.snapshot)+ hydrateFromSnapshot(window.hermesDesktop?.uiPreferences?.snapshot ?? (await browserSnapshot()))}diff --git a/apps/desktop/src/lib/ui-preferences/keys.ts b/apps/desktop/src/lib/ui-preferences/keys.tsindex 3d15702fb18..5af90e3c586 100644--- a/apps/desktop/src/lib/ui-preferences/keys.ts+++ b/apps/desktop/src/lib/ui-preferences/keys.ts@@ -36,6 +36,7 @@ const SHARED_KEYS: ReadonlySet<string> = new Set(['hermes.desktop.profileRailVisible','hermes.desktop.sessionListDensity','hermes.desktop.sessionOrder',+ 'hermes.desktop.sessionOrder.manual','hermes.desktop.showAllProfiles','hermes.desktop.sidebarAgentsGrouped.allProfiles','hermes.desktop.sidebarCardRows',@@ -74,6 +75,8 @@ const SHARED_KEYS: ReadonlySet<string> = new Set([// Model picker.'hermes.desktop.collapsed-providers','hermes.desktop.favorite-models',+ // visible-models is a diff against known-models: they only make sense together.+ 'hermes.desktop.known-models','hermes.desktop.model-presets','hermes.desktop.visible-models'])diff --git a/apps/desktop/src/lib/ui-preferences/sync.test.ts b/apps/desktop/src/lib/ui-preferences/sync.test.tsindex a50a50b70ed..f152fb10e98 100644--- a/apps/desktop/src/lib/ui-preferences/sync.test.ts+++ b/apps/desktop/src/lib/ui-preferences/sync.test.ts@@ -133,4 +133,60 @@ describe('machine UI preferences sync', () => {expect(window.localStorage.getItem(DENSITY)).toBe('detailed')expect(store.snapshot().values).toEqual({ [DENSITY]: 'detailed' })})++ it('keeps one write in flight so a newer edit is never overwritten by an older batch', async () => {+ const store = memoryStore({ [DENSITY]: 'compact' })+ const write = store.bridge.write+ let release: () => void = () => undefined+ let held = true+ const sent: (null | string)[] = []++ store.bridge.write = payload => {+ sent.push(payload.values[DENSITY] ?? null)++ return held+ ? new Promise(resolve => {+ release = () => {+ held = false+ resolve(write(payload))+ }+ })+ : write(payload)+ }++ stop = startUiPreferencesSync(store.bridge)+ await vi.runAllTimersAsync()+ writeKey(DENSITY, 'comfortable')+ await vi.advanceTimersByTimeAsync(200)+ writeKey(DENSITY, 'detailed')+ await vi.advanceTimersByTimeAsync(2000)++ expect(sent).toEqual(['comfortable'])++ release()+ await vi.runAllTimersAsync()++ expect(sent).toEqual(['comfortable', 'detailed'])+ expect(store.snapshot().values[DENSITY]).toBe('detailed')+ expect(window.localStorage.getItem(DENSITY)).toBe('detailed')+ })++ it('does not hold later changes behind a batch the store refused', async () => {+ const store = memoryStore({ [DENSITY]: 'compact' })+ const write = store.bridge.write+ vi.spyOn(console, 'warn').mockImplementation(() => undefined)++ store.bridge.write = payload =>+ MODE in payload.values ? Promise.reject(new Error('400: unsupported value for ' + MODE)) : write(payload)++ stop = startUiPreferencesSync(store.bridge)+ await vi.runAllTimersAsync()+ writeKey(MODE, 'x'.repeat(10))+ await vi.runAllTimersAsync()+ writeKey(DENSITY, 'detailed')+ await vi.runAllTimersAsync()++ expect(store.snapshot().values).toEqual({ [DENSITY]: 'detailed' })+ expect(window.localStorage.getItem(MODE)).toBe('x'.repeat(10))+ })})diff --git a/apps/desktop/src/lib/ui-preferences/sync.ts b/apps/desktop/src/lib/ui-preferences/sync.tsindex 40fff22a30c..b92b62ec772 100644--- a/apps/desktop/src/lib/ui-preferences/sync.ts+++ b/apps/desktop/src/lib/ui-preferences/sync.ts@@ -114,6 +114,14 @@ function saveOutbox(pending: Map<string, null | string>) {writeRaw(OUTBOX_KEY, pending.size === 0 ? null : JSON.stringify(Object.fromEntries(pending)))}+/** A write the store answered "no" to (HTTP 400 / validation), as opposed to+ * one that could not reach it; only the latter is worth retrying. */+function isRefusal(error: unknown): boolean {+ const message = error instanceof Error ? error.message : String(error)++ return /^400:|unsupported preference|unsupported value|store is full/.test(message)+}+function announce(key: string, oldValue: null | string, newValue: null | string) {// Existing cross-window listeners (theme, translucency, haptics, persistent// atoms) already follow `storage` events; a same-window apply fires one too.@@ -135,6 +143,8 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | undeconst known = new Map<string, null | string>()const pending = readOutbox()+ // Values the store refused, kept in this window until changed again.+ const refused = new Map<string, null | string>()let revision = -1let flushTimer: ReturnType<typeof setTimeout> | null = nulllet stopped = false@@ -159,7 +169,7 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | undeknown.set(key, value)// A change made here and not yet stored outranks an older store value.- if (pending.has(key)) {+ if (pending.has(key) || (refused.has(key) && refused.get(key) === readRaw(key))) {continue}@@ -171,12 +181,17 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde}}+ let writing = false+ let writeDelay = RETRY_DELAY_MS+const schedule = (delay: number) => {- if (flushTimer === null && ready && !stopped) {+ if (flushTimer === null && !writing && ready && !stopped) {flushTimer = setTimeout(() => void flush(), delay)}}+ // One write in flight at a time: two independent requests could commit out+ // of order, and the older batch's later revision would win.const flush = async () => {flushTimer = null@@ -185,28 +200,45 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde}const batch = new Map(pending)+ let retryIn = FLUSH_DELAY_MS+ writing = truetry {const snapshot = await bridge.write({ values: Object.fromEntries(batch) })- for (const [key, value] of batch) {- if (pending.get(key) === value) {- pending.delete(key)- }- }-- saveOutbox(pending)-+ settle(batch)+ writeDelay = RETRY_DELAY_MSapply(snapshot, { live: true })- } catch {- schedule(RETRY_DELAY_MS)+ } catch (error) {+ if (isRefusal(error)) {+ // The store refused this batch outright (oversized value, full store):+ // it stays in this window only, and later changes are not held behind it.+ console.warn('[ui-preferences] the machine store refused these preferences', [...batch.keys()], error)+ batch.forEach((value, key) => refused.set(key, value))+ settle(batch)+ } else {+ retryIn = writeDelay+ writeDelay = Math.min(writeDelay * 2, MAX_RETRY_DELAY_MS)+ }+ } finally {+ writing = false}if (pending.size > 0) {- schedule(FLUSH_DELAY_MS)+ schedule(retryIn)}}+ const settle = (batch: Map<string, null | string>) => {+ for (const [key, value] of batch) {+ if (pending.get(key) === value) {+ pending.delete(key)+ }+ }++ saveOutbox(pending)+ }+const stopListening = onPersistenceEvent(event => {if (event.op === 'read' || !isSharedPreferenceKey(event.key)) {return@@ -216,6 +248,7 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | undereturn}+ refused.delete(event.key)pending.set(event.key, event.value)saveOutbox(pending)schedule(FLUSH_DELAY_MS)diff --git a/apps/desktop/src/themes/user-themes.ts b/apps/desktop/src/themes/user-themes.tsindex d3c0f167663..ee02c931469 100644--- a/apps/desktop/src/themes/user-themes.ts+++ b/apps/desktop/src/themes/user-themes.ts@@ -13,6 +13,7 @@import { atom, computed } from 'nanostores'import { registry } from '@/contrib/registry'+import { writeJson } from '@/lib/storage'import { $backendThemes } from './backend-sync'import { BUILTIN_THEMES } from './presets'@@ -54,12 +55,10 @@ function readStored(): Record<string, DesktopTheme> {}}+// Through the storage choke point (best-effort, like a direct write) so the+// machine's shared preferences store sees an install (#145213).function persist(record: Record<string, DesktopTheme>) {- try {- window.localStorage.setItem(USER_THEMES_KEY, JSON.stringify(record))- } catch {- // Best-effort: a restricted storage context shouldn't break theming.- }+ writeJson(USER_THEMES_KEY, record)}/** Reactive map of installed user themes, keyed by slug. */diff --git a/hermes_cli/ui_preferences.py b/hermes_cli/ui_preferences.pyindex 7aef9ea5814..749bb4996a7 100644--- a/hermes_cli/ui_preferences.py+++ b/hermes_cli/ui_preferences.py@@ -21,11 +21,12 @@ credentials, grants and per-window state out.from __future__ import annotationsimport os+import secretsimport threadingimport timefrom contextlib import contextmanagerfrom pathlib import Path-from typing import Iterator, Mapping, Optional+from typing import Callable, Iterator, Mapping, Optionalfrom utils import atomic_json_write, read_json_or_empty@@ -51,12 +52,15 @@ class PreferencesBusy(RuntimeError):def store_path(root: Optional[Path] = None) -> Path:- """The machine's preferences file. The root home is the same for every profile one process- serves, so this read is profile-independent by design (not a launch-profile leak)."""+ """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)."""if root is None:- from hermes_constants import get_default_hermes_root+ from hermes_constants import get_hermes_home- root = get_default_hermes_root()+ home = Path(get_hermes_home()).resolve()+ root = home.parent.parent if home.parent.name.lower() == "profiles" else homereturn Path(root) / STORE_NAME@@ -90,10 +94,51 @@ def _validate(changes: Mapping[str, Optional[str]]) -> None:raise PreferencesError(f"unsupported value for {key}")+def _owner_file(lock_dir: Path) -> Path:+ return lock_dir / "owner"+++def _release(lock_dir: Path, token: str) -> None:+ """Remove the lock only while it is still ours: a lock broken as stale and re-taken by another+ writer must not be removed by the writer that lost it."""+ if not _owns(lock_dir, token):+ return+ try:+ _owner_file(lock_dir).unlink()+ os.rmdir(lock_dir)+ except OSError:+ pass+++def _owns(lock_dir: Path, token: str) -> bool:+ try:+ return _owner_file(lock_dir).read_text(encoding="utf-8-sig") == token+ except OSError:+ return False+++def _break_if_stale(lock_dir: Path) -> None:+ try:+ stale = time.time() - lock_dir.stat().st_mtime > _LOCK_STALE_S+ except FileNotFoundError:+ return+ if not stale:+ return+ # A writer that died holding the lock must not wedge every later write. Writes hold it for+ # milliseconds, and the data file itself is only ever replaced whole.+ try:+ _owner_file(lock_dir).unlink(missing_ok=True)+ os.rmdir(lock_dir)+ except OSError:+ pass++@contextmanager-def _store_lock(path: Path) -> Iterator[None]:- """Cross-process lock shared with the Electron writer: the ``<store>.lock`` directory."""+def _store_lock(path: Path) -> Iterator[Callable[[], bool]]:+ """Cross-process lock shared with the Electron writer: the ``<store>.lock`` directory, whose+ ``owner`` file names the holder."""lock_dir = path.with_name(path.name + ".lock")+ token = f"{os.getpid()}-{secrets.token_hex(8)}"deadline = time.monotonic() + _LOCK_WAIT_Swith _thread_lock:while True:@@ -101,28 +146,15 @@ def _store_lock(path: Path) -> Iterator[None]:os.mkdir(lock_dir)breakexcept FileExistsError:- try:- stale = time.time() - lock_dir.stat().st_mtime > _LOCK_STALE_S- except FileNotFoundError:- continue- if stale:- # A writer that died holding the lock must not wedge every later write; the- # data file itself is only ever replaced whole, so breaking it loses nothing.- try:- os.rmdir(lock_dir)- except OSError:- pass- continue+ _break_if_stale(lock_dir)if time.monotonic() > deadline:raise PreferencesBusy("preferences store is busy")time.sleep(_LOCK_POLL_S)try:- yield+ _owner_file(lock_dir).write_text(token, encoding="utf-8")+ yield lambda: _owns(lock_dir, token)finally:- try:- os.rmdir(lock_dir)- except OSError:- pass+ _release(lock_dir, token)def write_preferences(changes: Mapping[str, Optional[str]], *, seed: bool = False,@@ -135,7 +167,7 @@ def write_preferences(changes: Mapping[str, Optional[str]], *, seed: bool = Fals_validate(changes)path = path or store_path()path.parent.mkdir(parents=True, exist_ok=True)- with _store_lock(path):+ with _store_lock(path) as still_ours:current = _snapshot(path)if seed and current["exists"]:return current@@ -150,5 +182,9 @@ def write_preferences(changes: Mapping[str, Optional[str]], *, seed: bool = Falsif current["exists"] and values == current["values"]:return currentrevision = current["revision"] + 1+ 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}diff --git a/tests/hermes_cli/test_ui_preferences.py b/tests/hermes_cli/test_ui_preferences.pyindex 0220f0291c4..a9b63d261ec 100644--- a/tests/hermes_cli/test_ui_preferences.py+++ b/tests/hermes_cli/test_ui_preferences.py@@ -29,6 +29,17 @@ def test_a_profile_home_and_the_root_home_resolve_the_same_store(monkeypatch, tmassert from_root == from_profile == root / "ui-preferences.json"+def test_a_custom_home_under_the_native_home_is_its_own_root(monkeypatch, tmp_path):+ """Native Desktop keeps an explicit ``HERMES_HOME`` that is not a profile as the root; the+ Webapp's server must resolve the same file, not collapse it to the native home."""+ sandbox = tmp_path / ".hermes" / "sandbox"+ sandbox.mkdir(parents=True)+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("HERMES_HOME", str(sandbox))++ assert ui_preferences.store_path() == sandbox.resolve() / "ui-preferences.json"++def test_the_seed_import_never_overwrites_an_existing_store(tmp_path):path = tmp_path / "ui-preferences.json"first = ui_preferences.write_preferences({"hermes.desktop.sessionListDensity": "detailed"},