Skip to content

The agent that grows with you

fix(desktop): an edit left unsent in a closed tab is still written

Teknium777f98a2f3d4
diff --git a/apps/desktop/src/lib/ui-preferences/outbox.ts b/apps/desktop/src/lib/ui-preferences/outbox.ts
new file mode 100644
index 00000000000..11a6d73ed6e
--- /dev/null
+++ b/apps/desktop/src/lib/ui-preferences/outbox.ts
@@ -0,0 +1,248 @@
+// Local changes not yet confirmed by the machine's 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. 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. 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.
+import { isSharedPreferenceKey } from './keys'
+
+const OUTBOX_PREFIX = 'hermes:ui-preferences:outbox:'
+const TAB_KEY = 'hermes:ui-preferences:tab'
+// A live tab with unsent changes re-stamps its outbox this often. A hidden
+// tab's timers can be throttled to once a minute, so an owner counts as gone
+// only well past that, or once its page was hidden for good (`closed`).
+export const OUTBOX_HEARTBEAT_MS = 10_000
+const OUTBOX_DEAD_MS = 90_000
+
+interface OutboxDoc {
+ beat: number
+ closed?: boolean
+ values: Record<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
+
+function readRaw(key: string): null | string {
+ try {
+ return window.localStorage.getItem(key)
+ } catch {
+ return null
+ }
+}
+
+function writeRaw(key: string, value: null | string) {
+ try {
+ if (value === null) {
+ window.localStorage.removeItem(key)
+ } else {
+ window.localStorage.setItem(key, value)
+ }
+ } catch {
+ // Storage is best-effort.
+ }
+}
+
+function parseOutbox(raw: null | string): null | OutboxDoc {
+ try {
+ const doc = JSON.parse(raw ?? 'null') as null | Partial<OutboxDoc>
+ const values = doc?.values
+
+ if (!doc || !values || typeof values !== 'object' || Array.isArray(values)) {
+ return null
+ }
+
+ return {
+ beat: typeof doc.beat === 'number' ? doc.beat : 0,
+ closed: doc.closed === true,
+ values: Object.fromEntries(
+ Object.entries(values).filter(
+ (entry): entry is [string, null | string] =>
+ isSharedPreferenceKey(entry[0]) && (entry[1] === null || typeof entry[1] === 'string')
+ )
+ )
+ }
+ } catch {
+ return null
+ }
+}
+
+function outboxKeys(): string[] {
+ const keys: string[] = []
+
+ try {
+ for (let index = 0; index < window.localStorage.length; index += 1) {
+ const key = window.localStorage.key(index)
+
+ if (key?.startsWith(OUTBOX_PREFIX)) {
+ keys.push(key)
+ }
+ }
+ } catch {
+ // Restricted storage reads as empty.
+ }
+
+ return keys
+}
+
+/**
+ * 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> {
+ const now = Date.now()
+ const own = outboxKey
+
+ const orphans = outboxKeys()
+ .filter(key => key !== own)
+ .map(key => ({ doc: parseOutbox(readRaw(key)), key }))
+ .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>()
+
+ for (const { doc, key } of orphans) {
+ for (const [name, value] of Object.entries(doc?.values ?? {})) {
+ if (readRaw(name) === value) {
+ adopted.set(name, value)
+ }
+ }
+
+ writeRaw(key, null)
+ }
+
+ return adopted
+}
+
+/** 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). */
+export function siblingPendingKeys(): Set<string> {
+ const own = claimOutboxKey()
+
+ return new Set(
+ outboxKeys()
+ .filter(key => key !== own)
+ .flatMap(key => Object.keys(parseOutbox(readRaw(key))?.values ?? {}))
+ )
+}
+
+/** This tab's outbox key, claimed once per page load. The previous load of this
+ * tab (same sessionStorage) hands its unsent changes over, and the outboxes
+ * of tabs that are gone join them. */
+export 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}`
+ const carried = previous ? parseOutbox(readRaw(`${OUTBOX_PREFIX}${previous}`)) : null
+
+ if (previous) {
+ writeRaw(`${OUTBOX_PREFIX}${previous}`, null)
+ }
+
+ saveOutbox(new Map([...adoptOrphanedOutboxes(), ...Object.entries(carried?.values ?? {})]))
+
+ return outboxKey
+}
+
+export function readOutbox(): Map<string, null | string> {
+ return new Map(Object.entries(parseOutbox(readRaw(claimOutboxKey()))?.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 } = {}) {
+ const key = claimOutboxKey()
+ const doc: OutboxDoc = { beat: Date.now(), ...(closed && { closed }), values: Object.fromEntries(pending) }
+
+ writeRaw(key, pending.size === 0 ? null : JSON.stringify(doc))
+}
+
+/** Heartbeat and page-lifecycle hooks for one running sync. `touch()` after
+ * every outbox save arms the heartbeat (`onOrphans`: adopt, re-stamp, touch)
+ * while the outbox holds changes, and only then: an idle tab runs no timer.
+ * Another tab's outbox saved as `closed` is an orphan the moment its page goes. */
+export function watchOutbox({
+ hasPending,
+ onLeave,
+ onOrphans,
+ onReturn
+}: {
+ hasPending: () => boolean
+ onLeave: () => void
+ onOrphans: () => void
+ onReturn: () => void
+}): { stop: () => void; touch: () => void } {
+ let timer: null | ReturnType<typeof setTimeout> = null
+
+ const touch = () => {
+ if (timer === null && hasPending()) {
+ timer = setTimeout(() => {
+ timer = null
+ onOrphans()
+ }, OUTBOX_HEARTBEAT_MS)
+ }
+ }
+
+ const hide = () => {
+ pageClosing = true
+ onLeave()
+ }
+
+ const show = () => {
+ pageClosing = false
+ onReturn()
+ }
+
+ const visibility = () => {
+ if (document.visibilityState === 'hidden') {
+ onLeave()
+ }
+ }
+
+ const storage = (event: StorageEvent) => {
+ if (event.key?.startsWith(OUTBOX_PREFIX) && event.key !== outboxKey && parseOutbox(event.newValue)?.closed) {
+ onOrphans()
+ }
+ }
+
+ window.addEventListener('pagehide', hide)
+ window.addEventListener('pageshow', show)
+ window.addEventListener('storage', storage)
+ document.addEventListener('visibilitychange', visibility)
+
+ return {
+ stop: () => {
+ if (timer !== null) {
+ clearTimeout(timer)
+ }
+
+ window.removeEventListener('pagehide', hide)
+ window.removeEventListener('pageshow', show)
+ window.removeEventListener('storage', storage)
+ document.removeEventListener('visibilitychange', visibility)
+ },
+ touch
+ }
+}
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 2e95f31674e..fa7daa15089 100644
--- a/apps/desktop/src/lib/ui-preferences/sync-handoff.test.ts
+++ b/apps/desktop/src/lib/ui-preferences/sync-handoff.test.ts
@@ -4,11 +4,7 @@ import path from 'node:path'
import { afterEach, expect, it, vi } from 'vitest'
-import {
- parseUiPreferencesWrite,
- readUiPreferences,
- writeUiPreferences
-} from '../../../electron/ui-preferences'
+import { parseUiPreferencesWrite, readUiPreferences, writeUiPreferences } from '../../../electron/ui-preferences'
import type { UiPreferencesBridge } from './sync'
@@ -133,3 +129,51 @@ it('a browser upgraded from a build that stored every default at load never seed
])
expect(readUiPreferences(file).values).toEqual({ [HAPTICS]: 'true', [KEYBINDS]: CUSTOM_KEYBINDS })
})
+
+it('a tab closed with an edit still unsent hands it to the next tab, which writes it and removes the outbox', async () => {
+ const file = storeFile()
+ await writeUiPreferences(file, { values: { [MODE]: 'light' } })
+ await pageLoad(file, { stores: [] })
+ closeTabs()
+
+ // The gateway is unreachable; the user switches to dark and closes the tab.
+ await pageLoad(file, { offline: true, stores: [] })
+ const { writeKey } = await import('@/lib/storage')
+ writeKey(MODE, 'dark')
+ // Closing fires pagehide and visibilitychange, in either order.
+ window.dispatchEvent(new PageTransitionEvent('pagehide'))
+ Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'hidden' })
+ document.dispatchEvent(new Event('visibilitychange'))
+ Reflect.deleteProperty(document, 'visibilityState')
+ window.sessionStorage.clear()
+
+ // The next tab opens at once, with the gateway back; the closed tab's
+ // module (and its sync) is gone.
+ await pageLoad(file, { stores: [] })
+
+ expect([window.localStorage.getItem(MODE), readUiPreferences(file).values[MODE]]).toEqual(['dark', 'dark'])
+ expect(outboxes()).toEqual([])
+})
+
+it('a crashed tab’s outbox is adopted by the next load once its heartbeat is stale; a live sibling’s is left alone', async () => {
+ const file = storeFile()
+ await writeUiPreferences(file, { values: { [MODE]: 'light' } })
+ await pageLoad(file, { offline: true, stores: [] })
+ const { writeKey } = await import('@/lib/storage')
+ writeKey(MODE, 'dark')
+ window.sessionStorage.clear()
+
+ // A sibling opening right away: the first tab is alive, its edit is its own.
+ await pageLoad(file, { stores: [] })
+ expect(readUiPreferences(file).values[MODE]).toBe('light')
+ expect(outboxes()).toHaveLength(1)
+
+ // The first tab died without a pagehide (a crash: no teardown, no more
+ // heartbeats): its stamp ages out.
+ vi.useFakeTimers({ now: Date.now() + 120_000, toFake: ['Date'] })
+ window.sessionStorage.clear()
+ await pageLoad(file, { stores: [] })
+
+ expect(readUiPreferences(file).values[MODE]).toBe('dark')
+ expect(outboxes()).toEqual([])
+})
diff --git a/apps/desktop/src/lib/ui-preferences/sync.ts b/apps/desktop/src/lib/ui-preferences/sync.ts
index 4ee6d2e8a8e..b0368ced48d 100644
--- a/apps/desktop/src/lib/ui-preferences/sync.ts
+++ b/apps/desktop/src/lib/ui-preferences/sync.ts
@@ -2,6 +2,7 @@ import type { UiPreferencesSnapshot, UiPreferencesWrite } from '../../../electro
import { markProvisionalPreference, onPersistenceEvent, provisionalPreferenceKeys } from '../storage'
import { isSharedPreferenceKey } from './keys'
+import { adoptOrphanedOutboxes, readOutbox, saveOutbox, siblingPendingKeys, watchOutbox } from './outbox'
export type { UiPreferencesSnapshot, UiPreferencesWrite }
@@ -16,14 +17,6 @@ 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. 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.
@@ -31,7 +24,6 @@ const JOINED_KEY = 'hermes:ui-preferences:generation'
const RETRY_DELAY_MS = 5000
const MAX_RETRY_DELAY_MS = 60_000
-let outboxKey: null | string = null
// The shared keys this window held before the app's module graph evaluated
// (`captureOwnPreferences`, run by boot.ts): this client's own data. Stores
// that persist their default the moment their module loads add keys after
@@ -66,37 +58,6 @@ function adopt(key: string, value: null | string, prune: boolean, live: boolean)
}
}
-/** 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. */
@@ -165,7 +126,7 @@ export function hydrateFromSnapshot(snapshot: null | undefined | UiPreferencesSn
return
}
- const outbox = readOutbox()
+ const outbox = new Set([...readOutbox().keys(), ...siblingPendingKeys()])
const prune = hasJoined(snapshot)
for (const key of new Set([...localSharedKeys(), ...Object.keys(snapshot.values)])) {
@@ -175,29 +136,6 @@ export function hydrateFromSnapshot(snapshot: null | undefined | UiPreferencesSn
}
}
-function readOutbox(): Map<string, null | string> {
- try {
- const parsed = JSON.parse(readRaw(claimOutboxKey()) ?? '{}') as unknown
-
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
- return new Map()
- }
-
- return new Map(
- Object.entries(parsed).filter(
- (entry): entry is [string, null | string] =>
- isSharedPreferenceKey(entry[0]) && (entry[1] === null || typeof entry[1] === 'string')
- )
- )
- } catch {
- return new Map()
- }
-}
-
-function saveOutbox(pending: Map<string, null | string>) {
- writeRaw(claimOutboxKey(), pending.size === 0 ? null : JSON.stringify(Object.fromEntries(pending)))
-}
-
/** A write the store answered "no" to (HTTP 400 / validation), as opposed to
* one that could not reach it; only the latter is worth retrying. */
function isRefusal(error: unknown): boolean {
@@ -257,6 +195,8 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
ownKeys = null
}
+ const siblings = siblingPendingKeys()
+
for (const key of new Set([...localSharedKeys(), ...Object.keys(snapshot.values), ...known.keys()])) {
if (!isSharedPreferenceKey(key)) {
continue
@@ -265,8 +205,9 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
const value = snapshot.values[key] ?? null
known.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))) {
+ // 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))) {
adopt(key, value, prune, live)
}
}
@@ -350,9 +291,40 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
refused.delete(event.key)
pending.set(event.key, event.value)
+ store()
+ })
+
+ // A tab that closed with changes unsent left its outbox: take it over (its
+ // values are already this origin's cache). This tab's own outbox stays
+ // stamped as alive while it holds changes; a page going away sends at once.
+ const outbox = watchOutbox({
+ hasPending: () => pending.size > 0 && !stopped,
+ onLeave: () => {
+ saveOutbox(pending)
+
+ if (flushTimer !== null) {
+ clearTimeout(flushTimer)
+ flushTimer = null
+ }
+
+ if (ready && !writing) {
+ void flush()
+ }
+ },
+ onOrphans: () => {
+ adoptOrphanedOutboxes().forEach((value, key) => pending.has(key) || pending.set(key, value))
+ store()
+ },
+ onReturn: () => saveOutbox(pending)
+ })
+
+ function store() {
saveOutbox(pending)
+ outbox.touch()
schedule(FLUSH_DELAY_MS)
- })
+ }
+
+ outbox.touch()
// First contact with a generation: add this origin's values the store lacks.
const join = async (snapshot: UiPreferencesSnapshot) => {
@@ -454,6 +426,9 @@ export function startUiPreferencesSync(bridge: null | UiPreferencesBridge | unde
stopped = true
stopListening()
stopChanges()
+ outbox.stop()
+ // Nothing here sends it any more: the next tab adopts what is unsent.
+ saveOutbox(pending, { closed: true })
if (flushTimer !== null) {
clearTimeout(flushTimer)