Skip to content

The agent that grows with you

fix(desktop): a late first snapshot never lets a stale list replace the shared one

Tekniumc47a2681c53d
diff --git a/apps/desktop/src/lib/storage.ts b/apps/desktop/src/lib/storage.ts
index 5011f9bdbcb..17abc081ec9 100644
--- a/apps/desktop/src/lib/storage.ts
+++ b/apps/desktop/src/lib/storage.ts
@@ -14,6 +14,13 @@ export interface PersistenceEvent {
value: null | string
}
+// A write's or removal's value before it, beside the event rather than in it
+// so every observer keeps the event shape it matches on.
+const previousValues = new WeakMap<PersistenceEvent, null | string>()
+
+/** The stored value a write or removal replaced (undefined for a read). */
+export const previousValueOf = (event: PersistenceEvent) => previousValues.get(event)
+
type PersistenceListener = (event: PersistenceEvent) => void
const persistenceListeners = new Set<PersistenceListener>()
@@ -118,10 +125,9 @@ export function writeKey(
{ isDefault = false, provisional = false }: WriteOptions = {}
) {
const shared = isSharedPreferenceKey(key)
+ const previous = rawRead(key)
if (provisional) {
- const previous = rawRead(key)
-
if (previous === value) {
if (shared && isDefault && value !== null) {
markProvisionalPreference(key, true)
@@ -139,9 +145,16 @@ export function writeKey(
markProvisionalPreference(key, provisional)
}
- emitPersistence({ key, op: value === null ? 'remove' : 'write', value, ...(provisional && { provisional }) })
-}
+ const event: PersistenceEvent = {
+ key,
+ op: value === null ? 'remove' : 'write',
+ value,
+ ...(provisional && { provisional })
+ }
+ previousValues.set(event, previous)
+ emitPersistence(event)
+}
/** Parsed JSON read. Returns null on absence, unavailable storage, OR malformed
* JSON — callers layer their own shape validation on the parsed value. */
diff --git a/apps/desktop/src/lib/ui-preferences/merge.ts b/apps/desktop/src/lib/ui-preferences/merge.ts
new file mode 100644
index 00000000000..73daf03eb63
--- /dev/null
+++ b/apps/desktop/src/lib/ui-preferences/merge.ts
@@ -0,0 +1,83 @@
+// A store that reads its value once (a plain atom such as the favorite models)
+// keeps what it read when a newer machine value lands later (a first snapshot
+// past the boot bound, another window's change), and its next edit carries
+// that stale view whole. Written as is, it would drop every entry the user
+// never touched (#145536 re-review). Rebasing keeps the user's edit and the
+// store's other entries: for a list, the entries the user removed go and the
+// ones they added join; for a record, the properties they changed win.
+type Json = unknown[] | Record<string, unknown>
+
+function parse(raw: null | string): Json | null | undefined {
+ if (raw === null) {
+ return null
+ }
+
+ try {
+ const value = JSON.parse(raw) as unknown
+
+ return value && typeof value === 'object' ? (value as Json) : undefined
+ } catch {
+ return undefined
+ }
+}
+
+const same = (left: unknown, right: unknown) => JSON.stringify(left) === JSON.stringify(right)
+
+function rebaseList(base: unknown[], theirs: unknown[], mine: unknown[]): unknown[] {
+ const has = (list: unknown[], item: unknown) => list.some(entry => same(entry, item))
+ const removed = base.filter(item => !has(mine, item))
+
+ return [...mine, ...theirs.filter(item => !has(mine, item) && !has(removed, item))]
+}
+
+function rebaseRecord(
+ base: Record<string, unknown>,
+ theirs: Record<string, unknown>,
+ mine: Record<string, unknown>
+): Record<string, unknown> {
+ const result = { ...theirs }
+
+ for (const name of new Set([...Object.keys(base), ...Object.keys(mine)])) {
+ if (!same(base[name], mine[name])) {
+ if (Object.hasOwn(mine, name)) {
+ result[name] = mine[name]
+ } else {
+ delete result[name]
+ }
+ }
+ }
+
+ return result
+}
+
+/**
+ * `mine` (this window's write) rebased from `base` (the value this window's
+ * store last saw) onto `theirs` (the store's current value). A scalar, or any
+ * value that is not a list or record on all sides, is the user's choice: mine
+ * wins. An absent key reads as an empty list or record.
+ */
+export function rebaseWrite(base: null | string, theirs: null | string, mine: null | string): null | string {
+ if (theirs === base) {
+ return mine
+ }
+
+ const sides = [parse(base), parse(theirs), parse(mine)]
+ const shape = sides.find(side => side !== null)
+
+ if (
+ !shape ||
+ sides.some(side => side === undefined || (side !== null && Array.isArray(side) !== Array.isArray(shape)))
+ ) {
+ return mine
+ }
+
+ const [b, t, m] = sides.map(side => side ?? (Array.isArray(shape) ? [] : {})) as Json[]
+
+ const rebased = Array.isArray(shape)
+ ? rebaseList(b as unknown[], t as unknown[], m as unknown[])
+ : rebaseRecord(b as Record<string, unknown>, t as Record<string, unknown>, m as Record<string, unknown>)
+
+ const empty = Array.isArray(rebased) ? rebased.length === 0 : Object.keys(rebased).length === 0
+
+ return mine === null && empty ? null : JSON.stringify(rebased)
+}
diff --git a/apps/desktop/src/lib/ui-preferences/sync-handoff.test.ts b/apps/desktop/src/lib/ui-preferences/sync-handoff.test.ts
index fa7daa15089..a943a01724c 100644
--- a/apps/desktop/src/lib/ui-preferences/sync-handoff.test.ts
+++ b/apps/desktop/src/lib/ui-preferences/sync-handoff.test.ts
@@ -177,3 +177,40 @@ it('a crashed tab’s outbox is adopted by the next load once its heartbeat is s
expect(readUiPreferences(file).values[MODE]).toBe('dark')
expect(outboxes()).toEqual([])
})
+
+it('a first snapshot that lands after the app read its cache never drops the store’s favorites on the next star', async () => {
+ const file = storeFile()
+ await writeUiPreferences(file, { values: { [FAVORITES]: JSON.stringify(['host::kept']) } })
+ becomeClient({ [FAVORITES]: JSON.stringify(['mine::old']) })
+
+ await pageLoad(file, { late: true, stores: [() => import('@/store/favorite-models')] })
+ const { toggleFavoriteModel } = await import('@/store/favorite-models')
+ toggleFavoriteModel('mine', 'new')
+ toggleFavoriteModel('mine', 'old')
+ await tick()
+
+ expect(JSON.parse(readUiPreferences(file).values[FAVORITES] ?? '[]')).toEqual(['mine::new', 'host::kept'])
+})
+
+it('a star made before the late snapshot lands joins the store’s favorites instead of replacing them', async () => {
+ const file = storeFile()
+ await writeUiPreferences(file, { values: { [FAVORITES]: JSON.stringify(['host::kept']) } })
+ becomeClient({ [FAVORITES]: JSON.stringify(['host::kept']) })
+ await pageLoad(file)
+ closeTabs()
+
+ await writeUiPreferences(file, { values: { [FAVORITES]: JSON.stringify(['host::kept', 'host::added']) } })
+ vi.resetModules()
+ const sync = await import('./sync')
+ sync.captureOwnPreferences()
+ const { toggleFavoriteModel } = await import('@/store/favorite-models')
+ stops.push(sync.startUiPreferencesSync(bridgeFor(file, { slow: true })))
+ toggleFavoriteModel('mine', 'new')
+ await tick(800)
+
+ expect(JSON.parse(readUiPreferences(file).values[FAVORITES] ?? '[]')).toEqual([
+ 'host::kept',
+ 'mine::new',
+ 'host::added'
+ ])
+})
diff --git a/apps/desktop/src/lib/ui-preferences/sync.ts b/apps/desktop/src/lib/ui-preferences/sync.ts
index b0368ced48d..5d0da96aef1 100644
--- a/apps/desktop/src/lib/ui-preferences/sync.ts
+++ b/apps/desktop/src/lib/ui-preferences/sync.ts
@@ -1,7 +1,8 @@
import type { UiPreferencesSnapshot, UiPreferencesWrite } from '../../../electron/ui-preferences'
-import { markProvisionalPreference, onPersistenceEvent, provisionalPreferenceKeys } from '../storage'
+import { markProvisionalPreference, onPersistenceEvent, previousValueOf, provisionalPreferenceKeys } from '../storage'
import { isSharedPreferenceKey } from './keys'
+import { rebaseWrite } from './merge'
import { adoptOrphanedOutboxes, readOutbox, saveOutbox, siblingPendingKeys, watchOutbox } from './outbox'
export type { UiPreferencesSnapshot, UiPreferencesWrite }
@@ -58,6 +59,18 @@ function adopt(key: string, value: null | string, prune: boolean, live: boolean)
}
}
+/** `mine`, a change made from `base`, rebased onto `current` (see merge.ts);
+ * the cache takes the result, announced, when it differs from `mine`. */
+function rebaseLocal(key: string, base: null | string, current: null | string, mine: null | string): null | string {
+ const rebased = rebaseWrite(base, current, mine)
+
+ if (rebased !== mine && writeRaw(key, rebased)) {
+ announce(key, mine, rebased)
+ }
+
+ return rebased
+}
+
const generationOf = (snapshot: UiPreferencesSnapshot) => snapshot.generation ?? ''
/** True once this origin imported its values into the snapshot's generation. */
@@ -167,6 +180,13 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
const known = new Map<string, null | string>()
const pending = readOutbox()
+ // What this window's stores last saw per key (read at load, read again, or
+ // written), and the cached value each pending change was made on: a store
+ // that never re-reads must not undo the entries a newer value brought.
+ const loaded = new Map(localSharedKeys().map(key => [key, readRaw(key)]))
+ const seen = new Map<string, null | string>()
+ const pendingBase = new Map<string, null | string>()
+ const seenOf = (key: string) => (seen.has(key) ? (seen.get(key) ?? null) : (loaded.get(key) ?? null))
// Values the store refused, kept in this window until changed again.
const refused = new Map<string, null | string>()
let revision = -1
@@ -205,9 +225,14 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
const value = snapshot.values[key] ?? null
known.set(key, value)
- // A change made here, or in a sibling tab, and not yet stored outranks
- // an older store value.
- if (!pending.has(key) && !siblings.has(key) && !(refused.has(key) && refused.get(key) === readRaw(key))) {
+ // A change made here and not yet stored outranks an older store value,
+ // rebased onto it so the store's other entries survive; so does one a
+ // sibling tab has not stored yet.
+ if (pending.has(key) && pendingBase.has(key) && pendingBase.get(key) !== value) {
+ pending.set(key, rebaseLocal(key, pendingBase.get(key) ?? null, value, pending.get(key) ?? null))
+ pendingBase.set(key, value)
+ saveOutbox(pending)
+ } else if (!pending.has(key) && !siblings.has(key) && !(refused.has(key) && refused.get(key) === readRaw(key))) {
adopt(key, value, prune, live)
}
}
@@ -269,6 +294,7 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
for (const [key, value] of batch) {
if (pending.get(key) === value) {
pending.delete(key)
+ pendingBase.delete(key)
}
}
@@ -276,10 +302,19 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
}
const stopListening = onPersistenceEvent(event => {
- if (event.op === 'read' || !isSharedPreferenceKey(event.key)) {
+ if (!isSharedPreferenceKey(event.key)) {
return
}
+ if (event.op === 'read') {
+ seen.set(event.key, event.value)
+
+ return
+ }
+
+ const base = seenOf(event.key)
+ seen.set(event.key, event.value)
+
// A provisional value (storage.ts keeps the mark) never leaves this origin.
if (event.provisional) {
return
@@ -289,8 +324,15 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
return
}
+ const current = previousValueOf(event) ?? null
+ const value = rebaseLocal(event.key, base, current, event.value)
+
+ if (!pendingBase.has(event.key)) {
+ pendingBase.set(event.key, current)
+ }
+
refused.delete(event.key)
- pending.set(event.key, event.value)
+ pending.set(event.key, value)
store()
})