Skip to content

The agent that grows with you

fix(desktop): drafts survive a clock jump back and a downgrade/re-upgrade

Teknium7c18f4893fbe
diff --git a/apps/desktop/src/store/composer-draft-stash.test.ts b/apps/desktop/src/store/composer-draft-stash.test.ts
index da235cd9e6b..3a64ef30b3e 100644
--- a/apps/desktop/src/store/composer-draft-stash.test.ts
+++ b/apps/desktop/src/store/composer-draft-stash.test.ts
@@ -1,7 +1,7 @@
import { afterEach, expect, it, vi } from 'vitest'
import type * as ComposerStore from './composer'
-import { clearSessionDraft, stashSessionDraft, takeSessionDraft } from './composer'
+import { clearSessionDraft, SESSION_DRAFTS_STORAGE_KEY, stashSessionDraft, takeSessionDraft } from './composer'
// Two windows share localStorage, but each reads its own copy and gets the
// other's writes milliseconds later. A second module instance is the other
@@ -40,7 +40,14 @@ async function otherWindowWritesFrom(stale: Record<string, string>, write: (othe
}
}
+async function reopen(): Promise<typeof ComposerStore> {
+ vi.resetModules()
+
+ return import('./composer')
+}
+
afterEach(() => {
+ vi.restoreAllMocks()
clearSessionDraft(ALPHA)
clearSessionDraft(GAMMA)
window.localStorage.clear()
@@ -69,3 +76,41 @@ it("another window's write from a stale copy neither drops nor revives this wind
expect(reopened.takeSessionDraft(ALPHA).text).toBe('')
expect(reopened.takeSessionDraft(GAMMA).text).toBe('gamma edited')
})
+
+it('a draft saved after the system clock jumps back is not evicted by the cap on its own save', async () => {
+ window.localStorage.clear()
+ const start = 1_800_000_000_000
+ let now = start
+ vi.spyOn(Date, 'now').mockImplementation(() => now)
+ let store = await reopen()
+
+ for (let index = 0; index < 50; index++) {
+ now = start + index * 1000
+ store.stashSessionDraft(`old-${index}`, `old ${index}`, [])
+ }
+
+ now = start - 3_600_000
+ store.stashSessionDraft('after-jump', 'typed after the jump', [])
+ store = await reopen()
+
+ expect(store.takeSessionDraft('after-jump').text).toBe('typed after the jump')
+ expect(store.takeSessionDraft('old-0').text).toBe('')
+})
+
+it('after a downgrade and re-upgrade, what the older build edited, sent and typed sticks', async () => {
+ // The older build reads and writes only the legacy list: it edited A, sent B and typed C.
+ window.localStorage.clear()
+ let store = await reopen()
+ store.stashSessionDraft('A', 'a before', [])
+ store.stashSessionDraft('B', 'b sent in the older build', [])
+ window.localStorage.setItem(SESSION_DRAFTS_STORAGE_KEY, JSON.stringify({ A: 'a edited there', C: 'c typed there' }))
+
+ for (let boot = 0; boot < 2; boot++) {
+ store = await reopen()
+ expect(['A', 'B', 'C'].map(key => store.takeSessionDraft(key).text)).toEqual([
+ 'a edited there',
+ '',
+ 'c typed there'
+ ])
+ }
+})
diff --git a/apps/desktop/src/store/composer-draft-stash.ts b/apps/desktop/src/store/composer-draft-stash.ts
index 7816bf1b98f..ae164226294 100644
--- a/apps/desktop/src/store/composer-draft-stash.ts
+++ b/apps/desktop/src/store/composer-draft-stash.ts
@@ -13,10 +13,21 @@
* a stale copy cannot stick. The cap keeps the most recently saved drafts,
* by those times, so every window drops the same ones.
*
+ * Times come from one clock across every key (`nextStashStamp`): the newest
+ * stamp in the stash plus one when the wall clock reads earlier. After the
+ * system clock jumps back, a draft saved then still sorts newest, so the cap
+ * never evicts it on its own save.
+ *
* The authoritative copy is one key (`DRAFT_STASH_STORAGE_KEY`) so a read never
* sees half of another window's write. The older `{ key: text }` list is still
- * written after it, for builds and readers that only know that list; two
- * windows writing in the same instant can leave that mirror one write behind.
+ * written, before it, for older builds that only know that list. That list is
+ * exactly the texts of the stash's drafts, so the stash is also the copy of the
+ * list as this build last wrote it. An older build (after a downgrade) edits,
+ * sends and adds drafts only in the list: at boot, a list that differs from
+ * that copy was written there, and `adoptLegacyEdits` takes its changes (a key
+ * gone from the list was sent or cleared there). Two windows writing in the
+ * same instant can leave the list one write behind; the next stash write any
+ * window hears about rewrites it (`healLegacyMirror`).
*/
export const DRAFT_STASH_STORAGE_KEY = 'hermes:composer-drafts:v4'
@@ -32,6 +43,8 @@ export type StashEntries = Map<string, StashEntry>
interface StoredStash {
cleared?: Record<string, number>
drafts?: Record<string, { at?: number; text?: string }>
+ /** `false`: the legacy list could not be written with this stash, so it is not a copy of it. */
+ mirrored?: boolean
}
// A marker only has to outlive another window's stale copy (milliseconds);
@@ -60,11 +73,30 @@ export function hasDraftStash(): boolean {
}
}
+/** Later than every entry in `entries` and no earlier than the wall clock. */
+export function nextStashStamp(entries: StashEntries, now: number): number {
+ let highest = 0
+
+ for (const entry of entries.values()) {
+ highest = Math.max(highest, entry.at)
+ }
+
+ return Math.max(now, highest + 1)
+}
+
+function readStoredStash(): StoredStash {
+ try {
+ return JSON.parse(window.localStorage.getItem(DRAFT_STASH_STORAGE_KEY) ?? '{}') as StoredStash
+ } catch {
+ return {}
+ }
+}
+
export function readDraftStash(): StashEntries {
const entries: StashEntries = new Map()
try {
- const stored = JSON.parse(window.localStorage.getItem(DRAFT_STASH_STORAGE_KEY) ?? '{}') as StoredStash
+ const stored = readStoredStash()
for (const [key, at] of Object.entries(stored.cleared ?? {})) {
entries.set(key, { at: Number(at) || 0, text: null })
@@ -98,6 +130,57 @@ export function readLegacyDrafts(legacyKey: string): StashEntries {
}
}
+/** Keys whose text in the legacy list is not the stash's (a cleared marker reads as absent). */
+function legacyChanges(entries: StashEntries, legacyKey: string): Map<string, string | null> {
+ const legacy = readLegacyDrafts(legacyKey)
+ const changes = new Map<string, string | null>()
+
+ for (const key of new Set([...entries.keys(), ...legacy.keys()])) {
+ const theirs = legacy.get(key)?.text ?? null
+
+ if (theirs !== (entries.get(key)?.text ?? null)) {
+ changes.set(key, theirs)
+ }
+ }
+
+ return changes
+}
+
+/**
+ * Take what an older build changed in the legacy list since this build last
+ * wrote it: edited and added drafts, and keys it dropped (sent or cleared
+ * there) as cleared markers, all stamped newest. `null` when nothing changed.
+ */
+export function adoptLegacyEdits(entries: StashEntries, legacyKey: string, now: number): StashEntries | null {
+ if (readStoredStash().mirrored === false) {
+ return null
+ }
+
+ const changes = legacyChanges(entries, legacyKey)
+
+ if (changes.size === 0) {
+ return null
+ }
+
+ const at = nextStashStamp(entries, now)
+ const adopted: StashEntries = new Map(entries)
+
+ for (const [key, text] of changes) {
+ adopted.set(key, { at, text })
+ }
+
+ return adopted
+}
+
+/** Rewrite the legacy list from the stored stash when another window's write left it behind. */
+export function healLegacyMirror(legacyKey: string): void {
+ const entries = readDraftStash()
+
+ if (legacyChanges(entries, legacyKey).size > 0) {
+ writeLegacyList(entries, legacyKey)
+ }
+}
+
/** Keep the `maxDrafts` most recently saved drafts and only recent cleared markers. */
export function compactDraftStash(entries: StashEntries, maxDrafts: number, now: number): StashEntries {
const byRecency = [...entries].sort(([ka, a], [kb, b]) => b.at - a.at || (ka < kb ? -1 : ka > kb ? 1 : 0))
@@ -118,35 +201,56 @@ export function compactDraftStash(entries: StashEntries, maxDrafts: number, now:
return kept
}
-/** Write the stash (and the legacy list after it); `false` when storage refused. */
+/** The legacy `{ key: text }` list, oldest first (its most-recent-last order); `false` when storage refused. */
+function writeLegacyList(entries: StashEntries, legacyKey: string): boolean {
+ const texts: Record<string, string> = {}
+
+ for (const [key, entry] of [...entries].sort(([, a], [, b]) => a.at - b.at)) {
+ if (entry.text !== null) {
+ texts[key] = entry.text
+ }
+ }
+
+ try {
+ if (Object.keys(texts).length === 0) {
+ window.localStorage.removeItem(legacyKey)
+ } else {
+ window.localStorage.setItem(legacyKey, JSON.stringify(texts))
+ }
+
+ return true
+ } catch {
+ return false
+ }
+}
+
+/**
+ * Write the legacy list, then the stash; `false` when storage refused the stash.
+ * The list goes first so a stash write that fails leaves the list newer, and
+ * the next boot adopts it; a list write that fails marks the stash `mirrored:
+ * false`, so the next boot does not take the stale list for an older build's.
+ */
export function writeDraftStash(entries: StashEntries, legacyKey: string): boolean {
const drafts: NonNullable<StoredStash['drafts']> = {}
const cleared: Record<string, number> = {}
- const texts: Record<string, string> = {}
- // Oldest first, so the legacy list keeps its most-recent-last order.
for (const [key, entry] of [...entries].sort(([, a], [, b]) => a.at - b.at)) {
if (entry.text === null) {
cleared[key] = entry.at
} else {
drafts[key] = { at: entry.at, text: entry.text }
- texts[key] = entry.text
}
}
+ const mirrored = writeLegacyList(entries, legacyKey)
+
try {
- const raw = JSON.stringify({ cleared, drafts })
+ const raw = JSON.stringify(mirrored ? { cleared, drafts } : { cleared, drafts, mirrored })
if (window.localStorage.getItem(DRAFT_STASH_STORAGE_KEY) !== raw) {
window.localStorage.setItem(DRAFT_STASH_STORAGE_KEY, raw)
}
- if (Object.keys(texts).length === 0) {
- window.localStorage.removeItem(legacyKey)
- } else {
- window.localStorage.setItem(legacyKey, JSON.stringify(texts))
- }
-
return true
} catch {
return false
diff --git a/apps/desktop/src/store/composer.ts b/apps/desktop/src/store/composer.ts
index c8325401842..94262bb554b 100644
--- a/apps/desktop/src/store/composer.ts
+++ b/apps/desktop/src/store/composer.ts
@@ -7,10 +7,13 @@ import { triggerHaptic } from '@/lib/haptics'
import { persistString, storedString } from '@/lib/storage'
import {
+ adoptLegacyEdits,
compactDraftStash,
DRAFT_STASH_STORAGE_KEY,
hasDraftStash,
+ healLegacyMirror,
newerEntry,
+ nextStashStamp,
readDraftStash,
readLegacyDrafts,
type StashEntries,
@@ -316,11 +319,19 @@ const cloneDraft = (draft: SessionDraft): SessionDraft => ({
// What this window last read from or wrote to the shared stash, cleared
// markers included. A reload applies only entries newer than this, and a write
// puts back any entry here that storage has since lost to a stale writer.
-// The pre-v4 list seeds it only before any window has written v4: after
-// that the list is a mirror that can lag a moment behind, and reading it
-// could bring back a draft whose cleared marker has expired.
+// The pre-v4 list seeds it before any window has written v4; after that only
+// what an older build changed in that list since this build wrote it counts.
let persistedDrafts: StashEntries = hasDraftStash() ? readDraftStash() : readLegacyDrafts(SESSION_DRAFTS_STORAGE_KEY)
+if (typeof window !== 'undefined' && hasDraftStash()) {
+ const adopted = adoptLegacyEdits(persistedDrafts, SESSION_DRAFTS_STORAGE_KEY, Date.now())
+
+ if (adopted) {
+ persistedDrafts = compactDraftStash(adopted, MAX_PERSISTED_DRAFTS, Date.now())
+ writeDraftStash(persistedDrafts, SESSION_DRAFTS_STORAGE_KEY)
+ }
+}
+
const draftsBySession = new Map<string, SessionDraft>(
[...persistedDrafts]
.filter((entry): entry is [string, StashEntry & { text: string }] => entry[1].text !== null)
@@ -434,7 +445,7 @@ function applyStoredDraft(key: string, entry: StashEntry): void {
}
/** Merge storage with this window's copy (plus `local`, this window's new save) and write back what storage lacks. */
-function syncPersistedDrafts(local?: { entry: StashEntry; key: string }): void {
+function syncPersistedDrafts(local?: { key: string; text: string | null }): void {
const stored = readDraftStash()
const merged: StashEntries = new Map()
let rewrite = Boolean(local)
@@ -455,7 +466,9 @@ function syncPersistedDrafts(local?: { entry: StashEntry; key: string }): void {
}
if (local) {
- merged.set(local.key, local.entry)
+ // Later than every entry any window has saved, whatever the wall clock
+ // says, so the save wins the merge everywhere and the cap never evicts it.
+ merged.set(local.key, { at: nextStashStamp(merged, Date.now()), text: local.text })
}
persistedDrafts = rewrite ? compactDraftStash(merged, MAX_PERSISTED_DRAFTS, Date.now()) : merged
@@ -473,6 +486,7 @@ if (typeof window !== 'undefined') {
window.addEventListener('storage', event => {
if (event.key === DRAFT_STASH_STORAGE_KEY || event.key === null) {
syncPersistedDrafts()
+ healLegacyMirror(SESSION_DRAFTS_STORAGE_KEY)
}
})
}
@@ -535,9 +549,7 @@ export function stashSessionDraft(scope: string | null | undefined, text: string
// Clearing a draft this window never saw saved has nothing to clear.
if (saved !== null || previous?.text) {
- // Stamped later than any copy of this key this window has seen, so the
- // save wins the merge in every window.
- syncPersistedDrafts({ entry: { at: Math.max(Date.now(), (previous?.at ?? 0) + 1), text: saved }, key })
+ syncPersistedDrafts({ key, text: saved })
}
publishDraftTitle(key, deriveDraftTitle(text))
diff --git a/apps/desktop/src/store/dead-session-prune.ts b/apps/desktop/src/store/dead-session-prune.ts
index 2b3aebc22de..6cbc87f6930 100644
--- a/apps/desktop/src/store/dead-session-prune.ts
+++ b/apps/desktop/src/store/dead-session-prune.ts
@@ -3,7 +3,7 @@
* the backend.
*
* Pins (`hermes.desktop.pinnedSessions`), composer drafts
- * (`hermes:composer-drafts:v3`), queued prompts
+ * (`hermes:composer-drafts:v4`, mirrored to v3), queued prompts
* (`hermes.desktop.composerQueue.v1`) and interrupted sends
* (`hermes:composer-outbox:v1:*`) are keyed by session id and re-asserted
* or probed at boot. When a session is removed from state.db (retention purge,