The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): load-time defaults never overwrite another client's shared preference
Teknium8e3b928b2f28
diff --git a/apps/desktop/src/lib/storage.ts b/apps/desktop/src/lib/storage.tsindex bc3eb13aa3b..d9bda5e5b97 100644--- a/apps/desktop/src/lib/storage.ts+++ b/apps/desktop/src/lib/storage.ts@@ -6,6 +6,9 @@export interface PersistenceEvent {key: stringop: 'read' | 'remove' | 'write'+ /** A value this client stored for itself (a migration or a default), not a+ * choice the user made: the machine's shared preferences never take it. */+ provisional?: booleanvalue: null | string}@@ -42,7 +45,7 @@ export function readKey(key: string): null | string {}/** Raw write. A null value removes the key. Best-effort. */-export function writeKey(key: string, value: null | string) {+export function writeKey(key: string, value: null | string, { provisional = false } = {}) {try {if (value === null) {window.localStorage.removeItem(key)@@ -53,7 +56,7 @@ export function writeKey(key: string, value: null | string) {// Storage is best-effort; never let a quota/permission error break the UI.}- emitPersistence({ key, op: value === null ? 'remove' : 'write', value })+ emitPersistence({ key, op: value === null ? 'remove' : 'write', value, ...(provisional && { provisional }) })}/** Parsed JSON read. Returns null on absence, unavailable storage, OR malformed@@ -83,8 +86,8 @@ export function storedBoolean(key: string, fallback: boolean): boolean {return value === null ? fallback : value === 'true'}-export function persistBoolean(key: string, value: boolean) {- writeKey(key, String(value))+export function persistBoolean(key: string, value: boolean, options?: { provisional?: boolean }) {+ writeKey(key, String(value), options)}export function storedString(key: string): null | string {diff --git a/apps/desktop/src/lib/ui-preferences/sync-defaults.test.ts b/apps/desktop/src/lib/ui-preferences/sync-defaults.test.tsnew file mode 100644index 00000000000..87163d5fb70--- /dev/null+++ b/apps/desktop/src/lib/ui-preferences/sync-defaults.test.ts@@ -0,0 +1,137 @@+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'++import { afterEach, expect, it, vi } from 'vitest'++import {+ parseUiPreferencesWrite,+ readUiPreferences,+ type UiPreferencesSnapshot,+ writeUiPreferences+} from '../../../electron/ui-preferences'++import type { UiPreferencesBridge } from './sync'++// A value a store writes for itself at load (its default, a migration from+// config) is not the user's choice and must never reach the machine's store+// ahead of the client that holds the real one (#145536 review), against the+// real native writer on a real file.+const TRANSLUCENCY = 'hermes.desktop.translucency.v2'+const AUTO_SPEAK = 'hermes.desktop.autoSpeakReplies'+const THEME = 'hermes-desktop-theme-v2'+const dirs: string[] = []+const tick = (ms = 400) => new Promise(resolve => setTimeout(resolve, ms))++function storeFile(): string {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-ui-defaults-'))+ dirs.push(dir)++ return path.join(dir, 'ui-preferences.json')+}++function realBridge(file: string) {+ let changed: ((snapshot: UiPreferencesSnapshot) => void) | null = null++ const bridge: UiPreferencesBridge = {+ read: async () => readUiPreferences(file),+ write: payload => writeUiPreferences(file, parseUiPreferencesWrite(payload)),+ onChanged: callback => {+ changed = callback++ return () => (changed = null)+ }+ }++ return { bridge, push: () => changed?.(readUiPreferences(file)) }+}++/** One page load, as boot.ts + main.tsx run it: capture, hydrate, then the app's stores. */+async function load(file: string, app: () => Promise<void>) {+ vi.resetModules()+ const sync = await import('./sync')+ sync.captureOwnPreferences()+ sync.hydrateFromSnapshot(readUiPreferences(file))+ const { bridge, push } = realBridge(file)+ const stop = sync.startUiPreferencesSync(bridge)+ await app()+ await tick()++ return { push, stop }+}++/** Native Desktop's localStorage is another origin's: switch to it. */+function becomeNative(values: Record<string, string>) {+ window.localStorage.clear()+ window.sessionStorage.clear()+ Object.entries(values).forEach(([key, value]) => window.localStorage.setItem(key, value))+}++afterEach(() => {+ window.localStorage.clear()+ window.sessionStorage.clear()++ for (const dir of dirs.splice(0)) {+ fs.rmSync(dir, { force: true, recursive: true })+ }+})++it('a fresh browser’s translucency default never replaces native’s custom translucency', async () => {+ const file = storeFile()+ const browser = await load(file, async () => void (await import('@/store/translucency')))+ browser.stop()++ const custom = JSON.stringify({ mode: 'clear', base: { intensity: 61 }, light: {}, dark: {} })+ becomeNative({ [TRANSLUCENCY]: custom })+ const native = await load(file, async () => void (await import('@/store/translucency')))+ native.stop()++ expect(window.localStorage.getItem(TRANSLUCENCY)).toBe(custom)+ expect(readUiPreferences(file).values[TRANSLUCENCY]).toBe(custom)+})++it('a fresh browser’s auto-speak migration never replaces native’s choice, across a browser reload too', async () => {+ const file = storeFile()++ const migrate = async () => {+ const prefs = await import('@/store/voice-prefs')+ prefs.applyAutoSpeakFromConfig({ voice: { auto_tts: false } })+ }++ ;(await load(file, migrate)).stop()+ // The reload finds its migrated value already in localStorage.+ ;(await load(file, migrate)).stop()+ expect(window.localStorage.getItem(AUTO_SPEAK)).toBe('false')++ becomeNative({ [AUTO_SPEAK]: 'true' })+ const native = await load(file, migrate)+ native.stop()++ expect(window.localStorage.getItem(AUTO_SPEAK)).toBe('true')+ expect(readUiPreferences(file).values[AUTO_SPEAK]).toBe('true')+})++it('a migrated auto-speak value stays put here while the store lacks it, and a real choice is shared', async () => {+ const file = storeFile()+ becomeNative({ [THEME]: 'nous' })+ const choose: { autoSpeak?: (enabled: boolean) => Promise<void> } = {}++ const native = await load(file, async () => {+ const prefs = await import('@/store/voice-prefs')+ prefs.applyAutoSpeakFromConfig({ voice: { auto_tts: true } })+ choose.autoSpeak = prefs.setAutoSpeakReplies+ })++ // Another client's change reaches this joined window: nothing it lacks is pruned.+ await writeUiPreferences(file, { values: { [THEME]: 'mono' } })+ native.push()+ await tick()+ expect(window.localStorage.getItem(AUTO_SPEAK)).toBe('true')+ expect(readUiPreferences(file).values).toEqual({ [THEME]: 'mono' })++ await choose.autoSpeak?.(false)+ await tick()+ native.stop()++ expect(readUiPreferences(file).values).toEqual({ [AUTO_SPEAK]: 'false', [THEME]: 'mono' })+})diff --git a/apps/desktop/src/lib/ui-preferences/sync.ts b/apps/desktop/src/lib/ui-preferences/sync.tsindex fedd644dd35..1f822167cb0 100644--- a/apps/desktop/src/lib/ui-preferences/sync.ts+++ b/apps/desktop/src/lib/ui-preferences/sync.ts@@ -28,6 +28,13 @@ const TAB_KEY = 'hermes:ui-preferences:tab'// Until then a key the store lacks is never removed here: it may be this// client's data the store has not received yet, not a peer's deletion.const JOINED_KEY = 'hermes:ui-preferences:generation'+// Shared keys whose value here is provisional: one this client stored for+// itself (a migration from its own config, a default), not a user's choice.+// Such a value never enters the store, by seed or by write: a fresh browser's+// default would otherwise sit there first and the client with the real value+// (native Desktop's) could not import it. It stays here until the store has a+// value for the key, or the user makes a real change.+const PROVISIONAL_KEY = 'hermes:ui-preferences:provisional'const RETRY_DELAY_MS = 5000const MAX_RETRY_DELAY_MS = 60_000@@ -42,7 +49,54 @@ let ownKeys: null | ReadonlySet<string> = null/** Record this window's own shared keys; boot.ts calls it before anything loads. */export function captureOwnPreferences(): void {- ownKeys = new Set(localSharedKeys())+ const provisional = readProvisional()++ ownKeys = new Set(localSharedKeys().filter(key => !provisional.has(key)))+}++function readProvisional(): Set<string> {+ try {+ const parsed = JSON.parse(readRaw(PROVISIONAL_KEY) ?? '[]') as unknown++ return new Set(Array.isArray(parsed) ? parsed.filter((key): key is string => typeof key === 'string') : [])+ } catch {+ return new Set()+ }+}++function markProvisional(key: string, provisional: boolean) {+ const keys = readProvisional()++ if (keys.has(key) === provisional) {+ return+ }++ if (provisional) {+ keys.add(key)+ } else {+ keys.delete(key)+ }++ writeRaw(PROVISIONAL_KEY, keys.size === 0 ? null : JSON.stringify([...keys]))+}++/** Cache one store value here. A key the store lacks is removed only once+ * this origin joined (`prune`), and never while its value here is+ * provisional; a value the store has replaces a provisional one for good. */+function adopt(key: string, value: null | string, prune: boolean, live: boolean) {+ if (value === null && (!prune || readProvisional().has(key))) {+ return+ }++ if (value !== null) {+ markProvisional(key, false)+ }++ const previous = readRaw(key)++ if (writeRaw(key, value) && live) {+ announce(key, previous, value)+ }}/** This tab's outbox key, claimed once per page load. The previous load of this@@ -148,16 +202,8 @@ export function hydrateFromSnapshot(snapshot: null | undefined | UiPreferencesSnconst prune = hasJoined(snapshot)for (const key of new Set([...localSharedKeys(), ...Object.keys(snapshot.values)])) {- const value = snapshot.values[key] ?? null-- if (!isSharedPreferenceKey(key) || outbox.has(key) || (value === null && !prune)) {- continue- }-- const previous = readRaw(key)-- if (writeRaw(key, value)) {- announce(key, previous, value)+ if (isSharedPreferenceKey(key) && !outbox.has(key)) {+ adopt(key, snapshot.values[key] ?? null, prune, true)}}}@@ -206,7 +252,8 @@ function announce(key: string, oldValue: null | string, newValue: null | string)* overwritten); until then no local key is removed for being absent there;* - 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.+ * - a change another window, tab or device made lands here live;+ * - a provisional value (a write marked `provisional`) never leaves this origin.*/export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | undefined): () => void {if (!bridge) {@@ -252,14 +299,8 @@ 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) || (refused.has(key) && refused.get(key) === readRaw(key)) || (value === null && !prune)) {- continue- }-- const previous = readRaw(key)-- if (writeRaw(key, value) && live) {- announce(key, previous, value)+ if (!pending.has(key) && !(refused.has(key) && refused.get(key) === readRaw(key))) {+ adopt(key, value, prune, live)}}@@ -331,6 +372,13 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | undereturn}+ // Provisional or not, the latest write decides what this value is.+ markProvisional(event.key, Boolean(event.provisional) && event.op === 'write')++ if (event.provisional) {+ return+ }+if (!pending.has(event.key) && known.has(event.key) && known.get(event.key) === event.value) {return}@@ -347,9 +395,11 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | undereturn snapshot}+ const provisional = readProvisional()+const values = Object.fromEntries(localSharedKeys()- .filter(key => !ownKeys || ownKeys.has(key))+ .filter(key => (!ownKeys || ownKeys.has(key)) && !provisional.has(key)).map(key => [key, readRaw(key)]))diff --git a/apps/desktop/src/store/translucency.ts b/apps/desktop/src/store/translucency.tsindex c2ef7c73e98..88aeaf40cb8 100644--- a/apps/desktop/src/store/translucency.ts+++ b/apps/desktop/src/store/translucency.ts@@ -366,9 +366,19 @@ if (typeof window !== 'undefined') {// setOpacity in clear mode and nothing at all under glass.let storageTimer: null | number = null+ // Only an edit is written. The book this window loaded, or adopted from a+ // sibling or the machine's shared preferences, already resolves from+ // storage: writing it back would push this window's default or its+ // normalisation (no glass in a browser) into the shared store over the+ // value the user set in native Desktop (#145213). A v1 state still lands in+ // v2 on first load, since v2 does not resolve to it yet.const persist = () => {storageTimer = null- writeJson(KEY, $translucencyBook.get())+ const book = $translucencyBook.get()++ if (JSON.stringify(book) !== JSON.stringify(normalizeBook(readJson<unknown>(KEY), GLASS_SUPPORTED))) {+ writeJson(KEY, book)+ }}// The RESOLVED state drives paint and IPC — main only ever cares about thediff --git a/apps/desktop/src/store/voice-prefs.ts b/apps/desktop/src/store/voice-prefs.tsindex 4a648df8e9e..6e76f6cd2b0 100644--- a/apps/desktop/src/store/voice-prefs.ts+++ b/apps/desktop/src/store/voice-prefs.ts@@ -8,13 +8,22 @@ export const $autoSpeakReplies = atom<boolean>(storedBoolean(AUTO_SPEAK_KEY, fal// Best-effort persistence must not give config refresh authority again.let autoSpeakChosen = readKey(AUTO_SPEAK_KEY) !== null-/** Migrate the legacy value once without editing the backend configuration. */+/** Migrate the legacy value once without editing the backend configuration.+ * Provisional: every client on this machine migrates from the same config, and+ * a fresh browser's migrated value must not replace one the user chose in+ * native Desktop in the machine's shared preferences (#145213). */export function applyAutoSpeakFromConfig(config: { voice?: { auto_tts?: unknown } | null } | null | undefined) {if (config != null && !autoSpeakChosen) {- void setAutoSpeakReplies(Boolean(config.voice?.auto_tts))+ storeAutoSpeak(Boolean(config.voice?.auto_tts), true)}}+function storeAutoSpeak(enabled: boolean, provisional: boolean) {+ autoSpeakChosen = true+ persistBoolean(AUTO_SPEAK_KEY, enabled, { provisional })+ $autoSpeakReplies.set(enabled)+}+// Backend default for `voice.stop_phrases` (DEFAULT_VOICE_STOP_PHRASES in// tools/voice_mode_transcript.py), used until `/api/config/defaults` answers.const BACKEND_DEFAULT_STOP_PHRASES: readonly string[] = ['stop']@@ -158,7 +167,5 @@ export function applyThinkingSoundFromConfig(/** Persist even an unchanged value, so migrating false is also one-time. */export async function setAutoSpeakReplies(enabled: boolean): Promise<void> {- autoSpeakChosen = true- persistBoolean(AUTO_SPEAK_KEY, enabled)- $autoSpeakReplies.set(enabled)+ storeAutoSpeak(enabled, false)}