The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): one UI preferences store per machine, shared by Desktop and its Webapp (#145213)
Tekniumb459f2c6ddc8
diff --git a/apps/desktop/electron/fs-ipc.ts b/apps/desktop/electron/fs-ipc.tsindex a70a1cf8459..6b90af62d6f 100644--- a/apps/desktop/electron/fs-ipc.ts+++ b/apps/desktop/electron/fs-ipc.ts@@ -21,6 +21,7 @@ import { DESKTOP_PROFILE_NAME_RE } from './desktop-profile'import { readDirForIpc } from './fs-read-dir'import { gitRootForIpc } from './git-root'import { registerPluginFilesIpc } from './plugin-files-ipc'+import { registerUiPreferencesIpc } from './ui-preferences'export interface FsIpcDeps {hermesHome: string@@ -62,6 +63,18 @@ export function registerFsIpc({trashItem: target => shell.trashItem(target)})+ // The machine's UI preferences file beside the root home (#145213), shared+ // with this machine's Webapp. `hermesHome` is already the root, never a profile.+ registerUiPreferencesIpc({+ ipcMain,+ hermesHome,+ broadcast: snapshot => {+ for (const window of BrowserWindow.getAllWindows()) {+ window.webContents.send('hermes:ui-preferences:changed', snapshot)+ }+ }+ })+ipcMain.handle('hermes:fs:gitRoot', async (_event, startPath) => gitRootForIpc(startPath))// Reveal a path in the OS file manager (Finder / Explorer / Files).diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex 552d7f59976..33494d336a5 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -23,6 +23,10 @@ const launchFlags: { localModels?: boolean; assumeFreshInstall?: boolean } | und// the built-in palette over the skin configured on this machine.const localSkin = ipcRenderer.sendSync('hermes:skin:local')+// This machine's UI preferences store (#145213), read before the first paint so+// a preference set in another window or in this machine's Webapp paints at once.+const uiPreferencesSnapshot = ipcRenderer.sendSync('hermes:ui-preferences:snapshot')+import { unwrapExpectedNotFound } from './api-expected-404'contextBridge.exposeInMainWorld('hermesDesktop', {@@ -35,6 +39,17 @@ contextBridge.exposeInMainWorld('hermesDesktop', {// onboarding treats this launch as a fresh install. Always false when packaged.assumeFreshInstall: launchFlags?.assumeFreshInstall === true,localSkin: localSkin && typeof localSkin === 'object' ? localSkin : null,+ uiPreferences: {+ snapshot: uiPreferencesSnapshot && typeof uiPreferencesSnapshot === 'object' ? uiPreferencesSnapshot : null,+ read: () => ipcRenderer.invoke('hermes:ui-preferences:read'),+ write: payload => ipcRenderer.invoke('hermes:ui-preferences:write', payload),+ onChanged: callback => {+ const listener = (_event, snapshot) => callback(snapshot)+ ipcRenderer.on('hermes:ui-preferences:changed', listener)++ return () => ipcRenderer.removeListener('hermes:ui-preferences:changed', listener)+ }+ },getConnection: (profile, opts) => ipcRenderer.invoke('hermes:connection', profile, opts),// Loopback origin that hosts YouTube's player for the file:// renderer.getEmbedHostOrigin: () => ipcRenderer.invoke('hermes:embed-host:origin'),diff --git a/apps/desktop/electron/ui-preferences.test.ts b/apps/desktop/electron/ui-preferences.test.tsnew file mode 100644index 00000000000..90e5c4f55d7--- /dev/null+++ b/apps/desktop/electron/ui-preferences.test.ts@@ -0,0 +1,98 @@+import assert from 'node:assert/strict'+import { execFile, execFileSync } from 'node:child_process'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { promisify } from 'node:util'++import { afterEach, test } from 'vitest'++import { resolveDesktopHermesHome } from './data-paths'+import { readUiPreferences, uiPreferencesPath, 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).+const repo = path.resolve(import.meta.dirname, '../../..')+const python = process.env.HERMES_PYTHON || 'python3'+const homes: string[] = []++afterEach(() => {+ for (const home of homes.splice(0)) {+ fs.rmSync(home, { force: true, recursive: true })+ }+})++function scratchHome(): string {+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-ui-prefs-'))+ homes.push(home)++ return home+}++function pythonEnv(home: string, hermesHome: string): NodeJS.ProcessEnv {+ return { HERMES_HOME: hermesHome, HOME: home, PATH: process.env.PATH, PYTHONPATH: repo }+}++const PY_PATH = 'from hermes_cli.ui_preferences import store_path; print(store_path())'++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 pythonFile = execFileSync(python, ['-c', PY_PATH], {+ cwd: repo,+ encoding: 'utf8',+ env: pythonEnv(home, profileHome)+ }).trim()++ assert.equal(electronFile, path.join(root, 'ui-preferences.json'))+ assert.equal(pythonFile, electronFile)+})++test('concurrent native and Webapp writers keep every key the other wrote', async () => {+ const home = scratchHome()+ const root = path.join(home, 'root')+ fs.mkdirSync(root)+ const file = uiPreferencesPath(root)++ const pyWrites = `+from hermes_cli.ui_preferences import write_preferences+for n in range(25):+ write_preferences({f"hermes.desktop.py{n}": "web"})+`++ const pythonRun = promisify(execFile)(python, ['-c', pyWrites], { cwd: repo, env: pythonEnv(home, root) })++ for (let n = 0; n < 25; n += 1) {+ await writeUiPreferences(file, { values: { [`hermes.desktop.native${n}`]: 'native' } })+ }++ await pythonRun++ const { revision, values } = readUiPreferences(file)++ assert.equal(Object.keys(values).length, 50)+ assert.equal(revision, 50)++ for (let n = 0; n < 25; n += 1) {+ assert.equal(values[`hermes.desktop.native${n}`], 'native')+ assert.equal(values[`hermes.desktop.py${n}`], 'web')+ }++ assert.equal(fs.existsSync(`${file}.lock`), false)+})++test('the one-time localStorage import never overwrites a store that exists', 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' })+})diff --git a/apps/desktop/electron/ui-preferences.ts b/apps/desktop/electron/ui-preferences.tsnew file mode 100644index 00000000000..9adf5df4ac9--- /dev/null+++ b/apps/desktop/electron/ui-preferences.ts@@ -0,0 +1,250 @@+// Machine-level UI preferences (#145213): one JSON document beside the ROOT+// Hermes home, shared by native Desktop (this module, over the typed preload+// capability) and every browser that opens this machine's Webapp (the Python+// twin `hermes_cli/ui_preferences.py`, over `/api/ui-preferences`). Not per+// profile, not per gateway connection: a Desktop connected to a remote gateway+// 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> } }+// 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 fs from 'node:fs'+import path from 'node:path'++export const UI_PREFERENCES_FILE = 'ui-preferences.json'+const KEY_PREFIXES = ['hermes.desktop.', 'hermes-desktop-']+const MAX_KEY_CHARS = 256+const MAX_VALUE_CHARS = 256 * 1024+const MAX_KEYS = 512+const MAX_TOTAL_CHARS = 2 * 1024 * 1024+const LOCK_WAIT_MS = 3000+const LOCK_STALE_MS = 10_000+const LOCK_POLL_MS = 20+const WATCH_INTERVAL_MS = 1500++export interface UiPreferencesSnapshot {+ exists: boolean+ revision: number+ values: Record<string, string>+}++export interface UiPreferencesWrite {+ seed?: boolean+ values: Record<string, null | string>+}++export const uiPreferencesPath = (hermesHome: string) => path.join(hermesHome, UI_PREFERENCES_FILE)++const sanitize = (values: unknown): Record<string, string> =>+ values && typeof values === 'object' && !Array.isArray(values)+ ? Object.fromEntries(+ Object.entries(values).filter((entry): entry is [string, string] => typeof entry[1] === 'string')+ )+ : {}++/** Synchronous so the preload can hand the first paint a hydrated snapshot. */+export function readUiPreferences(file: string): UiPreferencesSnapshot {+ let raw: string++ try {+ raw = fs.readFileSync(file, 'utf8')+ } catch {+ return { exists: false, revision: 0, values: {} }+ }++ let doc: { revision?: unknown; values?: unknown } = {}++ try {+ const parsed = JSON.parse(raw.replace(/^\uFEFF/, '')) as unknown++ doc = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}+ } catch {+ // A corrupt file reads as an empty existing store; the next write replaces it whole.+ }++ return {+ exists: true,+ revision: Number.isInteger(doc.revision) ? (doc.revision as number) : 0,+ values: sanitize(doc.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 {+ seed?: unknown+ values?: unknown+ }++ if (!values || typeof values !== 'object' || Array.isArray(values)) {+ throw new Error('ui preferences write needs a values object')+ }++ for (const [key, value] of Object.entries(values)) {+ if (!KEY_PREFIXES.some(prefix => key.startsWith(prefix)) || key.length > MAX_KEY_CHARS) {+ throw new Error(`unsupported preference key: ${key}`)+ }++ if (value !== null && (typeof value !== 'string' || value.length > MAX_VALUE_CHARS)) {+ throw new Error(`unsupported value for ${key}`)+ }+ }++ return { seed: seed === true, values: values as Record<string, null | string> }+}++const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))++async function withStoreLock<T>(file: string, run: () => Promise<T>): Promise<T> {+ const lockDir = `${file}.lock`+ const deadline = Date.now() + LOCK_WAIT_MS++ for (;;) {+ try {+ await fs.promises.mkdir(lockDir)++ break+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {+ 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+ }++ if (Date.now() > deadline) {+ throw new Error('preferences store is busy')+ }++ await sleep(LOCK_POLL_MS)+ }+ }++ try {+ return await run()+ } finally {+ await fs.promises.rmdir(lockDir).catch(() => undefined)+ }+}++async function replaceAtomically(file: string, body: string): Promise<void> {+ const temp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${Date.now()}.tmp`)++ try {+ await fs.promises.writeFile(temp, body, { encoding: 'utf8', mode: 0o600 })+ await fs.promises.rename(temp, file)+ } catch (error) {+ await fs.promises.rm(temp, { force: true }).catch(() => undefined)++ throw error+ }+}++// In-process writes queue behind each other; the directory lock covers other processes.+let writeChain: Promise<unknown> = Promise.resolve()++export function writeUiPreferences(file: string, write: UiPreferencesWrite): Promise<UiPreferencesSnapshot> {+ const next = writeChain.then(async () => {+ await fs.promises.mkdir(path.dirname(file), { recursive: true })++ return withStoreLock(file, async () => {+ 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 entries = Object.entries(values)++ if (+ entries.length > MAX_KEYS ||+ entries.reduce((sum, [k, v]) => sum + k.length + v.length, 0) > MAX_TOTAL_CHARS+ ) {+ throw new Error('preferences store is full')+ }++ if (current.exists && JSON.stringify(values) === JSON.stringify(current.values)) {+ return current+ }++ const revision = current.revision + 1++ await replaceAtomically(file, `${JSON.stringify({ version: 1, revision, values }, null, 2)}\n`)++ return { exists: true, revision, values }+ })+ })++ writeChain = next.catch(() => undefined)++ return next+}++interface IpcMainLike {+ handle(channel: string, listener: (event: unknown, ...args: unknown[]) => unknown): void+ on(channel: string, listener: (event: { returnValue: unknown }, ...args: unknown[]) => void): void+}++export interface UiPreferencesIpcDeps {+ ipcMain: IpcMainLike+ hermesHome: string+ /** Every app window's webContents; changes are pushed to all of them. */+ broadcast: (snapshot: UiPreferencesSnapshot) => void+}++/**+ * `hermes:ui-preferences:*` — the renderer's only door to the store: a+ * synchronous first-paint snapshot, a read, and a validated per-key write. A+ * write made here, or by the Webapp's Python process on this machine (seen by+ * 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 publish = (snapshot: UiPreferencesSnapshot) => {+ if (snapshot.revision !== lastRevision) {+ lastRevision = snapshot.revision+ broadcast(snapshot)+ }+ }++ ipcMain.on('hermes:ui-preferences:snapshot', event => {+ event.returnValue = readUiPreferences(file)+ })+ ipcMain.handle('hermes:ui-preferences:read', () => readUiPreferences(file))+ ipcMain.handle('hermes:ui-preferences:write', async (_event, payload) => {+ const snapshot = await writeUiPreferences(file, parseUiPreferencesWrite(payload))++ publish(snapshot)++ return snapshot+ })++ const onStat = () => publish(readUiPreferences(file))++ fs.watchFile(file, { interval: WATCH_INTERVAL_MS, persistent: false }, onStat)++ return () => fs.unwatchFile(file, onStat)+}diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex bcfbcb0dbfe..3313f280a9c 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -12,6 +12,7 @@ import type { UpdateHoldWire } from '../electron/update-hold-types'import type { UpdateRunReport } from '../electron/updater/update-metrics'import type { WindowSizeMode } from '../electron/window-size-types'+import type { UiPreferencesBridge } from './lib/ui-preferences/sync'import type { WakeIndicatorState } from './lib/wake-indicator'import type {PetOverlayBounds,@@ -417,6 +418,9 @@ declare global {assumeFreshInstall?: boolean/** Sanitized local `display.skin`, available before any gateway connects. */localSkin?: { profile: string; skin: HermesSkin } | null+ /** This machine's shared UI preferences store (#145213): preload IPC natively,+ * `/api/ui-preferences` on the Webapp. */+ uiPreferences?: UiPreferencesBridgesetTranslucency?: (payload: TranslucencyState) => voidsetKeepAwake?: (mode: KeepAwakeMode) => voidonKeepAwakeOffer?: (callback: () => void) => () => voiddiff --git a/apps/desktop/src/lib/browser-desktop-bridge.ts b/apps/desktop/src/lib/browser-desktop-bridge.tsindex dbf4d25283f..5aabacaed6c 100644--- a/apps/desktop/src/lib/browser-desktop-bridge.ts+++ b/apps/desktop/src/lib/browser-desktop-bridge.ts@@ -11,6 +11,7 @@ import { createBrowserProfileBridge } from '@/lib/browser-profile'import { createBrowserSettings } from '@/lib/browser-settings'import { createBrowserTerminal } from '@/lib/browser-terminal'import { browserApi, browserBootstrap, ticketedWebsocketUrl } from '@/lib/browser-transport'+import { createBrowserUiPreferences } from '@/lib/browser-ui-preferences'import { createBrowserUploadsBridge } from '@/lib/browser-uploads'import { announceWebappWindow, createBrowserWindowOpener, sessionWindowTarget } from '@/lib/browser-window'import { createBrowserZoom } from '@/lib/browser-zoom'@@ -141,6 +142,7 @@ export function installBrowserDesktopBridge(): boolean {}}),...createBrowserProfileBridge({ basePath: bootstrap.basePath, currentProfile, openWindow }),+ uiPreferences: createBrowserUiPreferences(api),zoom: createBrowserZoom(bootstrap.basePath)}diff --git a/apps/desktop/src/lib/browser-ui-preferences.ts b/apps/desktop/src/lib/browser-ui-preferences.tsnew file mode 100644index 00000000000..62e62508e43--- /dev/null+++ b/apps/desktop/src/lib/browser-ui-preferences.ts@@ -0,0 +1,38 @@+import type { HermesApiRequest } from '@/global'++import type { UiPreferencesBridge, UiPreferencesSnapshot } from './ui-preferences/sync'++const PATH = '/api/ui-preferences'+const POLL_MS = 10_000++/**+ * The Webapp's door to the serving machine's UI preferences store. The server+ * cannot push, so changes made by another device, origin or native Desktop on+ * that machine arrive by a cheap poll while this tab is visible, and at once+ * when the tab regains focus.+ */+export function createBrowserUiPreferences(api: <T>(request: HermesApiRequest) => Promise<T>): UiPreferencesBridge {+ const read = () => api<UiPreferencesSnapshot>({ path: PATH, timeoutMs: 10_000 })++ return {+ read,+ write: payload => api<UiPreferencesSnapshot>({ body: payload, method: 'PATCH', path: PATH, timeoutMs: 10_000 }),+ onChanged: callback => {+ const poll = () => {+ if (document.visibilityState === 'visible') {+ read().then(callback, () => undefined)+ }+ }++ const timer = window.setInterval(poll, POLL_MS)+ window.addEventListener('focus', poll)+ document.addEventListener('visibilitychange', poll)++ return () => {+ window.clearInterval(timer)+ window.removeEventListener('focus', poll)+ document.removeEventListener('visibilitychange', poll)+ }+ }+ }+}diff --git a/apps/desktop/src/lib/persisted.ts b/apps/desktop/src/lib/persisted.tsindex f9d3c7c4004..024d0a1006c 100644--- a/apps/desktop/src/lib/persisted.ts+++ b/apps/desktop/src/lib/persisted.ts@@ -1,6 +1,7 @@import { atom, type WritableAtom } from 'nanostores'import { readKey, writeKey } from './storage'+import { isSharedPreferenceKey } from './ui-preferences/keys'// A nanostore that auto-persists. Reads its seed from localStorage through the// storage choke point (so every read/write is observable in one place) and@@ -58,19 +59,20 @@ export const Codecs = {}}-export function persistentAtom<T>(key: string, fallback: T, codec: Codec<T> = Codecs.json<T>()): WritableAtom<T> {- const raw = readKey(key)- let initial = fallback-- if (raw !== null) {- try {- initial = codec.decode(raw)- } catch {- initial = fallback- }+function decodeOr<T>(raw: null | string, fallback: T, codec: Codec<T>): T {+ if (raw === null) {+ return fallback+ }++ try {+ return codec.decode(raw)+ } catch {+ return fallback}+}- const $value = atom<T>(initial)+export function persistentAtom<T>(key: string, fallback: T, codec: Codec<T> = Codecs.json<T>()): WritableAtom<T> {+ const $value = atom<T>(decodeOr(readKey(key), fallback, codec))// Persist CHANGES only — never the creation-time value. nanostores'// subscribe fires immediately, and writing what was just read back is a@@ -82,9 +84,13 @@ export function persistentAtom<T>(key: string, fallback: T, codec: Codec<T> = Co// the early load wrote `{}` over a populated store between the disk read// and the main window's module init.let creationEmission = true+ // A value adopted from storage (another window, or the machine's shared+ // preferences store) is already persisted; writing it back would turn a+ // peer's "back to default" removal into a stored fallback.+ let adopting = false$value.subscribe(value => {- if (creationEmission) {+ if (creationEmission || adopting) {creationEmission = falsereturn@@ -93,5 +99,22 @@ export function persistentAtom<T>(key: string, fallback: T, codec: Codec<T> = CowriteKey(key, codec.encode(value))})+ // Machine-level preferences follow changes made elsewhere live (#145213).+ if (isSharedPreferenceKey(key) && typeof window !== 'undefined') {+ window.addEventListener('storage', event => {+ if (event.key !== key) {+ return+ }++ adopting = true++ try {+ $value.set(decodeOr(event.newValue, fallback, codec))+ } finally {+ adopting = false+ }+ })+ }+return $value}diff --git a/apps/desktop/src/lib/ui-preferences/boot.ts b/apps/desktop/src/lib/ui-preferences/boot.tsnew file mode 100644index 00000000000..e323133a332--- /dev/null+++ b/apps/desktop/src/lib/ui-preferences/boot.ts@@ -0,0 +1,9 @@+// 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'++if (typeof window !== 'undefined') {+ hydrateFromSnapshot(window.hermesDesktop?.uiPreferences?.snapshot)+}diff --git a/apps/desktop/src/lib/ui-preferences/keys.ts b/apps/desktop/src/lib/ui-preferences/keys.tsnew file mode 100644index 00000000000..3d15702fb18--- /dev/null+++ b/apps/desktop/src/lib/ui-preferences/keys.ts@@ -0,0 +1,86 @@+/**+ * Which persisted keys are machine-level UI preferences (#145213).+ *+ * Only these leave localStorage for the machine's shared store, so native+ * Desktop and every browser that opens this machine's Webapp show the same+ * choices. Scoped families keep their scope inside the key name (a+ * `….profile.<name>` or per-connection suffix): only the location changes.+ *+ * Deliberately NOT here (they stay in this browser/window):+ * - credentials, grants and connection config: gateway registry, custom model+ * endpoints, plugin decisions and preview-script grants, embed permissions;+ * - per-window or per-device runtime state: layout tree, open tiles and tabs,+ * last route/session, scroll, zoom, pet and popout geometry, keep-awake;+ * - drafts, queues, journals and caches: composer queue, in-flight turns,+ * pending/prepared submissions, previews, pricing, backend skin cache;+ * - seen/dismissed markers and onboarding progress.+ */++const SHARED_KEYS: ReadonlySet<string> = new Set([+ // Appearance.+ 'hermes-desktop-theme-v2',+ 'hermes-desktop-mode-v1',+ 'hermes-desktop-profile-themes-v1',+ 'hermes-desktop-profile-modes-v1',+ 'hermes-desktop-user-themes-v1',+ 'hermes.desktop.backdrop.v1',+ 'hermes.desktop.chat-text-scale.v1',+ 'hermes.desktop.interfaceMode.v1',+ 'hermes.desktop.textDirection',+ 'hermes.desktop.translucency.v2',+ 'hermes.desktop.user-bubble-transparency.v1',+ // Sessions sidebar and profile rail.+ 'hermes.desktop.agentsGroupedByWorkspace',+ 'hermes.desktop.profileColors',+ 'hermes.desktop.profileOrder',+ 'hermes.desktop.profileRailVisible',+ 'hermes.desktop.sessionListDensity',+ 'hermes.desktop.sessionOrder',+ 'hermes.desktop.showAllProfiles',+ 'hermes.desktop.sidebarAgentsGrouped.allProfiles',+ 'hermes.desktop.sidebarCardRows',+ 'hermes.desktop.sidebarGrouping',+ 'hermes.desktop.sidebarGrouping.allProfiles',+ 'hermes.desktop.sidebarRowMeta',+ 'hermes.desktop.sidebarShowAllSessions',+ 'hermes.desktop.sidebarShowArchived',+ 'hermes.desktop.sidebarSortKey',+ // Status bar.+ 'hermes.desktop.statusbarHidden.v2',+ 'hermes.desktop.statusbarVisible.v2',+ // Transcript and tools.+ 'hermes.desktop.hideThreadTimeline',+ 'hermes.desktop.reasoning.collapsedByDefault',+ 'hermes.desktop.toolView.hideCodeDiffs',+ 'hermes.desktop.toolView.technical',+ // Shell, panes and behaviour.+ 'hermes.desktop.alwaysExternalLinks.v1',+ 'hermes.desktop.capabilities.catalogCardView',+ 'hermes.desktop.composerPopout.enabled',+ 'hermes.desktop.composerPopout.gesturesEnabled',+ 'hermes.desktop.files.showIgnored',+ 'hermes.desktop.keybinds',+ 'hermes.desktop.layoutPresets.v2',+ 'hermes.desktop.panesFlipped',+ 'hermes.desktop.tabStripDefault',+ 'hermes.desktop.tips.rotation.v1',+ 'hermes.desktop.titlebarAppActions',+ 'hermes.desktop.tours.v1',+ // Sound and media.+ 'hermes.desktop.autoSpeakReplies',+ 'hermes.desktop.completionSoundVariantId',+ 'hermes.desktop.hapticsMuted',+ 'hermes.desktop.videoPlaybackSpeed',+ // Model picker.+ 'hermes.desktop.collapsed-providers',+ 'hermes.desktop.favorite-models',+ 'hermes.desktop.model-presets',+ 'hermes.desktop.visible-models'+])++/** Families whose scope rides in the key suffix (gateway aliases/order/collapsed). */+const SHARED_PREFIXES: readonly string[] = ['hermes.desktop.sidebar.gatewayGroups.v1.']++export function isSharedPreferenceKey(key: string): boolean {+ return SHARED_KEYS.has(key) || SHARED_PREFIXES.some(prefix => key.startsWith(prefix))+}diff --git a/apps/desktop/src/lib/ui-preferences/sync.test.ts b/apps/desktop/src/lib/ui-preferences/sync.test.tsnew file mode 100644index 00000000000..74bc5fc3c49--- /dev/null+++ b/apps/desktop/src/lib/ui-preferences/sync.test.ts@@ -0,0 +1,119 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { persistentAtom } from '../persisted'+import { writeKey } from '../storage'++import { startUiPreferencesSync, type UiPreferencesBridge, type UiPreferencesSnapshot } from './sync'++// A bridge over an in-memory document with the store's semantics: per-key+// merge, null deletes, `seed` applies only while no document exists.+function memoryStore(initial: null | Record<string, string>) {+ let doc: null | UiPreferencesSnapshot = initial ? { exists: true, revision: 1, values: { ...initial } } : null+ const writes: { seed?: boolean; values: Record<string, null | string> }[] = []+ const listeners = new Set<(snapshot: UiPreferencesSnapshot) => void>()+ const snapshot = (): UiPreferencesSnapshot => doc ?? { exists: false, revision: 0, values: {} }++ const bridge: UiPreferencesBridge = {+ read: async () => snapshot(),+ write: async payload => {+ writes.push(payload)++ if (payload.seed && doc) {+ return snapshot()+ }++ const values = { ...(doc?.values ?? {}) }++ for (const [key, value] of Object.entries(payload.values)) {+ if (value === null) {+ delete values[key]+ } else {+ values[key] = value+ }+ }++ doc = { exists: true, revision: (doc?.revision ?? 0) + 1, values }++ return snapshot()+ },+ onChanged: callback => {+ listeners.add(callback)++ return () => listeners.delete(callback)+ }+ }++ const external = (values: Record<string, string>) => {+ doc = { exists: true, revision: (doc?.revision ?? 0) + 1, values }+ listeners.forEach(listener => listener(snapshot()))+ }++ return { bridge, external, snapshot, writes }+}++const DENSITY = 'hermes.desktop.sessionListDensity'+const MODE = 'hermes-desktop-mode-v1'+const DRAFT = 'hermes.desktop.composerQueue.v1'++describe('machine UI preferences sync', () => {+ let stop: () => void = () => undefined++ beforeEach(() => {+ window.localStorage.clear()+ vi.useFakeTimers()+ })++ afterEach(() => {+ stop()+ vi.useRealTimers()+ })++ it('seeds a missing store with only this window’s shared preferences', async () => {+ window.localStorage.setItem(DENSITY, 'detailed')+ window.localStorage.setItem(DRAFT, '[{"text":"unsent"}]')+ const store = memoryStore(null)++ stop = startUiPreferencesSync(store.bridge)+ await vi.runAllTimersAsync()++ expect(store.writes[0]).toEqual({ seed: true, values: { [DENSITY]: 'detailed' } })+ expect(store.snapshot().values).toEqual({ [DENSITY]: 'detailed' })+ })++ it('adopts an existing store over this window’s cache instead of overwriting it', async () => {+ window.localStorage.setItem(DENSITY, 'detailed')+ window.localStorage.setItem(MODE, 'light')+ const $density = persistentAtom(DENSITY, 'compact')+ const store = memoryStore({ [MODE]: 'dark' })++ stop = startUiPreferencesSync(store.bridge)+ await vi.runAllTimersAsync()++ expect(store.writes).toEqual([])+ expect(store.snapshot().values).toEqual({ [MODE]: 'dark' })+ expect(window.localStorage.getItem(MODE)).toBe('dark')+ expect(window.localStorage.getItem(DENSITY)).toBeNull()+ expect($density.get()).toBe('compact')+ })++ it('merges local changes per key and follows changes made elsewhere live', async () => {+ const $density = persistentAtom(DENSITY, 'compact', { decode: raw => raw, encode: value => value })+ const store = memoryStore({ [MODE]: 'dark' })++ stop = startUiPreferencesSync(store.bridge)+ await vi.runAllTimersAsync()++ $density.set('detailed')+ writeKey(DRAFT, 'local only')+ await vi.runAllTimersAsync()++ expect(store.writes).toEqual([{ values: { [DENSITY]: 'detailed' } }])+ expect(store.snapshot().values).toEqual({ [DENSITY]: 'detailed', [MODE]: 'dark' })++ store.external({ [DENSITY]: 'comfortable', [MODE]: 'dark' })+ await vi.runAllTimersAsync()++ expect($density.get()).toBe('comfortable')+ expect(store.writes).toHaveLength(1)+ })+})diff --git a/apps/desktop/src/lib/ui-preferences/sync.ts b/apps/desktop/src/lib/ui-preferences/sync.tsnew file mode 100644index 00000000000..96eb190c678--- /dev/null+++ b/apps/desktop/src/lib/ui-preferences/sync.ts@@ -0,0 +1,246 @@+import type { UiPreferencesSnapshot, UiPreferencesWrite } from '../../../electron/ui-preferences'+import { onPersistenceEvent } from '../storage'++import { isSharedPreferenceKey } from './keys'++export type { UiPreferencesSnapshot, UiPreferencesWrite }++/** The host's door to the machine store: preload IPC natively, `/api/ui-preferences` in a browser. */+export interface UiPreferencesBridge {+ /** Native only: the store as main read it before this window painted. */+ snapshot?: null | UiPreferencesSnapshot+ read(): Promise<UiPreferencesSnapshot>+ write(payload: UiPreferencesWrite): Promise<UiPreferencesSnapshot>+ /** Pushes (native) or polls (browser) the store after another writer changed it. */+ onChanged?(callback: (snapshot: UiPreferencesSnapshot) => void): () => void+}++const FLUSH_DELAY_MS = 250+const RETRY_DELAY_MS = 5000+const MAX_RETRY_DELAY_MS = 60_000++function localSharedKeys(): string[] {+ const keys: string[] = []++ try {+ for (let index = 0; index < window.localStorage.length; index += 1) {+ const key = window.localStorage.key(index)++ if (key && isSharedPreferenceKey(key)) {+ keys.push(key)+ }+ }+ } catch {+ // Restricted storage reads as empty.+ }++ return keys+}++function readRaw(key: string): null | string {+ try {+ return window.localStorage.getItem(key)+ } catch {+ return null+ }+}++/** Set one cached key to the store's value; true when localStorage changed. Raw on+ * purpose: the choke point would echo it back up as a local write. */+function writeRaw(key: string, value: null | string): boolean {+ const previous = readRaw(key)++ if (previous === value) {+ return false+ }++ try {+ if (value === null) {+ window.localStorage.removeItem(key)+ } else {+ window.localStorage.setItem(key, value)+ }+ } catch {+ return false+ }++ return true+}++/**+ * Make this window's localStorage cache match the store, before anything has+ * read it: the first-paint path for native Desktop, whose preload hands over+ * a snapshot synchronously. A store that does not exist yet changes nothing+ * (the sync seeds it from this cache instead).+ */+export function hydrateFromSnapshot(snapshot: null | undefined | UiPreferencesSnapshot): void {+ if (!snapshot?.exists) {+ return+ }++ for (const key of new Set([...localSharedKeys(), ...Object.keys(snapshot.values)])) {+ if (isSharedPreferenceKey(key)) {+ writeRaw(key, snapshot.values[key] ?? null)+ }+ }+}++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.+ window.dispatchEvent(new StorageEvent('storage', { key, newValue, oldValue }))+}++/**+ * Keep this window's shared preferences and the machine store in step:+ * - first contact with no store imports this window's existing values once+ * (`seed`), and never overwrites a store that exists;+ * - a local change to a shared key is merged into the store per key, last+ * write wins, debounced and retried while the store is unreachable;+ * - a change another window, tab or device made lands here live.+ */+export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | undefined): () => void {+ if (!bridge) {+ return () => undefined+ }++ const known = new Map<string, null | string>()+ const pending = new Map<string, null | string>()+ let revision = -1+ let flushTimer: ReturnType<typeof setTimeout> | null = null+ let stopped = false+ // Nothing is written until first contact: a write that created the store+ // ahead of the seed would make the seed see an existing store and skip the+ // rest of this window's values.+ let ready = false++ const apply = (snapshot: UiPreferencesSnapshot, { live }: { live: boolean }) => {+ if (!snapshot.exists || snapshot.revision < revision) {+ return+ }++ revision = snapshot.revision++ for (const key of new Set([...localSharedKeys(), ...Object.keys(snapshot.values), ...known.keys()])) {+ if (!isSharedPreferenceKey(key)) {+ continue+ }++ const value = snapshot.values[key] ?? null+ known.set(key, value)++ // A change made here and not yet stored outranks an older store value.+ if (pending.has(key)) {+ continue+ }++ const previous = readRaw(key)++ if (writeRaw(key, value) && live) {+ announce(key, previous, value)+ }+ }+ }++ const schedule = (delay: number) => {+ if (flushTimer === null && ready && !stopped) {+ flushTimer = setTimeout(() => void flush(), delay)+ }+ }++ const flush = async () => {+ flushTimer = null++ if (pending.size === 0) {+ return+ }++ const batch = new Map(pending)++ try {+ const snapshot = await bridge.write({ values: Object.fromEntries(batch) })++ for (const [key, value] of batch) {+ if (pending.get(key) === value) {+ pending.delete(key)+ }+ }++ apply(snapshot, { live: true })+ } catch {+ schedule(RETRY_DELAY_MS)+ }++ if (pending.size > 0) {+ schedule(FLUSH_DELAY_MS)+ }+ }++ const stopListening = onPersistenceEvent(event => {+ if (event.op === 'read' || !isSharedPreferenceKey(event.key)) {+ return+ }++ if (!pending.has(event.key) && known.has(event.key) && known.get(event.key) === event.value) {+ return+ }++ pending.set(event.key, event.value)+ schedule(FLUSH_DELAY_MS)+ })++ const seed = async (snapshot: UiPreferencesSnapshot) => {+ if (snapshot.exists) {+ return snapshot+ }++ const values = Object.fromEntries(localSharedKeys().map(key => [key, readRaw(key)]))++ return bridge.write({ seed: true, values })+ }++ let connectTimer: ReturnType<typeof setTimeout> | null = null+ let connectDelay = RETRY_DELAY_MS++ const connect = (initial: null | UiPreferencesSnapshot | undefined) => {+ connectTimer = null++ void (initial ? Promise.resolve(initial) : bridge.read())+ .then(seed)+ .then(snapshot => {+ if (stopped) {+ return+ }++ apply(snapshot, { live: true })+ ready = true+ schedule(FLUSH_DELAY_MS)+ })+ .catch(() => {+ // Unreachable store: this window keeps its cached values and local+ // changes stay pending until first contact succeeds.+ if (!stopped) {+ connectTimer = setTimeout(() => connect(null), connectDelay)+ connectDelay = Math.min(connectDelay * 2, MAX_RETRY_DELAY_MS)+ }+ })+ }++ connect(bridge.snapshot)++ const stopChanges = bridge.onChanged?.(snapshot => apply(snapshot, { live: true })) ?? (() => undefined)++ return () => {+ stopped = true+ stopListening()+ stopChanges()++ if (flushTimer !== null) {+ clearTimeout(flushTimer)+ }++ if (connectTimer !== null) {+ clearTimeout(connectTimer)+ }+ }+}diff --git a/apps/desktop/src/main.tsx b/apps/desktop/src/main.tsxindex 1e7f8d9d5ed..157f3f6ea03 100644--- a/apps/desktop/src/main.tsx+++ b/apps/desktop/src/main.tsx@@ -1,4 +1,6 @@import './styles.css'+// Hydrate the machine's shared UI preferences before any store reads them.+import './lib/ui-preferences/boot'// Install the loopback browser host before any store/App modules evaluate.// Electron preload remains authoritative when its bridge already exists.import './lib/browser-desktop-bridge-install'@@ -37,6 +39,7 @@ import { installClipboardShim } from './lib/clipboard'import { queryClient } from './lib/query-client'import { installRendererAnimationPauseState } from './lib/renderer-loop-pause'import { installSelectionCopyColorGuard } from './lib/selection-copy-colors'+import { startUiPreferencesSync } from './lib/ui-preferences/sync'import { installBrowserTabTitle } from './store/browser-tab-title'import { ThemeProvider } from './themes/context'@@ -47,6 +50,8 @@ installClipboardShim()installSelectionCopyColorGuard()// Browser host only: the tab carries session status while the user is away.installBrowserTabTitle()+// One preferences store per machine, shared by native Desktop and its Webapp (#145213).+startUiPreferencesSync(window.hermesDesktop?.uiPreferences)// The perf probe ships in dev, and in a production build ONLY when explicitly// opted in (VITE_PERF_PROBE=1) — this lets the perf harness measure a real,diff --git a/hermes_cli/ui_preferences.py b/hermes_cli/ui_preferences.pynew file mode 100644index 00000000000..7aef9ea5814--- /dev/null+++ b/hermes_cli/ui_preferences.py@@ -0,0 +1,154 @@+"""Machine-level Desktop/Webapp UI preferences (#145213).++One JSON document per machine, beside the ROOT Hermes home (``get_default_hermes_root()``, never a+profile's ``HERMES_HOME``): native Desktop writes it through its preload capability+(``apps/desktop/electron/ui-preferences.ts``) and every browser that opens this machine's Webapp+writes it through ``/api/ui-preferences``. It is deliberately neither per profile nor per gateway+connection; a key that is scoped (``….profile.<name>``) carries its scope in its own name.++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.++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+credentials, grants and per-window state out.+"""++from __future__ import annotations++import os+import threading+import time+from contextlib import contextmanager+from pathlib import Path+from typing import Iterator, Mapping, Optional++from utils import atomic_json_write, read_json_or_empty++STORE_NAME = "ui-preferences.json"+KEY_PREFIXES = ("hermes.desktop.", "hermes-desktop-")+MAX_KEY_CHARS = 256+MAX_VALUE_CHARS = 256 * 1024+MAX_KEYS = 512+MAX_TOTAL_CHARS = 2 * 1024 * 1024+_LOCK_WAIT_S = 3.0+_LOCK_STALE_S = 10.0+_LOCK_POLL_S = 0.02+_thread_lock = threading.Lock()+++class PreferencesError(ValueError):+ """A write the store refuses (bad key, value or size); the route answers 400."""+++class PreferencesBusy(RuntimeError):+ """Another writer held the store lock past the wait; the route answers 503 and the client+ keeps the change pending for its next attempt."""+++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)."""+ if root is None:+ from hermes_constants import get_default_hermes_root++ root = get_default_hermes_root()+ return Path(root) / STORE_NAME+++def _sanitize(values: object) -> dict[str, str]:+ if not isinstance(values, dict):+ return {}+ 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 {}+ revision = doc.get("revision")+ return {+ "exists": exists,+ "revision": revision if isinstance(revision, int) else 0,+ "values": _sanitize(doc.get("values")),+ }+++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())+++def _validate(changes: Mapping[str, Optional[str]]) -> None:+ for key, value in changes.items():+ if not isinstance(key, str) or not key.startswith(KEY_PREFIXES) or len(key) > MAX_KEY_CHARS:+ raise PreferencesError(f"unsupported preference key: {key!r}")+ if value is not None and (not isinstance(value, str) or len(value) > MAX_VALUE_CHARS):+ raise PreferencesError(f"unsupported value for {key}")+++@contextmanager+def _store_lock(path: Path) -> Iterator[None]:+ """Cross-process lock shared with the Electron writer: the ``<store>.lock`` directory."""+ lock_dir = path.with_name(path.name + ".lock")+ deadline = time.monotonic() + _LOCK_WAIT_S+ with _thread_lock:+ while True:+ try:+ os.mkdir(lock_dir)+ break+ except 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+ if time.monotonic() > deadline:+ raise PreferencesBusy("preferences store is busy")+ time.sleep(_LOCK_POLL_S)+ try:+ yield+ finally:+ try:+ os.rmdir(lock_dir)+ except OSError:+ pass+++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.+ """+ _validate(changes)+ path = path or store_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ with _store_lock(path):+ 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+ 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"]:+ return current+ revision = current["revision"] + 1+ atomic_json_write(path, {"version": 1, "revision": revision, "values": values}, mode=0o600)+ return {"exists": True, "revision": revision, "values": values}diff --git a/hermes_cli/web_routers/ui_preferences.py b/hermes_cli/web_routers/ui_preferences.pynew file mode 100644index 00000000000..5190a740322--- /dev/null+++ b/hermes_cli/web_routers/ui_preferences.py@@ -0,0 +1,42 @@+"""``/api/ui-preferences``: the Webapp's door to this machine's UI preferences store (#145213).++Thin HTTP over :mod:`hermes_cli.ui_preferences`. The store belongs to the machine serving the+Webapp, so every browser and origin that opens it reads and writes the same document native+Desktop on this machine uses (through its preload capability, not this route). Mounted only on+surfaces whose policy names ``ui_preferences`` (404 elsewhere) and, like every ``/api/`` route,+only past the session-token / sign-in gate.+"""++from __future__ import annotations++from typing import Optional++from fastapi import APIRouter, HTTPException+from pydantic import BaseModel, Field++from hermes_cli import ui_preferences++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.+ seed: bool = False++[email protected]("/api/ui-preferences")+def get_ui_preferences() -> dict:+ return ui_preferences.read_preferences()++[email protected]("/api/ui-preferences")+def patch_ui_preferences(body: PreferencesPatch) -> dict:+ try:+ return ui_preferences.write_preferences(body.values, seed=body.seed)+ except ui_preferences.PreferencesError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ except ui_preferences.PreferencesBusy as exc:+ raise HTTPException(status_code=503, detail=str(exc)) from excdiff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex d9f9d1babe5..07005e0b202 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -799,6 +799,7 @@ from hermes_cli.web_routers import (shared_metrics as _shared_metrics_routes,delegation as _delegation_routes,webapp_access as _webapp_access_routes,+ ui_preferences as _ui_preferences_routes,)import hermes_cli.web_routers.desktop_plugins as _desktop_plugin_routes@@ -843,6 +844,7 @@ app.include_router(_webapp_routes.router)app.include_router(_shared_metrics_routes.router)app.include_router(_delegation_routes.router)app.include_router(_webapp_access_routes.router, dependencies=[_Depends(_route_on("web_access"))])+app.include_router(_ui_preferences_routes.router, dependencies=[_Depends(_route_on("ui_preferences"))])# Plugin API routes and the dashboard auth routes (/login, /auth/*, /api/auth/*)# mount before the SPA catch-all so /{full_path:path} doesn't swallow them. Authdiff --git a/hermes_cli/web_server_surface.py b/hermes_cli/web_server_surface.pyindex 31b4806774f..17fdf8c74c3 100644--- a/hermes_cli/web_server_surface.py+++ b/hermes_cli/web_server_surface.py@@ -44,25 +44,28 @@ class SurfacePolicy:#: ``/api/desktop-plugins/*`` serves this host's desktop plugins to the browser's plugin loader;#: native Desktop reads its own disk.desktop_plugins: bool+ #: ``/api/ui-preferences`` serves: the browser's door to this machine's UI preferences store+ #: (native Desktop reaches the same file through its preload capability, not over HTTP).+ ui_preferences: boolPOLICIES: dict[str, SurfacePolicy] = {"serve": SurfacePolicy(serves_spa=False, html_token=True, host_terminal=False, launch_link=False, gateway_ticket=False,own_origin_cookie_writes=False, web_access=False, browser_files=False,- desktop_plugins=False),+ desktop_plugins=False, ui_preferences=False),"dashboard": SurfacePolicy(serves_spa=True, html_token=True, host_terminal=False, launch_link=False, gateway_ticket=False,own_origin_cookie_writes=False, web_access=False, browser_files=False,- desktop_plugins=False),+ desktop_plugins=False, ui_preferences=False),"gateway": SurfacePolicy(serves_spa=True, html_token=True, host_terminal=False, launch_link=False, gateway_ticket=False,own_origin_cookie_writes=False, web_access=True, browser_files=False,- desktop_plugins=False),+ desktop_plugins=False, ui_preferences=False),"webapp": SurfacePolicy(serves_spa=True, html_token=False, host_terminal=True, launch_link=True, gateway_ticket=True,own_origin_cookie_writes=True, web_access=True, browser_files=True,- desktop_plugins=True),+ desktop_plugins=True, ui_preferences=True),}diff --git a/tests/hermes_cli/test_ui_preferences.py b/tests/hermes_cli/test_ui_preferences.pynew file mode 100644index 00000000000..0220f0291c4--- /dev/null+++ b/tests/hermes_cli/test_ui_preferences.py@@ -0,0 +1,117 @@+"""The machine's UI preferences store (#145213): one file beside the ROOT Hermes home, shared by+native Desktop and every browser that opens this machine's Webapp.++Contracts: a profile's HERMES_HOME resolves the same file as the root; the one-time localStorage+import never overwrites an existing store; writes merge per key (concurrent writers keep each+other's keys); only Desktop-prefixed string keys are stored; the route exists only on the Webapp+and only past the session-token gate.+"""+from __future__ import annotations++import json+import multiprocessing++import pytest+from fastapi.testclient import TestClient++from hermes_cli import ui_preferences, web_server+++def test_a_profile_home_and_the_root_home_resolve_the_same_store(monkeypatch, tmp_path):+ root = tmp_path / "custom-root"+ (root / "profiles" / "coder").mkdir(parents=True)++ monkeypatch.setenv("HERMES_HOME", str(root))+ from_root = ui_preferences.store_path()+ monkeypatch.setenv("HERMES_HOME", str(root / "profiles" / "coder"))+ from_profile = ui_preferences.store_path()++ assert from_root == from_profile == root / "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"},+ 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"}+++def test_writes_merge_per_key_and_concurrent_writers_keep_each_others_keys(tmp_path):+ path = tmp_path / "ui-preferences.json"+ ui_preferences.write_preferences({"hermes-desktop-mode-v1": "dark", "hermes.desktop.panesFlipped": "true"},+ path=path)++ # Separate processes, like native Desktop and the Webapp's server: only the directory lock+ # stands between their read-merge-replace cycles.+ keys = [f"hermes.desktop.k{n}" for n in range(8)]+ spawn = multiprocessing.get_context("spawn")+ writers = [spawn.Process(target=ui_preferences.write_preferences, args=({key: "1"},),+ kwargs={"path": path}) for key in keys]+ for writer in writers:+ writer.start()+ for writer in writers:+ writer.join(60)+ assert [writer.exitcode for writer in writers] == [0] * len(keys)+ after = ui_preferences.write_preferences({"hermes.desktop.panesFlipped": None}, path=path)++ assert after["values"] == {"hermes-desktop-mode-v1": "dark", **{key: "1" for key in keys}}+ assert after["revision"] == 2 + len(keys)+ assert not path.with_name(path.name + ".lock").exists()++[email protected]("changes", [{"hermes.agent.secret": "x"}, {"hermes.desktop.n": 3}, {"": "x"}])+def test_only_desktop_string_keys_are_stored(tmp_path, changes):+ path = tmp_path / "ui-preferences.json"++ with pytest.raises(ui_preferences.PreferencesError):+ ui_preferences.write_preferences(changes, path=path)+ assert not path.exists()+++def webapp_state(monkeypatch):+ for key in ("ui_surface", "gateway_runner", "listener_public_url", "webapp_home"):+ if hasattr(web_server.app.state, key):+ monkeypatch.delattr(web_server.app.state, key)+ monkeypatch.setattr(web_server.app.state, "auth_required", False, raising=False)+ monkeypatch.setattr(web_server.app.state, "ui_surface", "webapp", raising=False)+++def _client(token: bool) -> TestClient:+ client = TestClient(web_server.app, raise_server_exceptions=False)+ if token:+ client.headers[web_server._SESSION_HEADER_NAME] = web_server._SESSION_TOKEN+ return client+++def test_the_webapp_reads_and_writes_the_machine_store_behind_the_session_gate(webapp_state):+ from hermes_constants import get_default_hermes_root++ store = get_default_hermes_root() / "ui-preferences.json"+ anonymous = _client(token=False)++ assert anonymous.get("/api/ui-preferences").status_code == 401+ assert anonymous.patch("/api/ui-preferences", json={"values": {"hermes-desktop-mode-v1": "dark"}}).status_code == 401+ assert not store.exists()++ tab = _client(token=True)+ assert tab.get("/api/ui-preferences").json() == {"exists": False, "revision": 0, "values": {}}+ written = tab.patch("/api/ui-preferences", json={"values": {"hermes-desktop-mode-v1": "dark"}})+ assert written.status_code == 200+ assert json.loads(store.read_text())["values"] == {"hermes-desktop-mode-v1": "dark"}+ assert tab.patch("/api/ui-preferences", json={"values": {"hermes.other": "x"}}).status_code == 400++[email protected]("surface", [None, "serve", "dashboard"])+def test_the_route_exists_only_on_the_webapp(monkeypatch, webapp_state, surface):+ if surface is None:+ monkeypatch.delattr(web_server.app.state, "ui_surface")+ else:+ monkeypatch.setattr(web_server.app.state, "ui_surface", surface, raising=False)++ assert _client(token=True).get("/api/ui-preferences").status_code == 404