Skip to content

The agent that grows with you

fix(desktop): concurrent edits from a stale view keep other clients' changes

Teknium74885f997bec
diff --git a/apps/desktop/src/lib/ui-preferences/merge.ts b/apps/desktop/src/lib/ui-preferences/merge.ts
index 73daf03eb63..45d52ab0199 100644
--- a/apps/desktop/src/lib/ui-preferences/merge.ts
+++ b/apps/desktop/src/lib/ui-preferences/merge.ts
@@ -23,11 +23,24 @@ function parse(raw: null | string): Json | null | undefined {
const same = (left: unknown, right: unknown) => JSON.stringify(left) === JSON.stringify(right)
+// A three-way merge: each side's removals and additions both apply, so an
+// entry another client removed stays removed. The order is this window's,
+// with the store's additions appended, unless only the store reordered.
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))]
+ const reordered = (list: unknown[]) =>
+ !same(
+ list.filter(item => has(base, item)),
+ base.filter(item => has(list, item))
+ )
+
+ const [first, second] = reordered(theirs) && !reordered(mine) ? [theirs, mine] : [mine, theirs]
+ const removed = base.filter(item => !has(theirs, item) || !has(mine, item))
+
+ const merged = first.filter(item => !has(removed, item))
+
+ return [...merged, ...second.filter(item => !has(merged, item) && !has(base, item))]
}
function rebaseRecord(
diff --git a/apps/desktop/src/lib/ui-preferences/outbox.ts b/apps/desktop/src/lib/ui-preferences/outbox.ts
index 11a6d73ed6e..f94935b2681 100644
--- a/apps/desktop/src/lib/ui-preferences/outbox.ts
+++ b/apps/desktop/src/lib/ui-preferences/outbox.ts
@@ -6,7 +6,9 @@
// unsent changes. A tab that closed with changes unsent (inside the debounce,
// offline, during a lock retry) leaves its outbox behind: the next tab of this
// origin adopts it once its owner is gone, so the change is still written and
-// the key is removed (#145536 re-review). Not shared keys themselves.
+// the key is removed (#145536 re-review). Each change keeps the value it was
+// made on (`bases`), so whoever sends it rebases it onto the store's current
+// value instead of writing it whole. Not shared keys themselves.
import { isSharedPreferenceKey } from './keys'
const OUTBOX_PREFIX = 'hermes:ui-preferences:outbox:'
@@ -18,17 +20,30 @@ export const OUTBOX_HEARTBEAT_MS = 10_000
const OUTBOX_DEAD_MS = 90_000
interface OutboxDoc {
+ /** The tab taking this outbox over: it re-reads the mark before sending,
+ * and the owner, seeing it, stops sending (one sender per change). */
+ adopter?: string
+ bases: Record<string, null | string>
beat: number
closed?: boolean
values: Record<string, null | string>
}
+/** Unsent changes and, per change, the value it was made on. */
+export interface Outbox {
+ bases: Map<string, null | string>
+ values: Map<string, null | string>
+}
+
let outboxKey: null | string = null
// Set once the page is going away (pagehide), cleared if it comes back from the
// back/forward cache: every save from then on marks the outbox closed, since
// pagehide and visibilitychange fire in either order and a send in flight may
// still settle.
let pageClosing = false
+// True while this tab's last save stored unsent changes: only then does a
+// missing outbox mean another tab took it (not full or blocked storage).
+let outboxHeld = false
function readRaw(key: string): null | string {
try {
@@ -59,15 +74,20 @@ function parseOutbox(raw: null | string): null | OutboxDoc {
return null
}
- return {
- beat: typeof doc.beat === 'number' ? doc.beat : 0,
- closed: doc.closed === true,
- values: Object.fromEntries(
- Object.entries(values).filter(
+ const entries = (record: unknown) =>
+ Object.fromEntries(
+ Object.entries(record && typeof record === 'object' ? record : {}).filter(
(entry): entry is [string, null | string] =>
isSharedPreferenceKey(entry[0]) && (entry[1] === null || typeof entry[1] === 'string')
)
)
+
+ return {
+ ...(typeof doc.adopter === 'string' && { adopter: doc.adopter }),
+ bases: entries(doc.bases),
+ beat: typeof doc.beat === 'number' ? doc.beat : 0,
+ closed: doc.closed === true,
+ values: entries(values)
}
} catch {
return null
@@ -92,13 +112,37 @@ function outboxKeys(): string[] {
return keys
}
+/** Claim another load's outbox and remove it: mark this tab as adopter, then
+ * re-read. Null when it is gone or another tab (or its owner, re-saving)
+ * wrote after the mark: that one sends it, not this tab. */
+function takeOutbox(key: string): null | OutboxDoc {
+ const doc = parseOutbox(readRaw(key))
+
+ if (!doc) {
+ writeRaw(key, null)
+
+ return null
+ }
+
+ writeRaw(key, JSON.stringify({ ...doc, adopter: outboxKey }))
+ const claimed = parseOutbox(readRaw(key))
+
+ if (claimed?.adopter !== outboxKey) {
+ return null
+ }
+
+ writeRaw(key, null)
+
+ return claimed
+}
+
/**
* Take over the outboxes of this origin's tabs that are gone, oldest first so
* a later change to a key wins, and remove them. An entry is taken only while
* this origin's cache still holds its value: anything since (an edit here, a
* newer store value a live tab adopted) superseded it.
*/
-export function adoptOrphanedOutboxes(): Map<string, null | string> {
+export function adoptOrphanedOutboxes(): Outbox {
const now = Date.now()
const own = outboxKey
@@ -108,21 +152,44 @@ export function adoptOrphanedOutboxes(): Map<string, null | string> {
.filter(({ doc }) => !doc || doc.closed || now - doc.beat > OUTBOX_DEAD_MS)
.sort((left, right) => (left.doc?.beat ?? 0) - (right.doc?.beat ?? 0))
- const adopted = new Map<string, null | string>()
+ const adopted: Outbox = { bases: new Map(), values: new Map() }
+
+ for (const { key } of orphans) {
+ const doc = takeOutbox(key)
- for (const { doc, key } of orphans) {
for (const [name, value] of Object.entries(doc?.values ?? {})) {
if (readRaw(name) === value) {
- adopted.set(name, value)
+ mergeEntry(adopted, doc as OutboxDoc, name)
}
}
-
- writeRaw(key, null)
}
return adopted
}
+function mergeEntry(into: Outbox, doc: OutboxDoc, name: string) {
+ into.values.set(name, doc.values[name] ?? null)
+
+ if (Object.hasOwn(doc.bases, name)) {
+ into.bases.set(name, doc.bases[name] ?? null)
+ } else {
+ into.bases.delete(name)
+ }
+}
+
+/** True when this tab's unsent changes were taken over by another tab (its
+ * outbox is gone or carries another adopter): it must not send them. */
+export function outboxTakenOver(): boolean {
+ const doc = parseOutbox(readRaw(claimOutboxKey()))
+
+ const taken = doc ? doc.adopter !== undefined && doc.adopter !== outboxKey : outboxHeld
+
+ // Reported once: changes saved after this are this tab's again.
+ outboxHeld = outboxHeld && !taken
+
+ return taken
+}
+
/** Keys another tab of this origin changed and has not stored yet: its edit
* is newer than the store's value, so no tab adopts the older value over it
* in the cache they share (and the orphan stays adoptable). */
@@ -155,28 +222,42 @@ export function claimOutboxKey(): string {
}
outboxKey = `${OUTBOX_PREFIX}${id}`
- const carried = previous ? parseOutbox(readRaw(`${OUTBOX_PREFIX}${previous}`)) : null
+ const carried = previous ? takeOutbox(`${OUTBOX_PREFIX}${previous}`) : null
+ const outbox = adoptOrphanedOutboxes()
- if (previous) {
- writeRaw(`${OUTBOX_PREFIX}${previous}`, null)
+ for (const name of Object.keys(carried?.values ?? {})) {
+ mergeEntry(outbox, carried as OutboxDoc, name)
}
- saveOutbox(new Map([...adoptOrphanedOutboxes(), ...Object.entries(carried?.values ?? {})]))
+ saveOutbox(outbox.values, { bases: outbox.bases })
return outboxKey
}
-export function readOutbox(): Map<string, null | string> {
- return new Map(Object.entries(parseOutbox(readRaw(claimOutboxKey()))?.values ?? {}))
+export function readOutbox(): Outbox {
+ const doc = parseOutbox(readRaw(claimOutboxKey()))
+
+ return { bases: new Map(Object.entries(doc?.bases ?? {})), values: new Map(Object.entries(doc?.values ?? {})) }
}
-/** Store this tab's unsent changes with a fresh liveness stamp; `closed` once
- * the page is going away, so the next tab need not wait for the stamp to age. */
-export function saveOutbox(pending: ReadonlyMap<string, null | string>, { closed = pageClosing } = {}) {
+/** Store this tab's unsent changes (and the value each was made on) with a
+ * fresh liveness stamp; `closed` once the page is going away, so the next
+ * tab need not wait for the stamp to age. */
+export function saveOutbox(
+ pending: ReadonlyMap<string, null | string>,
+ { bases = new Map(), closed = pageClosing }: { bases?: ReadonlyMap<string, null | string>; closed?: boolean } = {}
+) {
const key = claimOutboxKey()
- const doc: OutboxDoc = { beat: Date.now(), ...(closed && { closed }), values: Object.fromEntries(pending) }
+
+ const doc: OutboxDoc = {
+ bases: Object.fromEntries([...bases].filter(([name]) => pending.has(name))),
+ beat: Date.now(),
+ ...(closed && { closed }),
+ values: Object.fromEntries(pending)
+ }
writeRaw(key, pending.size === 0 ? null : JSON.stringify(doc))
+ outboxHeld = pending.size > 0 && readRaw(key) !== null
}
/** Heartbeat and page-lifecycle hooks for one running sync. `touch()` after
diff --git a/apps/desktop/src/lib/ui-preferences/sync-concurrent.test.ts b/apps/desktop/src/lib/ui-preferences/sync-concurrent.test.ts
new file mode 100644
index 00000000000..1d72b4fc856
--- /dev/null
+++ b/apps/desktop/src/lib/ui-preferences/sync-concurrent.test.ts
@@ -0,0 +1,159 @@
+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 type { UiPreferencesBridge } from './sync'
+
+// Edits made from a stale view while another client changed the store
+// (#145536 re-review round 3), against the real native writer on a real file:
+// a removal elsewhere, an edit carried over a reload or a takeover, a tab
+// whose unsent edit another tab already took over.
+const MODE = 'hermes-desktop-mode-v1'
+const FAVORITES = 'hermes.desktop.favorite-models'
+
+const dirs: string[] = []
+const stops: (() => void)[] = []
+const listeners = new Set<(snapshot: UiPreferencesSnapshot) => void>()
+const tick = (ms = 400) => new Promise(resolve => setTimeout(resolve, ms))
+
+function storeFile(): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-ui-concurrent-'))
+ dirs.push(dir)
+
+ return path.join(dir, 'ui-preferences.json')
+}
+
+const stored = (file: string, key: string) => readUiPreferences(file).values[key] ?? null
+const favorites = (file: string) => JSON.parse(stored(file, FAVORITES) ?? '[]') as string[]
+
+/** Every successful write is pushed to every other window, as native does. */
+function bridgeFor(file: string, net: { online: boolean }): UiPreferencesBridge {
+ const down = () => Promise.reject(new Error('fetch failed'))
+ let own: ((snapshot: UiPreferencesSnapshot) => void) | null = null
+
+ return {
+ read: async () => (net.online ? readUiPreferences(file) : down()),
+ write: async payload => {
+ if (!net.online) {
+ return down()
+ }
+
+ const snapshot = await writeUiPreferences(file, parseUiPreferencesWrite(payload))
+ listeners.forEach(callback => callback !== own && callback(snapshot))
+
+ return snapshot
+ },
+ onChanged: callback => {
+ own = callback
+ listeners.add(callback)
+
+ return () => listeners.delete(callback)
+ }
+ }
+}
+
+/** One page load as entry.ts/boot.ts + main.tsx run it. */
+async function pageLoad(file: string, { net = { online: true }, favoritesStore = true } = {}) {
+ vi.resetModules()
+ const sync = await import('./sync')
+ sync.captureOwnPreferences()
+ sync.hydrateFromSnapshot(net.online && fs.existsSync(file) ? readUiPreferences(file) : null)
+ const store = favoritesStore ? await import('@/store/favorite-models') : null
+ const storage = await import('@/lib/storage')
+ stops.push(sync.startUiPreferencesSync(bridgeFor(file, net)))
+ await tick()
+
+ return { storage, store }
+}
+
+const closeTabs = () => stops.splice(0).forEach(stop => stop())
+
+afterEach(() => {
+ closeTabs()
+ listeners.clear()
+ vi.useRealTimers()
+ window.localStorage.clear()
+ window.sessionStorage.clear()
+
+ for (const dir of dirs.splice(0)) {
+ fs.rmSync(dir, { force: true, recursive: true })
+ }
+})
+
+it('a favorite another client removed stays removed when a tab that still lists it stars another', async () => {
+ const file = storeFile()
+ await writeUiPreferences(file, { values: { [FAVORITES]: JSON.stringify(['p::X', 'p::Y']) } })
+ window.localStorage.setItem(FAVORITES, JSON.stringify(['p::X', 'p::Y']))
+ const { store } = await pageLoad(file)
+
+ // Native unfavorites X; the push lands here, the favorites atom keeps its read.
+ const snapshot = await writeUiPreferences(file, { values: { [FAVORITES]: JSON.stringify(['p::Y']) } })
+ listeners.forEach(callback => callback(snapshot))
+ await tick(50)
+ store?.toggleFavoriteModel('p', 'W')
+ await tick()
+
+ expect(favorites(file)).toEqual(['p::Y', 'p::W'])
+})
+
+it('an offline star carried over a reload or a takeover joins the favorites native added meanwhile', async () => {
+ for (const carry of ['reload', 'takeover'] as const) {
+ const file = storeFile()
+ await writeUiPreferences(file, { values: { [FAVORITES]: JSON.stringify(['p::A']) } })
+ window.localStorage.setItem(FAVORITES, JSON.stringify(['p::A']))
+ await pageLoad(file)
+ closeTabs()
+
+ const { store } = await pageLoad(file, { net: { online: false } })
+ store?.toggleFavoriteModel('p', 'W')
+ await tick()
+
+ if (carry === 'takeover') {
+ window.dispatchEvent(new PageTransitionEvent('pagehide'))
+ window.sessionStorage.clear()
+ }
+
+ closeTabs()
+ await writeUiPreferences(file, { values: { [FAVORITES]: JSON.stringify(['p::A', 'p::N']) } })
+ await pageLoad(file)
+
+ expect([carry, favorites(file).sort()]).toEqual([carry, ['p::A', 'p::N', 'p::W']])
+ closeTabs()
+ window.localStorage.clear()
+ window.sessionStorage.clear()
+ }
+}, 15_000)
+
+it('a frozen tab whose unsent edit another tab took over never re-sends it over a newer choice', async () => {
+ const file = storeFile()
+ await writeUiPreferences(file, { values: { [MODE]: 'light' } })
+ window.localStorage.setItem(MODE, 'light')
+ const frozenNet = { online: true }
+ const frozen = await pageLoad(file, { favoritesStore: false, net: frozenNet })
+ frozenNet.online = false
+ frozen.storage.writeKey(MODE, 'dark')
+ await tick()
+
+ // That tab stops beating for two minutes; a new tab adopts its edit, then
+ // the user picks again there.
+ vi.useFakeTimers({ now: Date.now() + 120_000, toFake: ['Date'] })
+ window.sessionStorage.clear()
+ const fresh = await pageLoad(file, { favoritesStore: false })
+ fresh.storage.writeKey(MODE, 'system')
+ await tick()
+ vi.useRealTimers()
+
+ frozenNet.online = true // the frozen tab wakes; its retry fires
+ await tick(6000)
+
+ expect(stored(file, MODE)).toBe('system')
+}, 15_000)
diff --git a/apps/desktop/src/lib/ui-preferences/sync.ts b/apps/desktop/src/lib/ui-preferences/sync.ts
index 5d0da96aef1..bde14ae3320 100644
--- a/apps/desktop/src/lib/ui-preferences/sync.ts
+++ b/apps/desktop/src/lib/ui-preferences/sync.ts
@@ -3,7 +3,7 @@ import { markProvisionalPreference, onPersistenceEvent, previousValueOf, provisi
import { isSharedPreferenceKey } from './keys'
import { rebaseWrite } from './merge'
-import { adoptOrphanedOutboxes, readOutbox, saveOutbox, siblingPendingKeys, watchOutbox } from './outbox'
+import { adoptOrphanedOutboxes, outboxTakenOver, readOutbox, saveOutbox, siblingPendingKeys, watchOutbox } from './outbox'
export type { UiPreferencesSnapshot, UiPreferencesWrite }
@@ -139,7 +139,7 @@ export function hydrateFromSnapshot(snapshot: null | undefined | UiPreferencesSn
return
}
- const outbox = new Set([...readOutbox().keys(), ...siblingPendingKeys()])
+ const outbox = new Set([...readOutbox().values.keys(), ...siblingPendingKeys()])
const prune = hasJoined(snapshot)
for (const key of new Set([...localSharedKeys(), ...Object.keys(snapshot.values)])) {
@@ -179,13 +179,14 @@ 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.
+ // Unsent changes and the cached value each was made on (kept in the outbox,
+ // so a change carried over a reload or taken over from a closed tab is
+ // rebased too), and what this window's stores last saw per key (read at
+ // load, read again, or written): a store that never re-reads must not undo
+ // the entries a newer value brought.
+ const { bases: pendingBase, values: pending } = readOutbox()
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>()
@@ -228,10 +229,8 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
// 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)
+ if (rebasePending(key, value)) {
+ save()
} else if (!pending.has(key) && !siblings.has(key) && !(refused.has(key) && refused.get(key) === readRaw(key))) {
adopt(key, value, prune, live)
}
@@ -242,6 +241,44 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
}
}
+ function rebasePending(key: string, current: null | string): boolean {
+ if (!pending.has(key) || !pendingBase.has(key) || pendingBase.get(key) === current) {
+ return false
+ }
+
+ pending.set(key, rebaseLocal(key, pendingBase.get(key) ?? null, current, pending.get(key) ?? null))
+ pendingBase.set(key, current)
+
+ return true
+ }
+
+ // Another tab took this tab's unsent changes over (this one was frozen past
+ // the liveness bound) and may have sent newer ones since: drop them here,
+ // never send or save them again, and follow the store instead.
+ const takenOver = (): boolean => {
+ if (pending.size === 0 || !outboxTakenOver()) {
+ return false
+ }
+
+ pending.clear()
+ pendingBase.clear()
+
+ if (ready && !stopped) {
+ void bridge.read().then(
+ snapshot => !stopped && apply(snapshot, { live: true }),
+ () => undefined
+ )
+ }
+
+ return true
+ }
+
+ const save = (options: { closed?: boolean } = {}) => {
+ if (!takenOver()) {
+ saveOutbox(pending, { bases: pendingBase, ...options })
+ }
+ }
+
let writing = false
let writeDelay = RETRY_DELAY_MS
@@ -256,7 +293,7 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
const flush = async () => {
flushTimer = null
- if (pending.size === 0) {
+ if (takenOver() || pending.size === 0) {
return
}
@@ -298,7 +335,7 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
}
}
- saveOutbox(pending)
+ save()
}
const stopListening = onPersistenceEvent(event => {
@@ -324,6 +361,7 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
return
}
+ takenOver()
const current = previousValueOf(event) ?? null
const value = rebaseLocal(event.key, base, current, event.value)
@@ -342,7 +380,7 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
const outbox = watchOutbox({
hasPending: () => pending.size > 0 && !stopped,
onLeave: () => {
- saveOutbox(pending)
+ save()
if (flushTimer !== null) {
clearTimeout(flushTimer)
@@ -354,14 +392,30 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
}
},
onOrphans: () => {
- adoptOrphanedOutboxes().forEach((value, key) => pending.has(key) || pending.set(key, value))
+ takenOver()
+ const adopted = adoptOrphanedOutboxes()
+
+ for (const [key, value] of adopted.values) {
+ if (!pending.has(key)) {
+ pending.set(key, value)
+
+ if (adopted.bases.has(key)) {
+ pendingBase.set(key, adopted.bases.get(key) ?? null)
+ }
+
+ if (ready && known.has(key)) {
+ rebasePending(key, known.get(key) ?? null)
+ }
+ }
+ }
+
store()
},
- onReturn: () => saveOutbox(pending)
+ onReturn: () => save()
})
function store() {
- saveOutbox(pending)
+ save()
outbox.touch()
schedule(FLUSH_DELAY_MS)
}
@@ -470,7 +524,7 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
stopChanges()
outbox.stop()
// Nothing here sends it any more: the next tab adopts what is unsent.
- saveOutbox(pending, { closed: true })
+ save({ closed: true })
if (flushTimer !== null) {
clearTimeout(flushTimer)