Skip to content

The agent that grows with you

fix(desktop): a default an older build stored at load never seeds the machine's preferences

Teknium930a81a5b100
diff --git a/apps/desktop/src/lib/persist-store.ts b/apps/desktop/src/lib/persist-store.ts
index 9230725819d..86b8befb567 100644
--- a/apps/desktop/src/lib/persist-store.ts
+++ b/apps/desktop/src/lib/persist-store.ts
@@ -1,13 +1,23 @@
import type { WriteOptions } from '@/lib/storage'
/** 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. */
+ * was stored) as provisional, every later change as the user's. A load value
+ * equal to `fallback` (the store's default) is provisional even when it is
+ * already stored: older builds persisted every default at load, unmarked, and
+ * a default carries no choice the machine's shared store should take over
+ * another client's real one (#145536 re-review). */
export function persistStore<T>(
store: { subscribe(listener: (value: T) => void): () => void },
- persist: (value: T, options: WriteOptions) => void
+ persist: (value: T, options: WriteOptions) => void,
+ fallback: T
): () => void {
let loading = true
- const stop = store.subscribe(value => persist(value, { provisional: loading }))
+ const fallbackJson = JSON.stringify(fallback)
+
+ const stop = store.subscribe(value =>
+ persist(value, loading ? { isDefault: JSON.stringify(value) === fallbackJson, provisional: true } : {})
+ )
+
loading = false
return stop
diff --git a/apps/desktop/src/lib/storage.ts b/apps/desktop/src/lib/storage.ts
index 6a3bb9663c3..5011f9bdbcb 100644
--- a/apps/desktop/src/lib/storage.ts
+++ b/apps/desktop/src/lib/storage.ts
@@ -47,6 +47,9 @@ export function readKey(key: string): null | string {
}
export interface WriteOptions {
+ /** With `provisional`: the value is the store's default, so it stays
+ * provisional even when it is already stored (an older build wrote it). */
+ isDefault?: boolean
/** 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
@@ -109,17 +112,25 @@ export function markProvisionalPreference(key: string, provisional: boolean) {
/** 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 = {}) {
+export function writeKey(
+ key: string,
+ value: null | string,
+ { isDefault = false, provisional = false }: WriteOptions = {}
+) {
const shared = isSharedPreferenceKey(key)
if (provisional) {
const previous = rawRead(key)
if (previous === value) {
+ if (shared && isDefault && value !== null) {
+ markProvisionalPreference(key, true)
+ }
+
return
}
- provisional = value !== null && (!shared || previous === null || provisionalPreferenceKeys().has(key))
+ provisional = value !== null && (isDefault || !shared || previous === null || provisionalPreferenceKeys().has(key))
}
rawWrite(key, value)
@@ -191,8 +202,8 @@ export function storedStringArray(key: string): string[] {
}
}
-export function persistStringArray(key: string, value: string[]) {
- writeKey(key, value.length === 0 ? null : JSON.stringify(value))
+export function persistStringArray(key: string, value: string[], options?: WriteOptions) {
+ writeKey(key, value.length === 0 ? null : JSON.stringify(value), options)
}
export function storedStringRecord(key: string): Record<string, string> {
diff --git a/apps/desktop/src/lib/ui-preferences/sync-handoff.test.ts b/apps/desktop/src/lib/ui-preferences/sync-handoff.test.ts
new file mode 100644
index 00000000000..2e95f31674e
--- /dev/null
+++ b/apps/desktop/src/lib/ui-preferences/sync-handoff.test.ts
@@ -0,0 +1,135 @@
+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,
+ writeUiPreferences
+} from '../../../electron/ui-preferences'
+
+import type { UiPreferencesBridge } from './sync'
+
+// Hand-offs between clients and page loads, against the real native writer on
+// a real file (#145536 re-review): an upgraded browser's old defaults, a closed
+// tab's unsent edit, a first snapshot that lands after the app read its cache.
+const KEYBINDS = 'hermes.desktop.keybinds'
+const HAPTICS = 'hermes.desktop.hapticsMuted'
+const MODE = 'hermes-desktop-mode-v1'
+const FAVORITES = 'hermes.desktop.favorite-models'
+const OUTBOX_PREFIX = 'hermes:ui-preferences:outbox:'
+const CUSTOM_KEYBINDS = '{"composer.dictate":["mod+shift+d"]}'
+
+// 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'),
+ () => import('@/store/translucency')
+]
+
+const dirs: string[] = []
+const stops: (() => void)[] = []
+const tick = (ms = 400) => new Promise(resolve => setTimeout(resolve, ms))
+
+function storeFile(): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-ui-handoff-'))
+ dirs.push(dir)
+
+ return path.join(dir, 'ui-preferences.json')
+}
+
+function bridgeFor(file: string, { offline = false, slow = false } = {}): UiPreferencesBridge {
+ const down = () => Promise.reject(new Error('fetch failed'))
+
+ return {
+ read: async () => (offline ? down() : (slow && (await tick(300)), readUiPreferences(file))),
+ write: async payload => (offline ? down() : writeUiPreferences(file, parseUiPreferencesWrite(payload))),
+ onChanged: () => () => undefined
+ }
+}
+
+interface LoadOptions {
+ /** No snapshot before the app loads: the boot read timed out or failed. */
+ late?: boolean
+ offline?: boolean
+ stores?: (() => Promise<unknown>)[]
+}
+
+/** One page load as entry.ts/boot.ts + main.tsx run it. */
+async function pageLoad(file: string, { late = false, offline = false, stores = LOAD_WRITERS }: LoadOptions = {}) {
+ vi.resetModules()
+ const sync = await import('./sync')
+ sync.captureOwnPreferences()
+ sync.hydrateFromSnapshot(offline || late || !fs.existsSync(file) ? null : readUiPreferences(file))
+
+ for (const load of stores) {
+ await load()
+ }
+
+ stops.push(sync.startUiPreferencesSync(bridgeFor(file, { offline, slow: late })))
+ await tick(late ? 700 : 400)
+}
+
+function closeTabs() {
+ stops.splice(0).forEach(stop => stop())
+}
+
+/** This origin's storage is another client's: native Desktop, or a new browser profile. */
+function becomeClient(values: Record<string, string>) {
+ closeTabs()
+ window.localStorage.clear()
+ window.sessionStorage.clear()
+ Object.entries(values).forEach(([key, value]) => window.localStorage.setItem(key, value))
+}
+
+const outboxes = () =>
+ Array.from({ length: window.localStorage.length }, (_, index) => window.localStorage.key(index) ?? '').filter(key =>
+ key.startsWith(OUTBOX_PREFIX)
+ )
+
+afterEach(() => {
+ closeTabs()
+ vi.useRealTimers()
+ window.localStorage.clear()
+ window.sessionStorage.clear()
+
+ for (const dir of dirs.splice(0)) {
+ fs.rmSync(dir, { force: true, recursive: true })
+ }
+})
+
+it('a browser upgraded from a build that stored every default at load never seeds them over native’s choices', async () => {
+ const file = storeFile()
+
+ // What that build left in a browser: each load-time store's default, unmarked.
+ await pageLoad(file, { offline: true })
+
+ const oldDefaults = Object.fromEntries(
+ Array.from({ length: window.localStorage.length }, (_, index) => window.localStorage.key(index) ?? '')
+ .filter(key => key.startsWith('hermes.desktop.') || key.startsWith('hermes-desktop-'))
+ .map(key => [key, window.localStorage.getItem(key) ?? ''])
+ )
+
+ expect(oldDefaults).toMatchObject({ [HAPTICS]: 'false', [KEYBINDS]: '{}' })
+
+ becomeClient(oldDefaults)
+ await pageLoad(file)
+
+ becomeClient({ [HAPTICS]: 'true', [KEYBINDS]: CUSTOM_KEYBINDS })
+ await pageLoad(file)
+
+ expect([window.localStorage.getItem(KEYBINDS), window.localStorage.getItem(HAPTICS)]).toEqual([
+ CUSTOM_KEYBINDS,
+ 'true'
+ ])
+ expect(readUiPreferences(file).values).toEqual({ [HAPTICS]: 'true', [KEYBINDS]: CUSTOM_KEYBINDS })
+})
diff --git a/apps/desktop/src/store/backdrop.ts b/apps/desktop/src/store/backdrop.ts
index 5d8472b356a..bb34b7b5e86 100644
--- a/apps/desktop/src/store/backdrop.ts
+++ b/apps/desktop/src/store/backdrop.ts
@@ -10,7 +10,7 @@ const KEY = 'hermes.desktop.backdrop.v1'
/** Whether the faint statue image renders behind the chat transcript. */
export const $backdrop = atom(storedBoolean(KEY, false))
-persistStore($backdrop, (on, options) => persistBoolean(KEY, on, options))
+persistStore($backdrop, (on, options) => persistBoolean(KEY, on, options), false)
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 5e8c7b4f65f..ec92453029b 100644
--- a/apps/desktop/src/store/completion-sound.ts
+++ b/apps/desktop/src/store/completion-sound.ts
@@ -30,7 +30,11 @@ function load(): number {
export const $completionSoundVariantId = atom(load())
-persistStore($completionSoundVariantId, (id, options) => persistString(STORAGE_KEY, String(id), options))
+persistStore(
+ $completionSoundVariantId,
+ (id, options) => persistString(STORAGE_KEY, String(id), options),
+ DEFAULT_COMPLETION_SOUND_VARIANT_ID
+)
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 00775be9a84..e1c031287f3 100644
--- a/apps/desktop/src/store/external-links.ts
+++ b/apps/desktop/src/store/external-links.ts
@@ -25,7 +25,7 @@ export function setAlwaysExternalLinks(on: boolean): void {
}
if (typeof window !== 'undefined') {
- persistStore($alwaysExternalLinks, (on, options) => persistBoolean(KEY, on, options))
+ persistStore($alwaysExternalLinks, (on, options) => persistBoolean(KEY, on, options), false)
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 1421b0b194c..d60652e8d88 100644
--- a/apps/desktop/src/store/haptics.ts
+++ b/apps/desktop/src/store/haptics.ts
@@ -7,7 +7,7 @@ const HAPTICS_MUTED_STORAGE_KEY = 'hermes.desktop.hapticsMuted'
export const $hapticsMuted = atom(storedBoolean(HAPTICS_MUTED_STORAGE_KEY, false))
-persistStore($hapticsMuted, (muted, options) => persistBoolean(HAPTICS_MUTED_STORAGE_KEY, muted, options))
+persistStore($hapticsMuted, (muted, options) => persistBoolean(HAPTICS_MUTED_STORAGE_KEY, muted, options), false)
// 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 a71cf455a52..5a3812fd48a 100644
--- a/apps/desktop/src/store/keybinds.ts
+++ b/apps/desktop/src/store/keybinds.ts
@@ -85,7 +85,7 @@ function persistBindings(bindings: KeybindBindings, options: WriteOptions): void
export const $bindings = atom<KeybindBindings>(loadBindings())
-persistStore($bindings, persistBindings)
+persistStore($bindings, persistBindings, defaultBindings())
/** 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 71be99153cf..8fa499daebc 100644
--- a/apps/desktop/src/store/profile.ts
+++ b/apps/desktop/src/store/profile.ts
@@ -193,7 +193,7 @@ const PROFILE_ORDER_STORAGE_KEY = 'hermes.desktop.profileOrder'
export const $profileOrder = atom<string[]>(storedStringArray(PROFILE_ORDER_STORAGE_KEY))
-$profileOrder.subscribe(value => persistStringArray(PROFILE_ORDER_STORAGE_KEY, [...value]))
+persistStore($profileOrder, (value, options) => persistStringArray(PROFILE_ORDER_STORAGE_KEY, [...value], options), [])
export function setProfileOrder(names: string[]): void {
if (!arraysEqual($profileOrder.get(), names)) {
@@ -214,7 +214,7 @@ const PROFILE_COLORS_STORAGE_KEY = 'hermes.desktop.profileColors'
export const $profileColors = atom<Record<string, string>>(storedStringRecord(PROFILE_COLORS_STORAGE_KEY))
-persistStore($profileColors, (value, options) => persistStringRecord(PROFILE_COLORS_STORAGE_KEY, value, options))
+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 {
@@ -951,7 +951,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))
-persistStore($showAllProfiles, (value, options) => persistBoolean(SHOW_ALL_PROFILES_STORAGE_KEY, value, options))
+persistStore($showAllProfiles, (value, options) => persistBoolean(SHOW_ALL_PROFILES_STORAGE_KEY, value, options), false)
// 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 44c0a718655..6f54bb72f2d 100644
--- a/apps/desktop/src/store/reasoning-disclosure.ts
+++ b/apps/desktop/src/store/reasoning-disclosure.ts
@@ -11,8 +11,10 @@ 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))
-persistStore($reasoningCollapsedByDefaultPref, (value, options) =>
- persistBoolean(REASONING_COLLAPSED_BY_DEFAULT_STORAGE_KEY, value, options)
+persistStore(
+ $reasoningCollapsedByDefaultPref,
+ (value, options) => persistBoolean(REASONING_COLLAPSED_BY_DEFAULT_STORAGE_KEY, value, options),
+ false
)
export const $reasoningCollapsedByDefault = modeBound(
diff --git a/apps/desktop/src/store/thread-timeline.ts b/apps/desktop/src/store/thread-timeline.ts
index a28898629c1..6be8725956f 100644
--- a/apps/desktop/src/store/thread-timeline.ts
+++ b/apps/desktop/src/store/thread-timeline.ts
@@ -10,7 +10,11 @@ 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))
-persistStore($hideThreadTimeline, (value, options) => persistBoolean(HIDE_THREAD_TIMELINE_STORAGE_KEY, value, options))
+persistStore(
+ $hideThreadTimeline,
+ (value, options) => persistBoolean(HIDE_THREAD_TIMELINE_STORAGE_KEY, value, options),
+ false
+)
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 346f768d756..0b8462a33f0 100644
--- a/apps/desktop/src/store/tool-view.ts
+++ b/apps/desktop/src/store/tool-view.ts
@@ -27,10 +27,16 @@ export const $toolDisclosureStates = atom<ToolDisclosureStates>(loadToolDisclosu
const disclosureOpenCache = new Map<string, ReadableAtom<boolean | undefined>>()
const anyDisclosureOpenCache = new Map<string, ReadableAtom<boolean>>()
-persistStore($toolViewModePref, (mode, options) =>
- persistBoolean(TOOL_VIEW_TECHNICAL_STORAGE_KEY, mode === 'technical', options)
+persistStore(
+ $toolViewModePref,
+ (mode, options) => persistBoolean(TOOL_VIEW_TECHNICAL_STORAGE_KEY, mode === 'technical', options),
+ 'product'
+)
+persistStore(
+ $hideCodeDiffsPref,
+ (hidden, options) => persistBoolean(HIDE_CODE_DIFFS_STORAGE_KEY, hidden, options),
+ false
)
-persistStore($hideCodeDiffsPref, (hidden, options) => persistBoolean(HIDE_CODE_DIFFS_STORAGE_KEY, hidden, options))
$toolDisclosureStates.subscribe(persistToolDisclosureStates)
export function setToolViewMode(mode: ToolViewMode) {
diff --git a/apps/desktop/src/store/translucency.ts b/apps/desktop/src/store/translucency.ts
index 88aeaf40cb8..a642d1b0d0e 100644
--- a/apps/desktop/src/store/translucency.ts
+++ b/apps/desktop/src/store/translucency.ts
@@ -46,7 +46,7 @@ import {
import { atom, computed } from 'nanostores'
import { isBrowserHostedDesktop, isMacPlatform, isWindowsPlatform } from '@/lib/platform'
-import { readJson, writeJson } from '@/lib/storage'
+import { readJson, readKey, writeJson, writeKey } from '@/lib/storage'
export {
defaultTranslucencyValues,
@@ -96,6 +96,19 @@ export const GLASS_IS_WINDOWS = GLASS_SUPPORTED && !isMacPlatform()
const KEY = 'hermes.desktop.translucency.v2'
const LEGACY_KEY = 'hermes.desktop.translucency.v1'
+// An older build persisted the book at every load, so a stored default is no
+// choice: keep it provisional, or a browser upgraded from that build would
+// seed it into the machine's shared store over native's tuned glass (#145536).
+if (typeof window !== 'undefined') {
+ const stored = readKey(KEY)
+
+ const book = JSON.stringify(normalizeBook(readJson<unknown>(KEY), true))
+
+ if (stored !== null && [true, false].some(glass => book === JSON.stringify(normalizeBook(null, glass)))) {
+ writeKey(KEY, stored, { isDefault: true, provisional: true })
+ }
+}
+
const read = (): TranslucencyBook =>
normalizeBook(readJson<unknown>(KEY) ?? readJson<unknown>(LEGACY_KEY), GLASS_SUPPORTED)