fix(desktop): hydrate shared preferences before any store module evaluates

Review finding 1 (#145536): boot.ts was imported first by main.tsx, but the
production chunk graph evaluates every shared chunk (where most persisted
stores live) before the entry body, and dev ESM evaluates sibling imports
before a top-level await settles. Stores read stale localStorage, and the
next write replaced the host's values (favourites [A,B] became [C]).

The renderer entry is now src/entry.ts: it hydrates through bootRenderer()
(native: the preload's synchronous snapshot; Webapp: /api/ui-preferences,
bounded at 1.5 s, local cache on failure) and only then dynamically imports
./main, so no store module can evaluate first in either host.
This commit is contained in:
Teknium
2026-10-27 08:56:40 -07:00
parent a21e42ae5c
commit 3d8dafc729
5 changed files with 76 additions and 10 deletions

View File

@@ -45,6 +45,6 @@
</head>
<body>
<div id="root" class="scrollbar-dt"></div>
<script type="module" src="/src/main.tsx"></script>
<script type="module" src="/src/entry.ts"></script>
</body>
</html>

View File

@@ -0,0 +1,8 @@
// Renderer entry. The whole app (every store that reads localStorage when its
// module evaluates) enters through the dynamic import below, so nothing can
// read a shared preference before this machine's store hydrated it (#145213),
// in the production chunk graph and in dev's unbundled ESM alike. Keep this
// file's static imports free of app modules.
import { bootRenderer } from './lib/ui-preferences/boot'
void bootRenderer(() => import('./main'))

View File

@@ -0,0 +1,51 @@
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { afterEach, expect, it } from 'vitest'
import { parseUiPreferencesWrite, readUiPreferences, writeUiPreferences } from '../../../electron/ui-preferences'
import { bootRenderer } from './boot'
import { startUiPreferencesSync, type UiPreferencesBridge } from './sync'
const FAVORITES = 'hermes.desktop.favorite-models'
const dirs: string[] = []
const tick = (ms = 400) => new Promise(resolve => setTimeout(resolve, ms))
afterEach(() => {
window.localStorage.clear()
delete window.hermesDesktop
for (const dir of dirs.splice(0)) {
fs.rmSync(dir, { force: true, recursive: true })
}
})
// The production chunk graph evaluates every shared chunk (where most stores
// live) before the entry body, so hydration must gate the app's module graph
// itself: a store that read localStorage first kept a stale value, and its
// next write replaced the host's favourites (#145536 review, finding 1).
it('no store module evaluates before the machine store hydrated, so its next write keeps the host’s values', async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-ui-boot-'))
dirs.push(dir)
const file = path.join(dir, 'ui-preferences.json')
await writeUiPreferences(file, { values: { [FAVORITES]: '["host::A","host::B"]' } })
const bridge: UiPreferencesBridge = {
snapshot: readUiPreferences(file),
read: async () => readUiPreferences(file),
write: payload => writeUiPreferences(file, parseUiPreferencesWrite(payload))
}
window.hermesDesktop = { uiPreferences: bridge } as unknown as typeof window.hermesDesktop
const favorites = await bootRenderer(() => import('@/store/favorite-models'))
const stop = startUiPreferencesSync(bridge)
await tick()
favorites.toggleFavoriteModel('mine', 'C')
await tick()
stop()
expect(JSON.parse(readUiPreferences(file).values[FAVORITES])).toEqual(['host::A', 'host::B', 'mine::C'])
})

View File

@@ -1,10 +1,13 @@
// Side-effect module, imported first by main.tsx, so the localStorage cache
// matches this machine's shared preferences before any store module reads it
// (no default flash, and no plain-atom store seeded from a stale cache).
// Runs BEFORE the app's module graph (see src/entry.ts): the localStorage cache
// must match this machine's shared preferences before any store module reads
// it, or a plain-atom store keeps a stale value and its next write clobbers the
// host's. A static import order cannot promise that (a bundler hoists shared
// chunks above the entry body, and ESM evaluates sibling imports before a
// top-level await settles), so the app is loaded only after `bootRenderer`
// hydrated. Keep this module's imports free of stores.
// Native Desktop's preload hands the snapshot over synchronously. A browser
// asks the server that serves it, bounded so an unreachable host never holds
// the first paint for long: the top-level await delays the modules main.tsx
// imports after this one.
// the first paint for long (then it boots on its local cache).
import { browserApi, browserBootstrap } from '@/lib/browser-transport'
import { hydrateFromSnapshot, type UiPreferencesSnapshot } from './sync'
@@ -28,6 +31,11 @@ async function browserSnapshot(): Promise<null | UiPreferencesSnapshot> {
return Promise.race([read, late])
}
if (typeof window !== 'undefined') {
hydrateFromSnapshot(window.hermesDesktop?.uiPreferences?.snapshot ?? (await browserSnapshot()))
/** Hydrate this window's shared preferences, then load the app. */
export async function bootRenderer<T>(loadApp: () => Promise<T>): Promise<T> {
if (typeof window !== 'undefined') {
hydrateFromSnapshot(window.hermesDesktop?.uiPreferences?.snapshot ?? (await browserSnapshot()))
}
return loadApp()
}

View File

@@ -1,6 +1,5 @@
// Loaded by src/entry.ts once the machine's shared UI preferences hydrated.
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'