The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): windows import before they prune, rejoin a replaced store, and keep per-tab outboxes
Teknium0d2565636c42
diff --git a/apps/desktop/src/lib/ui-preferences/sync-store.test.ts b/apps/desktop/src/lib/ui-preferences/sync-store.test.tsnew file mode 100644index 00000000000..4fb338c402c--- /dev/null+++ b/apps/desktop/src/lib/ui-preferences/sync-store.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 { hydrateFromSnapshot, startUiPreferencesSync, type UiPreferencesBridge } from './sync'++// The renderer sync against the real native writer on a real file (#145536 review).+const DENSITY = 'hermes.desktop.sessionListDensity'+const MODE = 'hermes-desktop-mode-v1'+const THEME = 'hermes-desktop-theme-v2'+const USER_THEMES = 'hermes-desktop-user-themes-v1'+const KEYBINDS = 'hermes.desktop.keybinds'+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-sync-'))+ 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)) }+}++afterEach(() => {+ window.localStorage.clear()+ window.sessionStorage.clear()++ for (const dir of dirs.splice(0)) {+ fs.rmSync(dir, { force: true, recursive: true })+ }+})++it('a store a fresh client created never removes another client’s values: it imports them', async () => {+ const file = storeFile()+ // A fresh browser (no shared keys yet) makes first contact.+ let stop = startUiPreferencesSync(realBridge(file).bridge)+ await tick()+ stop()++ // Native Desktop, another origin, launches with its own preferences.+ window.localStorage.clear()+ const mine = { [KEYBINDS]: '{"newChat":"mod+n"}', [THEME]: 'nous', [USER_THEMES]: '{"mine":{"name":"Mine"}}' }+ Object.entries(mine).forEach(([key, value]) => window.localStorage.setItem(key, value))+ hydrateFromSnapshot(readUiPreferences(file))+ stop = startUiPreferencesSync(realBridge(file).bridge)+ await tick()+ stop()++ expect(Object.fromEntries(Object.keys(mine).map(key => [key, window.localStorage.getItem(key)]))).toEqual(mine)+ expect(readUiPreferences(file).values).toEqual(mine)+})++it('a corrupt store is kept aside and open windows follow its replacement, re-importing what it lost', async () => {+ const file = storeFile()+ await writeUiPreferences(file, { values: { [MODE]: 'dark' } })++ for (let n = 0; n < 5; n += 1) {+ await writeUiPreferences(file, { values: { [DENSITY]: `d${n}` } })+ }++ const { bridge, push } = realBridge(file)+ const stop = startUiPreferencesSync(bridge)+ await tick()+ expect(window.localStorage.getItem(DENSITY)).toBe('d4')++ const torn = '{"version":1,"revision":6,"val'+ fs.writeFileSync(file, torn)+ await writeUiPreferences(file, { values: { [DENSITY]: 'compact' } }) // e.g. the Webapp's next write+ push()+ await tick()+ stop()++ const backups = fs.readdirSync(path.dirname(file)).filter(name => name.startsWith('ui-preferences.json.corrupt-'))++ expect(window.localStorage.getItem(DENSITY)).toBe('compact')+ expect(readUiPreferences(file).values).toEqual({ [DENSITY]: 'compact', [MODE]: 'dark' })+ expect(backups.map(name => fs.readFileSync(path.join(path.dirname(file), name), 'utf8'))).toEqual([torn])+})++it('same-origin tabs keep each other’s unsent changes', async () => {+ const file = storeFile()+ await writeUiPreferences(file, { values: { [DENSITY]: 'compact', [MODE]: 'light' } })+ const offline: UiPreferencesBridge = {+ read: () => new Promise(() => undefined),+ write: () => new Promise(() => undefined)+ }++ // Two tabs of one origin (one localStorage, a sessionStorage each), offline.+ vi.resetModules()+ const tabA = { storage: await import('../storage'), sync: await import('./sync') }+ const stopA = tabA.sync.startUiPreferencesSync(offline)+ const sessionA = Object.fromEntries(Object.entries(window.sessionStorage))+ window.sessionStorage.clear()+ vi.resetModules()+ const tabB = { storage: await import('../storage'), sync: await import('./sync') }+ const stopB = tabB.sync.startUiPreferencesSync(offline)++ tabA.storage.writeKey(DENSITY, 'detailed')+ tabB.storage.writeKey(MODE, 'dark')+ stopA()+ stopB()++ // Tab A reloads once the store is reachable again.+ window.sessionStorage.clear()+ Object.entries(sessionA).forEach(([key, value]) => window.sessionStorage.setItem(key, value))+ vi.resetModules()+ const reloadedA = await import('./sync')+ const stop = reloadedA.startUiPreferencesSync(realBridge(file).bridge)+ await tick()+ stop()++ expect(readUiPreferences(file).values[DENSITY]).toBe('detailed')+})diff --git a/apps/desktop/src/lib/ui-preferences/sync.test.ts b/apps/desktop/src/lib/ui-preferences/sync.test.tsindex f152fb10e98..49790be21f8 100644--- a/apps/desktop/src/lib/ui-preferences/sync.test.ts+++ b/apps/desktop/src/lib/ui-preferences/sync.test.ts@@ -6,9 +6,12 @@ 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.+// merge, null deletes, `seed` only adds the keys the store lacks.function memoryStore(initial: null | Record<string, string>) {- let doc: null | UiPreferencesSnapshot = initial ? { exists: true, revision: 1, values: { ...initial } } : null+ let doc: null | UiPreferencesSnapshot = initial+ ? { exists: true, generation: 'g1', 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: {} }@@ -18,21 +21,21 @@ function memoryStore(initial: null | Record<string, string>) {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) {+ if (payload.seed) {+ if (value !== null && !(key in values)) {+ values[key] = value+ }+ } else if (value === null) {delete values[key]} else {values[key] = value}}- doc = { exists: true, revision: (doc?.revision ?? 0) + 1, values }+ doc = { exists: true, generation: doc?.generation ?? 'g1', revision: (doc?.revision ?? 0) + 1, values }return snapshot()},@@ -44,7 +47,7 @@ function memoryStore(initial: null | Record<string, string>) {}const external = (values: Record<string, string>) => {- doc = { exists: true, revision: (doc?.revision ?? 0) + 1, values }+ doc = { exists: true, generation: doc?.generation ?? 'g1', revision: (doc?.revision ?? 0) + 1, values }listeners.forEach(listener => listener(snapshot()))}@@ -80,20 +83,18 @@ describe('machine UI preferences sync', () => {expect(store.snapshot().values).toEqual({ [DENSITY]: 'detailed' })})- it('adopts an existing store over this window’s cache instead of overwriting it', async () => {+ it('adopts an existing store’s values and imports only the keys it lacks', 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(store.writes).toEqual([{ seed: true, values: { [DENSITY]: 'detailed', [MODE]: 'light' } }])+ expect(store.snapshot().values).toEqual({ [DENSITY]: 'detailed', [MODE]: 'dark' })expect(window.localStorage.getItem(MODE)).toBe('dark')- expect(window.localStorage.getItem(DENSITY)).toBeNull()- expect($density.get()).toBe('compact')+ expect(window.localStorage.getItem(DENSITY)).toBe('detailed')})it('merges local changes per key and follows changes made elsewhere live', async () => {diff --git a/apps/desktop/src/lib/ui-preferences/sync.ts b/apps/desktop/src/lib/ui-preferences/sync.tsindex b92b62ec772..6b5daaf1de9 100644--- a/apps/desktop/src/lib/ui-preferences/sync.ts+++ b/apps/desktop/src/lib/ui-preferences/sync.ts@@ -18,11 +18,59 @@ export interface UiPreferencesBridge {const FLUSH_DELAY_MS = 150// Local changes not yet confirmed by the store, kept across reloads: a change// made right before the tab reloads or closes must still win over the older-// store value on the next load, and be written then. Not a shared key itself.-const OUTBOX_KEY = 'hermes:ui-preferences:outbox'+// store value on the next load, and be written then. One outbox PER TAB (its id+// rides in sessionStorage, which survives a reload): same-origin tabs share+// localStorage, and one shared outbox let each tab overwrite the others'+// unsent changes. Not shared keys themselves.+const OUTBOX_PREFIX = 'hermes:ui-preferences:outbox:'+const TAB_KEY = 'hermes:ui-preferences:tab'+// The store generation this origin has joined (imported its own values into).+// 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'const RETRY_DELAY_MS = 5000const MAX_RETRY_DELAY_MS = 60_000+let outboxKey: null | string = null++/** This tab's outbox key, claimed once per page load. The previous load of this+ * tab (same sessionStorage) hands its unsent changes over. */+function claimOutboxKey(): string {+ if (outboxKey) {+ return outboxKey+ }++ const id = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`+ let previous: null | string = null++ try {+ previous = window.sessionStorage.getItem(TAB_KEY)+ window.sessionStorage.setItem(TAB_KEY, id)+ } catch {+ // No sessionStorage: this load's outbox is still its own.+ }++ outboxKey = `${OUTBOX_PREFIX}${id}`++ if (previous) {+ const carried = readRaw(`${OUTBOX_PREFIX}${previous}`)++ if (carried !== null) {+ writeRaw(outboxKey, carried)+ writeRaw(`${OUTBOX_PREFIX}${previous}`, null)+ }+ }++ return outboxKey+}++const generationOf = (snapshot: UiPreferencesSnapshot) => snapshot.generation ?? ''++/** True once this origin imported its values into the snapshot's generation. */+function hasJoined(snapshot: UiPreferencesSnapshot): boolean {+ return snapshot.exists && readRaw(JOINED_KEY) === generationOf(snapshot)+}+function localSharedKeys(): string[] {const keys: string[] = []@@ -72,10 +120,12 @@ function writeRaw(key: string, value: null | string): boolean {}/**- * 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).+ * Make this window's localStorage cache match the store, before any store+ * module has read it (`boot.ts` runs this ahead of the app's module graph).+ * A store that does not exist yet changes nothing (the sync seeds it from this+ * cache instead), and until this origin joined the store's generation a key+ * the store lacks is kept: the store may simply not have it yet. Every change+ * is announced, so anything already listening follows it.*/export function hydrateFromSnapshot(snapshot: null | undefined | UiPreferencesSnapshot): void {if (!snapshot?.exists) {@@ -83,17 +133,26 @@ export function hydrateFromSnapshot(snapshot: null | undefined | UiPreferencesSn}const outbox = readOutbox()+ const prune = hasJoined(snapshot)for (const key of new Set([...localSharedKeys(), ...Object.keys(snapshot.values)])) {- if (isSharedPreferenceKey(key) && !outbox.has(key)) {- writeRaw(key, snapshot.values[key] ?? null)+ 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)}}}function readOutbox(): Map<string, null | string> {try {- const parsed = JSON.parse(readRaw(OUTBOX_KEY) ?? '{}') as unknown+ const parsed = JSON.parse(readRaw(claimOutboxKey()) ?? '{}') as unknownif (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {return new Map()@@ -111,7 +170,7 @@ function readOutbox(): Map<string, null | string> {}function saveOutbox(pending: Map<string, null | string>) {- writeRaw(OUTBOX_KEY, pending.size === 0 ? null : JSON.stringify(Object.fromEntries(pending)))+ writeRaw(claimOutboxKey(), pending.size === 0 ? null : JSON.stringify(Object.fromEntries(pending)))}/** A write the store answered "no" to (HTTP 400 / validation), as opposed to@@ -130,8 +189,9 @@ function announce(key: string, oldValue: null | string, newValue: null | string)/*** 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;+ * - first contact with a store generation (or with no store) imports this+ * origin's existing values (`seed`: only keys the store lacks, so nothing is+ * 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.@@ -146,6 +206,7 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde// Values the store refused, kept in this window until changed again.const refused = new Map<string, null | string>()let revision = -1+ let generation: null | string = nulllet flushTimer: ReturnType<typeof setTimeout> | null = nulllet stopped = false// Nothing is written until first contact: a write that created the store@@ -154,11 +215,15 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | undelet ready = falseconst apply = (snapshot: UiPreferencesSnapshot, { live }: { live: boolean }) => {- if (!snapshot.exists || snapshot.revision < revision) {+ // A replaced store (deleted, or corrupt and kept aside) starts a new+ // generation at a low revision: follow it rather than wait for the count.+ if (!snapshot.exists || (generationOf(snapshot) === generation && snapshot.revision < revision)) {return}revision = snapshot.revision+ generation = generationOf(snapshot)+ const prune = hasJoined(snapshot)for (const key of new Set([...localSharedKeys(), ...Object.keys(snapshot.values), ...known.keys()])) {if (!isSharedPreferenceKey(key)) {@@ -169,7 +234,7 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | undeknown.set(key, value)// A change made here and not yet stored outranks an older store value.- if (pending.has(key) || (refused.has(key) && refused.get(key) === readRaw(key))) {+ if (pending.has(key) || (refused.has(key) && refused.get(key) === readRaw(key)) || (value === null && !prune)) {continue}@@ -179,6 +244,10 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | undeannounce(key, previous, value)}}++ if (!prune && ready) {+ rejoin(snapshot)+ }}let writing = false@@ -254,14 +323,48 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | undeschedule(FLUSH_DELAY_MS)})- const seed = async (snapshot: UiPreferencesSnapshot) => {- if (snapshot.exists) {+ // First contact with a generation: add this origin's values the store lacks.+ const join = async (snapshot: UiPreferencesSnapshot) => {+ if (hasJoined(snapshot)) {return snapshot}const values = Object.fromEntries(localSharedKeys().map(key => [key, readRaw(key)]))+ // Nothing to import: an existing store is joined as it is, and no store is+ // created from nothing.+ const joinedSnapshot = Object.keys(values).length > 0 ? await bridge.write({ seed: true, values }) : snapshot++ if (joinedSnapshot.exists) {+ writeRaw(JOINED_KEY, generationOf(joinedSnapshot))+ }++ return joinedSnapshot+ }++ let joining = false+ let joinRefused = false++ // A live snapshot from a generation this origin has not joined (the store+ // was replaced while this window was open): import, then follow it.+ function rejoin(snapshot: UiPreferencesSnapshot) {+ if (joining || joinRefused || stopped) {+ return+ }++ joining = true+ join(snapshot).then(+ joinedSnapshot => {+ joining = false- return bridge.write({ seed: true, values })+ if (!stopped) {+ apply(joinedSnapshot, { live: true })+ }+ },+ error => {+ joining = false+ joinRefused = isRefusal(error)+ }+ )}let connectTimer: ReturnType<typeof setTimeout> | null = null@@ -271,20 +374,34 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | undeconnectTimer = nullvoid (initial ? Promise.resolve(initial) : bridge.read())- .then(seed)+ .then(join).then(snapshot => {if (stopped) {return}- apply(snapshot, { live: true })ready = true+ apply(snapshot, { live: 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) {+ .catch(error => {+ if (stopped) {+ return+ }++ if (isRefusal(error)) {+ // The store cannot take this origin's import (full): follow it+ // without removing anything here, and try the import on next load.+ joinRefused = true+ ready = true+ void bridge.read().then(+ snapshot => apply(snapshot, { live: true }),+ () => undefined+ )+ schedule(FLUSH_DELAY_MS)+ } else {+ // Unreachable store: this window keeps its cached values and local+ // changes stay pending until first contact succeeds.connectTimer = setTimeout(() => connect(null), connectDelay)connectDelay = Math.min(connectDelay * 2, MAX_RETRY_DELAY_MS)}