Skip to content

The agent that grows with you

fix(desktop): an app-filled default never enters the shared preferences store

Tekniumaf43648e72e5
diff --git a/apps/desktop/src/lib/storage.ts b/apps/desktop/src/lib/storage.ts
index d9bda5e5b97..bf025b08da4 100644
--- a/apps/desktop/src/lib/storage.ts
+++ b/apps/desktop/src/lib/storage.ts
@@ -3,6 +3,8 @@
// single subscriber (telemetry, cross-window sync, an audit log) can observe all
// of it without instrumenting each call site. No listeners by default → no cost.
+import { isSharedPreferenceKey } from './ui-preferences/keys'
+
export interface PersistenceEvent {
key: string
op: 'read' | 'remove' | 'write'
@@ -44,8 +46,29 @@ export function readKey(key: string): null | string {
return value
}
-/** Raw write. A null value removes the key. Best-effort. */
-export function writeKey(key: string, value: null | string, { provisional = false } = {}) {
+export interface WriteOptions {
+ /** A value this client derives for itself (a default, a heal, a migration
+ * that only fills a default), not a choice the user made. */
+ provisional?: boolean
+}
+
+// Shared preference keys whose value here is provisional. Kept at the choke
+// point, not in the sync, because stores write their load-time value while
+// their module evaluates, before the sync is listening: the machine's shared
+// store never takes such a value, by seed or by write, so a fresh client's
+// defaults cannot fill it ahead of the client that holds the user's choices
+// (#145536 review). Not a shared key itself.
+export const PROVISIONAL_PREFERENCES_KEY = 'hermes:ui-preferences:provisional'
+
+function rawRead(key: string): null | string {
+ try {
+ return window.localStorage.getItem(key)
+ } catch {
+ return null
+ }
+}
+
+function rawWrite(key: string, value: null | string) {
try {
if (value === null) {
window.localStorage.removeItem(key)
@@ -55,10 +78,72 @@ export function writeKey(key: string, value: null | string, { provisional = fals
} catch {
// Storage is best-effort; never let a quota/permission error break the UI.
}
+}
+
+export function provisionalPreferenceKeys(): Set<string> {
+ try {
+ const parsed = JSON.parse(rawRead(PROVISIONAL_PREFERENCES_KEY) ?? '[]') as unknown
+
+ return new Set(Array.isArray(parsed) ? parsed.filter((key): key is string => typeof key === 'string') : [])
+ } catch {
+ return new Set()
+ }
+}
+
+export function markProvisionalPreference(key: string, provisional: boolean) {
+ const keys = provisionalPreferenceKeys()
+
+ if (keys.has(key) === provisional) {
+ return
+ }
+
+ if (provisional) {
+ keys.add(key)
+ } else {
+ keys.delete(key)
+ }
+
+ rawWrite(PROVISIONAL_PREFERENCES_KEY, keys.size === 0 ? null : JSON.stringify([...keys]))
+}
+
+/** Raw write. A null value removes the key. Best-effort. A provisional write
+ * that changes nothing is skipped, and one that rewrites the user's own value
+ * (a heal, a migration from a real value) keeps it theirs. */
+export function writeKey(key: string, value: null | string, { provisional = false }: WriteOptions = {}) {
+ const shared = isSharedPreferenceKey(key)
+
+ if (provisional) {
+ const previous = rawRead(key)
+
+ if (previous === value) {
+ return
+ }
+
+ provisional = value !== null && (!shared || previous === null || provisionalPreferenceKeys().has(key))
+ }
+
+ rawWrite(key, value)
+
+ if (shared) {
+ markProvisionalPreference(key, provisional)
+ }
emitPersistence({ key, op: value === null ? 'remove' : 'write', value, ...(provisional && { provisional }) })
}
+/** Persist a store: the value it loads with (its default, or a heal of what
+ * was stored) as provisional, every later change as the user's. */
+export function persistStore<T>(
+ store: { subscribe(listener: (value: T) => void): () => void },
+ persist: (value: T, options: WriteOptions) => void
+): () => void {
+ let loading = true
+ const stop = store.subscribe(value => persist(value, { provisional: loading }))
+ loading = false
+
+ return stop
+}
+
/** Parsed JSON read. Returns null on absence, unavailable storage, OR malformed
* JSON — callers layer their own shape validation on the parsed value. */
export function readJson<T>(key: string): T | null {
@@ -86,7 +171,7 @@ export function storedBoolean(key: string, fallback: boolean): boolean {
return value === null ? fallback : value === 'true'
}
-export function persistBoolean(key: string, value: boolean, options?: { provisional?: boolean }) {
+export function persistBoolean(key: string, value: boolean, options?: WriteOptions) {
writeKey(key, String(value), options)
}
@@ -94,8 +179,8 @@ export function storedString(key: string): null | string {
return readKey(key)
}
-export function persistString(key: string, value: null | string) {
- writeKey(key, value)
+export function persistString(key: string, value: null | string, options?: WriteOptions) {
+ writeKey(key, value, options)
}
export function storedStringArray(key: string): string[] {
@@ -144,8 +229,8 @@ export function storedStringRecord(key: string): Record<string, string> {
}
}
-export function persistStringRecord(key: string, value: Record<string, string>) {
- writeKey(key, JSON.stringify(value))
+export function persistStringRecord(key: string, value: Record<string, string>, options?: WriteOptions) {
+ writeKey(key, JSON.stringify(value), options)
}
export function arraysEqual(left: string[], right: string[]) {
diff --git a/apps/desktop/src/lib/ui-preferences/sync-defaults.test.ts b/apps/desktop/src/lib/ui-preferences/sync-defaults.test.ts
index 87163d5fb70..a901bd0bc99 100644
--- a/apps/desktop/src/lib/ui-preferences/sync-defaults.test.ts
+++ b/apps/desktop/src/lib/ui-preferences/sync-defaults.test.ts
@@ -20,6 +20,22 @@ import type { UiPreferencesBridge } from './sync'
const TRANSLUCENCY = 'hermes.desktop.translucency.v2'
const AUTO_SPEAK = 'hermes.desktop.autoSpeakReplies'
const THEME = 'hermes-desktop-theme-v2'
+const KEYBINDS = 'hermes.desktop.keybinds'
+const HAPTICS_MUTED = 'hermes.desktop.hapticsMuted'
+
+// Every store that writes its value the moment its module evaluates.
+const LOAD_WRITERS = [
+ () => import('@/store/backdrop'),
+ () => import('@/store/completion-sound'),
+ () => import('@/store/external-links'),
+ () => import('@/store/haptics'),
+ () => import('@/store/keybinds'),
+ () => import('@/store/profile'),
+ () => import('@/store/reasoning-disclosure'),
+ () => import('@/store/thread-timeline'),
+ () => import('@/store/tool-view')
+]
+
const dirs: string[] = []
const tick = (ms = 400) => new Promise(resolve => setTimeout(resolve, ms))
@@ -60,6 +76,22 @@ async function load(file: string, app: () => Promise<void>) {
return { push, stop }
}
+/** One page load in production order: the app's stores evaluate before main.tsx starts the sync. */
+async function boot(file: string) {
+ vi.resetModules()
+ const sync = await import('./sync')
+ sync.captureOwnPreferences()
+ sync.hydrateFromSnapshot(readUiPreferences(file))
+
+ for (const load of LOAD_WRITERS) {
+ await load()
+ }
+
+ const stop = sync.startUiPreferencesSync(realBridge(file).bridge)
+ await tick()
+ stop()
+}
+
/** Native Desktop's localStorage is another origin's: switch to it. */
function becomeNative(values: Record<string, string>) {
window.localStorage.clear()
@@ -135,3 +167,20 @@ it('a migrated auto-speak value stays put here while the store lacks it, and a r
expect(readUiPreferences(file).values).toEqual({ [AUTO_SPEAK]: 'false', [THEME]: 'mono' })
})
+
+it('a fresh browser that reloads before native connects never fills the store with its defaults', async () => {
+ const file = storeFile()
+ await boot(file)
+ await boot(file)
+
+ expect(window.localStorage.getItem(KEYBINDS)).toBe('{}')
+ expect(readUiPreferences(file).values).toEqual({})
+
+ const keybinds = JSON.stringify({ 'composer.modelPicker': ['mod+shift+k'] })
+ becomeNative({ [HAPTICS_MUTED]: 'true', [KEYBINDS]: keybinds })
+ await boot(file)
+
+ expect(window.localStorage.getItem(KEYBINDS)).toBe(keybinds)
+ expect(window.localStorage.getItem(HAPTICS_MUTED)).toBe('true')
+ expect(readUiPreferences(file).values).toEqual({ [HAPTICS_MUTED]: 'true', [KEYBINDS]: keybinds })
+})
diff --git a/apps/desktop/src/lib/ui-preferences/sync.ts b/apps/desktop/src/lib/ui-preferences/sync.ts
index 1f822167cb0..4ee6d2e8a8e 100644
--- a/apps/desktop/src/lib/ui-preferences/sync.ts
+++ b/apps/desktop/src/lib/ui-preferences/sync.ts
@@ -1,5 +1,5 @@
import type { UiPreferencesSnapshot, UiPreferencesWrite } from '../../../electron/ui-preferences'
-import { onPersistenceEvent } from '../storage'
+import { markProvisionalPreference, onPersistenceEvent, provisionalPreferenceKeys } from '../storage'
import { isSharedPreferenceKey } from './keys'
@@ -28,13 +28,6 @@ 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 = 5000
const MAX_RETRY_DELAY_MS = 60_000
@@ -49,47 +42,21 @@ let ownKeys: null | ReadonlySet<string> = null
/** Record this window's own shared keys; boot.ts calls it before anything loads. */
export function captureOwnPreferences(): void {
- const provisional = readProvisional()
+ const provisional = provisionalPreferenceKeys()
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))) {
+ if (value === null && (!prune || provisionalPreferenceKeys().has(key))) {
return
}
if (value !== null) {
- markProvisional(key, false)
+ markProvisionalPreference(key, false)
}
const previous = readRaw(key)
@@ -372,9 +339,7 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
return
}
- // Provisional or not, the latest write decides what this value is.
- markProvisional(event.key, Boolean(event.provisional) && event.op === 'write')
-
+ // A provisional value (storage.ts keeps the mark) never leaves this origin.
if (event.provisional) {
return
}
@@ -395,7 +360,7 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
return snapshot
}
- const provisional = readProvisional()
+ const provisional = provisionalPreferenceKeys()
const values = Object.fromEntries(
localSharedKeys()
diff --git a/apps/desktop/src/store/backdrop.ts b/apps/desktop/src/store/backdrop.ts
index 20fcc26932a..2419095d1be 100644
--- a/apps/desktop/src/store/backdrop.ts
+++ b/apps/desktop/src/store/backdrop.ts
@@ -1,6 +1,6 @@
import { atom } from 'nanostores'
-import { persistBoolean, storedBoolean } from '@/lib/storage'
+import { persistBoolean, persistStore, storedBoolean } from '@/lib/storage'
import { recordFeatureToggle } from './desktop-metrics'
@@ -9,7 +9,7 @@ const KEY = 'hermes.desktop.backdrop.v1'
/** Whether the faint statue image renders behind the chat transcript. */
export const $backdrop = atom(storedBoolean(KEY, false))
-$backdrop.subscribe(on => persistBoolean(KEY, on))
+persistStore($backdrop, (on, options) => persistBoolean(KEY, on, options))
export function setBackdrop(on: boolean) {
recordFeatureToggle('backdrop', $backdrop.get(), on)
diff --git a/apps/desktop/src/store/completion-sound.ts b/apps/desktop/src/store/completion-sound.ts
index f73c2aaddb4..df53605584f 100644
--- a/apps/desktop/src/store/completion-sound.ts
+++ b/apps/desktop/src/store/completion-sound.ts
@@ -1,6 +1,6 @@
import { atom } from 'nanostores'
-import { persistString, storedString } from '@/lib/storage'
+import { persistStore, persistString, storedString } from '@/lib/storage'
const STORAGE_KEY = 'hermes.desktop.completionSoundVariantId'
@@ -29,7 +29,7 @@ function load(): number {
export const $completionSoundVariantId = atom(load())
-$completionSoundVariantId.subscribe(id => persistString(STORAGE_KEY, String(id)))
+persistStore($completionSoundVariantId, (id, options) => persistString(STORAGE_KEY, String(id), options))
export function setCompletionSoundVariantId(variantId: number) {
$completionSoundVariantId.set(resolveCompletionSoundVariantId(variantId))
diff --git a/apps/desktop/src/store/external-links.ts b/apps/desktop/src/store/external-links.ts
index f22c8c0c081..88c1e50fee3 100644
--- a/apps/desktop/src/store/external-links.ts
+++ b/apps/desktop/src/store/external-links.ts
@@ -13,7 +13,7 @@
import { atom } from 'nanostores'
-import { persistBoolean, storedBoolean } from '@/lib/storage'
+import { persistBoolean, persistStore, storedBoolean } from '@/lib/storage'
const KEY = 'hermes.desktop.alwaysExternalLinks.v1'
@@ -24,7 +24,7 @@ export function setAlwaysExternalLinks(on: boolean): void {
}
if (typeof window !== 'undefined') {
- $alwaysExternalLinks.subscribe(on => persistBoolean(KEY, on))
+ persistStore($alwaysExternalLinks, (on, options) => persistBoolean(KEY, on, options))
window.addEventListener('storage', event => {
if (event.key === KEY) {
diff --git a/apps/desktop/src/store/haptics.ts b/apps/desktop/src/store/haptics.ts
index ef600887dab..f5031f1c178 100644
--- a/apps/desktop/src/store/haptics.ts
+++ b/apps/desktop/src/store/haptics.ts
@@ -1,12 +1,12 @@
import { atom } from 'nanostores'
-import { persistBoolean, storedBoolean } from '@/lib/storage'
+import { persistBoolean, persistStore, storedBoolean } from '@/lib/storage'
const HAPTICS_MUTED_STORAGE_KEY = 'hermes.desktop.hapticsMuted'
export const $hapticsMuted = atom(storedBoolean(HAPTICS_MUTED_STORAGE_KEY, false))
-$hapticsMuted.subscribe(muted => persistBoolean(HAPTICS_MUTED_STORAGE_KEY, muted))
+persistStore($hapticsMuted, (muted, options) => persistBoolean(HAPTICS_MUTED_STORAGE_KEY, muted, options))
// Keep automatic cues quiet in every open window, not just the settings window.
if (typeof window !== 'undefined') {
diff --git a/apps/desktop/src/store/keybinds.ts b/apps/desktop/src/store/keybinds.ts
index 597a6c80942..e035dd0abfa 100644
--- a/apps/desktop/src/store/keybinds.ts
+++ b/apps/desktop/src/store/keybinds.ts
@@ -3,7 +3,7 @@ import { atom, computed } from 'nanostores'
import { $registryVersion } from '@/contrib/registry'
import { allKeybindActions, defaultBindings, keybindAction, type KeybindBindings } from '@/lib/keybinds/actions'
import { canonicalizeCombo } from '@/lib/keybinds/combo'
-import { arraysEqual, persistString, storedString } from '@/lib/storage'
+import { arraysEqual, persistStore, persistString, storedString, type WriteOptions } from '@/lib/storage'
const STORAGE_KEY = 'hermes.desktop.keybinds'
@@ -55,7 +55,7 @@ function loadBindings(): KeybindBindings {
// Persist only the actions whose combos differ from their shipped default, so
// changing a default never gets shadowed by a stored snapshot.
-function persistBindings(bindings: KeybindBindings): void {
+function persistBindings(bindings: KeybindBindings, options: WriteOptions): void {
const defaults = defaultBindings()
const diff: KeybindBindings = {}
@@ -79,12 +79,12 @@ function persistBindings(bindings: KeybindBindings): void {
}
}
- persistString(STORAGE_KEY, JSON.stringify(diff))
+ persistString(STORAGE_KEY, JSON.stringify(diff), options)
}
export const $bindings = atom<KeybindBindings>(loadBindings())
-$bindings.subscribe(persistBindings)
+persistStore($bindings, persistBindings)
/** Live combos for an action: explicit binding → stored override → default. */
export function bindingsFor(id: string, bindings: KeybindBindings = $bindings.get()): string[] {
diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.ts
index 41e2d412c38..bacc09cf686 100644
--- a/apps/desktop/src/store/profile.ts
+++ b/apps/desktop/src/store/profile.ts
@@ -9,6 +9,7 @@ import { invalidateProfileScopedQueries } from '@/lib/query-client'
import {
arraysEqual,
persistBoolean,
+ persistStore,
persistStringArray,
persistStringRecord,
storedBoolean,
@@ -221,7 +222,7 @@ const PROFILE_COLORS_STORAGE_KEY = 'hermes.desktop.profileColors'
export const $profileColors = atom<Record<string, string>>(storedStringRecord(PROFILE_COLORS_STORAGE_KEY))
-$profileColors.subscribe(value => persistStringRecord(PROFILE_COLORS_STORAGE_KEY, value))
+persistStore($profileColors, (value, options) => persistStringRecord(PROFILE_COLORS_STORAGE_KEY, value, options))
// Set (or, with null, clear) a profile's color override.
export function setProfileColor(name: string, color: null | string): void {
@@ -958,7 +959,7 @@ const SHOW_ALL_PROFILES_STORAGE_KEY = 'hermes.desktop.showAllProfiles'
// single-profile users (who never see the switcher) are completely unaffected.
export const $showAllProfiles = atom<boolean>(storedBoolean(SHOW_ALL_PROFILES_STORAGE_KEY, false))
-$showAllProfiles.subscribe(value => persistBoolean(SHOW_ALL_PROFILES_STORAGE_KEY, value))
+persistStore($showAllProfiles, (value, options) => persistBoolean(SHOW_ALL_PROFILES_STORAGE_KEY, value, options))
// The profile context the sidebar is currently showing: a concrete profile key,
// or ALL_PROFILES for the unified grouped view. Concrete scope is tied to the
diff --git a/apps/desktop/src/store/reasoning-disclosure.ts b/apps/desktop/src/store/reasoning-disclosure.ts
index cb66d9c7dc5..cbaca97b7ac 100644
--- a/apps/desktop/src/store/reasoning-disclosure.ts
+++ b/apps/desktop/src/store/reasoning-disclosure.ts
@@ -1,6 +1,6 @@
import { atom } from 'nanostores'
-import { persistBoolean, storedBoolean } from '@/lib/storage'
+import { persistBoolean, persistStore, storedBoolean } from '@/lib/storage'
import { modeBound } from '@/store/interface-mode'
import type { HermesConfig } from '@/types/hermes'
@@ -10,7 +10,9 @@ const REASONING_COLLAPSED_BY_DEFAULT_STORAGE_KEY = 'hermes.desktop.reasoning.col
* Simple mode rests reasoning collapsed without touching this preference. */
const $reasoningCollapsedByDefaultPref = atom(storedBoolean(REASONING_COLLAPSED_BY_DEFAULT_STORAGE_KEY, false))
-$reasoningCollapsedByDefaultPref.subscribe(value => persistBoolean(REASONING_COLLAPSED_BY_DEFAULT_STORAGE_KEY, value))
+persistStore($reasoningCollapsedByDefaultPref, (value, options) =>
+ persistBoolean(REASONING_COLLAPSED_BY_DEFAULT_STORAGE_KEY, value, options)
+)
export const $reasoningCollapsedByDefault = modeBound(
'reasoningCollapsedByDefault',
diff --git a/apps/desktop/src/store/thread-timeline.ts b/apps/desktop/src/store/thread-timeline.ts
index f339e814506..740b68ad900 100644
--- a/apps/desktop/src/store/thread-timeline.ts
+++ b/apps/desktop/src/store/thread-timeline.ts
@@ -1,6 +1,6 @@
import { atom } from 'nanostores'
-import { persistBoolean, storedBoolean } from '@/lib/storage'
+import { persistBoolean, persistStore, storedBoolean } from '@/lib/storage'
import { recordFeatureToggle } from './desktop-metrics'
@@ -9,7 +9,7 @@ const HIDE_THREAD_TIMELINE_STORAGE_KEY = 'hermes.desktop.hideThreadTimeline'
/** Desktop-local appearance preference, shared by all threads in this window. */
export const $hideThreadTimeline = atom(storedBoolean(HIDE_THREAD_TIMELINE_STORAGE_KEY, false))
-$hideThreadTimeline.subscribe(value => persistBoolean(HIDE_THREAD_TIMELINE_STORAGE_KEY, value))
+persistStore($hideThreadTimeline, (value, options) => persistBoolean(HIDE_THREAD_TIMELINE_STORAGE_KEY, value, options))
export function setHideThreadTimeline(value: boolean) {
recordFeatureToggle('thread_timeline', !$hideThreadTimeline.get(), !value)
diff --git a/apps/desktop/src/store/tool-view.ts b/apps/desktop/src/store/tool-view.ts
index 3ba27d7e6c6..08c5d244b3c 100644
--- a/apps/desktop/src/store/tool-view.ts
+++ b/apps/desktop/src/store/tool-view.ts
@@ -1,6 +1,6 @@
import { atom, computed, onStop, type ReadableAtom } from 'nanostores'
-import { persistBoolean, storedBoolean } from '@/lib/storage'
+import { persistBoolean, persistStore, storedBoolean } from '@/lib/storage'
import { modeBound } from '@/store/interface-mode'
export type ToolViewMode = 'product' | 'technical'
@@ -26,8 +26,10 @@ export const $toolDisclosureStates = atom<ToolDisclosureStates>(loadToolDisclosu
const disclosureOpenCache = new Map<string, ReadableAtom<boolean | undefined>>()
const anyDisclosureOpenCache = new Map<string, ReadableAtom<boolean>>()
-$toolViewModePref.subscribe(mode => persistBoolean(TOOL_VIEW_TECHNICAL_STORAGE_KEY, mode === 'technical'))
-$hideCodeDiffsPref.subscribe(hidden => persistBoolean(HIDE_CODE_DIFFS_STORAGE_KEY, hidden))
+persistStore($toolViewModePref, (mode, options) =>
+ persistBoolean(TOOL_VIEW_TECHNICAL_STORAGE_KEY, mode === 'technical', options)
+)
+persistStore($hideCodeDiffsPref, (hidden, options) => persistBoolean(HIDE_CODE_DIFFS_STORAGE_KEY, hidden, options))
$toolDisclosureStates.subscribe(persistToolDisclosureStates)
export function setToolViewMode(mode: ToolViewMode) {