Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(chats): a wiped IndexedDB is restored, and the backup stops finishing the job

purplef5589e65bcf1
diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs
index 06947ae8..06bdc7ec 100644
--- a/src-tauri/src/commands/system.rs
+++ b/src-tauri/src/commands/system.rs
@@ -264,15 +264,96 @@ fn persistent_dir() -> Result<std::path::PathBuf, String> {
}
}
-/// Backup all localStorage stores to %APPDATA% (survives NSIS updates)
-/// Uses atomic write (temp file + rename) to prevent corruption on crash
+/// Which keys the previous backup carried that the incoming snapshot does not.
+///
+/// A key is only ever ABSENT from a snapshot when the storage read came back
+/// empty, which means the store is gone, not that the user emptied it: a
+/// cleared chat list still serialises to a present, valid value. So a missing
+/// key is a signal that something was lost since the last backup, never a
+/// deletion the user asked for.
+///
+/// Both sides must be JSON objects for this to mean anything. Anything else
+/// answers "nothing was lost", which leaves the plain overwrite in place
+/// rather than inventing a merge over data we cannot read.
+pub(crate) fn keys_lost(previous: &str, incoming: &str) -> Vec<String> {
+ let (Ok(serde_json::Value::Object(prev)), Ok(serde_json::Value::Object(next))) = (
+ serde_json::from_str::<serde_json::Value>(previous),
+ serde_json::from_str::<serde_json::Value>(incoming),
+ ) else {
+ return Vec::new();
+ };
+ prev.iter()
+ .filter(|(k, v)| {
+ !v.as_str().unwrap_or("").is_empty()
+ && next.get(*k).and_then(|n| n.as_str()).unwrap_or("").is_empty()
+ })
+ .map(|(k, _)| k.clone())
+ .collect()
+}
+
+/// The snapshot that actually goes to disk: the incoming one, plus every key
+/// it lost carried over from the backup that is already there.
+///
+/// aldrich_ironhart, 2.6.5, Discord #general 18.08.: "My code chats are
+/// vaporised". chat-conversations lives in IndexedDB, localStorage does not,
+/// and they are different storage layers with different lifetimes. A hard
+/// process kill during a self update can leave Chromium discarding the whole
+/// IndexedDB database on the next start while localStorage comes back
+/// untouched. On that boot the snapshot the frontend builds simply has no
+/// chat-conversations in it, and this command wrote that over the one
+/// remaining copy of the chats, five seconds after launch, every launch.
+///
+/// A backup is not a mirror. It may lag, it may hold something the live store
+/// no longer has, and it must never be the thing that finishes a data loss.
+pub(crate) fn merged_backup(previous: &str, incoming: &str, lost: &[String]) -> String {
+ if lost.is_empty() {
+ return incoming.to_string();
+ }
+ let (Ok(serde_json::Value::Object(prev)), Ok(serde_json::Value::Object(mut next))) = (
+ serde_json::from_str::<serde_json::Value>(previous),
+ serde_json::from_str::<serde_json::Value>(incoming),
+ ) else {
+ return incoming.to_string();
+ };
+ for key in lost {
+ if let Some(v) = prev.get(key) {
+ next.insert(key.clone(), v.clone());
+ }
+ }
+ serde_json::Value::Object(next).to_string()
+}
+
+/// Backup all stores to %APPDATA% (survives NSIS updates). Atomic write (temp
+/// file + rename) so a crash mid-write cannot truncate a previous backup.
+///
+/// Never destructive: a snapshot that lost a key keeps the old value for it,
+/// and the untouched previous file is set aside once as store_backup.prev.json
+/// so the loss can still be looked at afterwards. See merged_backup.
#[tauri::command]
pub fn backup_stores(data: String) -> Result<(), String> {
let dir = persistent_dir()?;
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let target = dir.join("store_backup.json");
let tmp = dir.join("store_backup.tmp");
- std::fs::write(&tmp, &data).map_err(|e| e.to_string())?;
+
+ let previous = std::fs::read_to_string(&target).unwrap_or_default();
+ let lost = keys_lost(&previous, &data);
+ let payload = if lost.is_empty() {
+ data
+ } else {
+ tracing::warn!("backup snapshot lost {:?}, keeping the previous values", lost);
+ // Set the last complete file aside before it is replaced, once. The
+ // merge means the next snapshot is complete again, so a machine in
+ // this state writes this file on the first boot after the loss and
+ // never again.
+ let aside = dir.join("store_backup.prev.json");
+ if !aside.exists() {
+ let _ = std::fs::write(&aside, &previous);
+ }
+ merged_backup(&previous, &data, &lost)
+ };
+
+ std::fs::write(&tmp, &payload).map_err(|e| e.to_string())?;
std::fs::rename(&tmp, &target).map_err(|e| e.to_string())?;
Ok(())
}
@@ -394,6 +475,88 @@ pub fn get_current_time() -> Result<serde_json::Value, String> {
mod tests {
use super::*;
+ /// aldrich_ironhart, 2.6.5, Discord #general 18.08. 12:59 "has anyone lost
+ /// their chats after a restart??" and 16:12 "My code chats are vaporised".
+ ///
+ /// chat-conversations lives in IndexedDB and the rest of the stores live
+ /// in localStorage. Those are different storage layers with different
+ /// lifetimes, so a boot can come back with one gone and the other whole.
+ /// On such a boot the snapshot the frontend hands this command has no
+ /// chat-conversations in it at all, and the old code wrote it straight
+ /// over the only remaining copy.
+ #[test]
+ fn a_snapshot_that_lost_the_chats_does_not_take_the_backup_with_it() {
+ let previous = r#"{"__ts":"old","chat-conversations":"{\"chats\":42}","chat-settings":"{}"}"#;
+ let incoming = r#"{"__ts":"new","chat-settings":"{}"}"#;
+
+ let lost = keys_lost(previous, incoming);
+ assert_eq!(lost, vec!["chat-conversations".to_string()]);
+
+ let merged = merged_backup(previous, incoming, &lost);
+ let v: serde_json::Value = serde_json::from_str(&merged).unwrap();
+ assert_eq!(v["chat-conversations"], "{\"chats\":42}");
+ // The rest of the snapshot is still the new one.
+ assert_eq!(v["__ts"], "new");
+
+ // Negative control: the old rule was the incoming string, unread.
+ let old_rule: serde_json::Value = serde_json::from_str(incoming).unwrap();
+ assert!(old_rule.get("chat-conversations").is_none());
+ }
+
+ /// The one case that must NOT be treated as a loss. A user who deletes
+ /// every chat still has a live store, so the key is present and carries a
+ /// valid empty payload. Carrying the old value over there would resurrect
+ /// chats somebody deliberately deleted.
+ #[test]
+ fn an_emptied_store_is_not_a_lost_one() {
+ let previous = r#"{"chat-conversations":"{\"state\":{\"conversations\":[1,2]}}"}"#;
+ let incoming = r#"{"chat-conversations":"{\"state\":{\"conversations\":[]}}"}"#;
+ assert!(keys_lost(previous, incoming).is_empty());
+ assert_eq!(merged_backup(previous, incoming, &[]), incoming);
+ }
+
+ #[test]
+ fn a_first_backup_and_unreadable_neighbours_are_left_alone() {
+ let incoming = r#"{"__ts":"new","chat-conversations":"x"}"#;
+ // No previous file at all.
+ assert!(keys_lost("", incoming).is_empty());
+ assert_eq!(merged_backup("", incoming, &[]), incoming);
+ // A previous file that is not JSON, or not an object, cannot be
+ // reasoned about, and guessing over unreadable data is worse than the
+ // plain overwrite this replaced.
+ assert!(keys_lost("not json at all", incoming).is_empty());
+ assert!(keys_lost("[1,2,3]", incoming).is_empty());
+ // And an incoming payload we cannot read is written as it came.
+ assert!(keys_lost(r#"{"a":"1"}"#, "not json").is_empty());
+ }
+
+ #[test]
+ fn an_empty_string_value_counts_as_lost_too() {
+ // The frontend skips falsy values, so this shape should not occur, but
+ // an empty payload is a loss by any reading and must not overwrite.
+ let previous = r#"{"chat-conversations":"real"}"#;
+ let incoming = r#"{"chat-conversations":""}"#;
+ assert_eq!(keys_lost(previous, incoming), vec!["chat-conversations".to_string()]);
+ let merged = merged_backup(previous, incoming, &["chat-conversations".to_string()]);
+ let v: serde_json::Value = serde_json::from_str(&merged).unwrap();
+ assert_eq!(v["chat-conversations"], "real");
+ }
+
+ #[test]
+ fn every_key_that_went_missing_comes_back_not_just_the_first() {
+ let previous = r#"{"chat-conversations":"c","locally-uncensored-memory":"m","rag-store":"r"}"#;
+ let incoming = r#"{"rag-store":"r2"}"#;
+ let mut lost = keys_lost(previous, incoming);
+ lost.sort();
+ assert_eq!(lost, vec!["chat-conversations".to_string(), "locally-uncensored-memory".to_string()]);
+ let merged = merged_backup(previous, incoming, &lost);
+ let v: serde_json::Value = serde_json::from_str(&merged).unwrap();
+ assert_eq!(v["chat-conversations"], "c");
+ assert_eq!(v["locally-uncensored-memory"], "m");
+ // A key the snapshot DID bring keeps the new value, not the old one.
+ assert_eq!(v["rag-store"], "r2");
+ }
+
/// The old implementation spawned a process for the UTC offset and fell
/// back to 0 when that failed, so it could report UTC as local time. These
/// assert the three values stay consistent with each other.
diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsx
index 803a215e..7701ed90 100644
--- a/src/components/layout/AppShell.tsx
+++ b/src/components/layout/AppShell.tsx
@@ -24,6 +24,8 @@ import { detectLocalBackends, type DetectedBackend } from '../../lib/backend-det
import { whenRunsIdle } from '../../lib/run-idle'
import { backendCall, isTauri } from '../../api/backend'
import { idbStorage } from '../../lib/idbStorage'
+import { idbKeysToRestore, mayReloadForIdbRestore } from '../../lib/idb-restore'
+import { log } from '../../lib/logger'
import type { AIModel } from '../../types/models'
import { useKeyboardShortcuts } from '../../hooks/useKeyboardShortcuts'
import { useCloudAuth } from '../../hooks/useCloudAuth'
@@ -215,6 +217,44 @@ export function AppShell() {
// backup exists and the live store has none for the documents the
// localStorage `rag-store` knows about. Best-effort; ignore errors.
;(async () => {
+ // The chats live in IndexedDB too, and until now nothing on this
+ // branch looked at them. A hard process kill mid write, which is
+ // what a self update is, can leave Chromium discarding the whole
+ // IndexedDB database while localStorage comes back whole, and this
+ // branch IS that boot: every localStorage store answers, so the full
+ // restore below never runs. aldrich_ironhart lost a 230k token
+ // coding chat that way on 2.6.5 with a good copy of it sitting in
+ // store_backup.json the entire time.
+ try {
+ const live: Record<string, string | null> = {}
+ for (const key of IDB_STORE_KEYS) {
+ live[key] = await Promise.resolve(idbStorage.getItem(key)).catch(() => null)
+ }
+ if (Object.values(live).some((v) => !v)) {
+ const raw = await backendCall<string | null>('restore_stores')
+ const parsed = raw ? JSON.parse(raw) : null
+ const wanted = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
+ ? idbKeysToRestore(live, parsed as Record<string, unknown>)
+ : []
+ let back = 0
+ for (const key of wanted) {
+ try {
+ await Promise.resolve(idbStorage.setItem(key, (parsed as Record<string, string>)[key]))
+ back++
+ } catch { /* one key failing must not stop the rest */ }
+ }
+ if (back > 0) {
+ log.warn('[AppShell] IndexedDB stores were empty, restored from the appData backup', { keys: wanted })
+ // The stores already hydrated empty, so only a reload picks
+ // this up. Once per window session, never a loop.
+ if (mayReloadForIdbRestore(typeof sessionStorage !== 'undefined' ? sessionStorage : null)) {
+ resolveRestoreDecided()
+ window.location.reload()
+ return
+ }
+ }
+ }
+ } catch { /* best-effort, the RAG restore below still runs */ }
try {
const data = await backendCall<string | null>('restore_rag_chunks')
if (data) {
diff --git a/src/lib/__tests__/idb-restore.test.ts b/src/lib/__tests__/idb-restore.test.ts
new file mode 100644
index 00000000..28eaceac
--- /dev/null
+++ b/src/lib/__tests__/idb-restore.test.ts
@@ -0,0 +1,125 @@
+/**
+ * DATA LOSS, aldrich_ironhart on 2.6.5, Discord #general 18.08.:
+ * 12:59 "Uhhh guys, has anyone lost their chats after a restart??",
+ * 16:12 "My code chats are vaporised" (a coding chat around 230k tokens).
+ * sockenmonster on the same build still had every chat, weeks old ones
+ * included, so this is not a plain regression in how LU writes.
+ *
+ * chat-conversations and locally-uncensored-memory live in IndexedDB (2.5.0,
+ * the 5 MB localStorage cap could not hold a real history). Everything else
+ * lives in localStorage. Two storage layers, two lifetimes: a hard process
+ * kill mid write, which is what a self update does, can leave Chromium
+ * discarding the whole IndexedDB database on the next start while
+ * localStorage comes back untouched.
+ *
+ * AppShell's restore only ever asked localStorage. On that boot every
+ * localStorage store answers, so it took the quiet branch, restored RAG
+ * chunks, and returned. Nothing looked at IndexedDB. The chats stayed gone
+ * with a good copy of them sitting in store_backup.json the whole time, and
+ * the backup triad then wrote the empty state over it (the second half of
+ * this fix lives in Rust, backup_stores).
+ *
+ * Run: npx vitest run src/lib/__tests__/idb-restore.test.ts
+ */
+import { describe, it, expect, vi } from 'vitest'
+import { idbKeysToRestore, mayReloadForIdbRestore, IDB_RESTORE_ONCE_KEY } from '../idb-restore'
+
+const CHATS = 'chat-conversations'
+const MEM = 'locally-uncensored-memory'
+
+describe('deciding what to put back after an IndexedDB wipe', () => {
+ it('names the store that is gone while the backup still has it', () => {
+ // aldrich's boot: localStorage whole, IndexedDB empty, backup intact.
+ const live = { [CHATS]: null, [MEM]: null }
+ const backup = { __ts: 'yesterday', [CHATS]: '{"state":{"conversations":[1]}}', [MEM]: '{"state":{}}' }
+ expect(idbKeysToRestore(live, backup).sort()).toEqual([CHATS, MEM])
+ })
+
+ it('never writes over a store that still has something', () => {
+ // The ordinary boot, which is every boot but one. Restoring here would
+ // roll a live store back to whatever the last backup happened to hold.
+ const live = { [CHATS]: '{"state":{"conversations":[1,2,3]}}', [MEM]: null }
+ const backup = { [CHATS]: '{"state":{"conversations":[1]}}', [MEM]: '{"state":{}}' }
+ expect(idbKeysToRestore(live, backup)).toEqual([MEM])
+ })
+
+ it('a shorter live store is not a wiped one', () => {
+ // Deleting chats is something people do on purpose. Only nothing at all
+ // counts, never "less than the backup has".
+ const live = { [CHATS]: '{"state":{"conversations":[]}}' }
+ const backup = { [CHATS]: '{"state":{"conversations":[1,2,3]}}' }
+ expect(idbKeysToRestore(live, backup)).toEqual([])
+ })
+
+ it('nothing to restore from is nothing to do', () => {
+ expect(idbKeysToRestore({ [CHATS]: null }, null)).toEqual([])
+ expect(idbKeysToRestore({ [CHATS]: null }, {})).toEqual([])
+ expect(idbKeysToRestore({ [CHATS]: null }, { [CHATS]: '' })).toEqual([])
+ expect(idbKeysToRestore({ [CHATS]: null }, { [CHATS]: ' ' })).toEqual([])
+ // A backup value that is not a string cannot be handed to idbStorage.
+ expect(idbKeysToRestore({ [CHATS]: null }, { [CHATS]: { conversations: [] } })).toEqual([])
+ })
+
+ it('NEGATIVE CONTROL: the old rule never asked IndexedDB at all', () => {
+ // What AppShell decided on aldrich's boot: some localStorage store is
+ // there and the restore sentinel is set, therefore nothing to restore.
+ // Both true, and the chats were gone.
+ const localStorageStores = { 'chat-settings': '{}', 'lu-providers': '{}' }
+ const hasStores = Object.values(localStorageStores).some(Boolean)
+ const restoreComplete = '1'
+ expect(hasStores && !!restoreComplete).toBe(true)
+ // The new question, on the same boot, has an answer.
+ expect(idbKeysToRestore({ [CHATS]: null }, { [CHATS]: 'the chats' })).toEqual([CHATS])
+ })
+})
+
+describe('the reload that makes a restored store visible', () => {
+ function session() {
+ const store: Record<string, string> = {}
+ return {
+ getItem: vi.fn((k: string) => store[k] ?? null),
+ setItem: vi.fn((k: string, v: string) => { store[k] = v }),
+ }
+ }
+
+ it('happens once, so a write that never lands cannot loop the app', () => {
+ const s = session()
+ expect(mayReloadForIdbRestore(s)).toBe(true)
+ expect(s.setItem).toHaveBeenCalledWith(IDB_RESTORE_ONCE_KEY, '1')
+ // Second boot of the same window session: the restore may run again, the
+ // reload may not.
+ expect(mayReloadForIdbRestore(s)).toBe(false)
+ })
+
+ it('no session storage means no reload, rather than an unbounded one', () => {
+ expect(mayReloadForIdbRestore(null)).toBe(false)
+ const broken = {
+ getItem: () => null,
+ setItem: () => { throw new Error('denied') },
+ }
+ expect(mayReloadForIdbRestore(broken)).toBe(false)
+ })
+})
+
+describe('the wiring in AppShell', () => {
+ it('asks IndexedDB before it releases the backup triad', async () => {
+ // Order is the whole safety property: the triad's first doBackup reads the
+ // live stores and writes them to store_backup.json. Released too early on
+ // a wiped boot, it snapshots nothing over the only copy of the chats. The
+ // file already guards the localStorage case with restoreDecided; this pins
+ // that the IndexedDB case sits inside the same gate.
+ const { readFileSync } = await import('node:fs')
+ const { fileURLToPath } = await import('node:url')
+ const { dirname, resolve } = await import('node:path')
+ const src = readFileSync(
+ resolve(dirname(fileURLToPath(import.meta.url)), '../../components/layout/AppShell.tsx'),
+ 'utf8',
+ )
+ const ask = src.indexOf('idbKeysToRestore(live')
+ const release = src.indexOf('resolveRestoreDecided()')
+ expect(ask).toBeGreaterThan(-1)
+ expect(release).toBeGreaterThan(ask)
+ // And the reload is gated, not unconditional.
+ expect(src).toContain('mayReloadForIdbRestore(')
+ })
+})
diff --git a/src/lib/idb-restore.ts b/src/lib/idb-restore.ts
new file mode 100644
index 00000000..c44d48d8
--- /dev/null
+++ b/src/lib/idb-restore.ts
@@ -0,0 +1,67 @@
+/**
+ * Which IndexedDB-backed stores need to be put back from the appData backup.
+ *
+ * aldrich_ironhart, 2.6.5, Discord #general 18.08.: "has anyone lost their
+ * chats after a restart??", then "My code chats are vaporised".
+ *
+ * LU keeps chat-conversations and locally-uncensored-memory in IndexedDB
+ * (2.5.0, the 5 MB localStorage cap could not hold a real history) and every
+ * other store in localStorage. Those are different storage layers with
+ * different lifetimes: a hard process kill mid write, which is what a self
+ * update does, can leave Chromium discarding the whole IndexedDB database on
+ * the next start while localStorage comes back untouched.
+ *
+ * AppShell's restore only ever asked localStorage. On that boot every
+ * localStorage store answers, so it took the quiet branch, restored RAG chunks
+ * and returned. Nothing looked at IndexedDB, so the chats stayed gone with a
+ * good copy of them sitting in store_backup.json the whole time.
+ *
+ * Pure so the decision can be proven without a webview: the caller reads the
+ * live stores and the backup, this says what to write back.
+ */
+
+/** Never restore over something the live store still has. A shorter live
+ * value is not evidence of anything (a user can delete chats), so the only
+ * case that counts is a live store with nothing in it at all. */
+function isEmpty(value: string | null | undefined): boolean {
+ return !value || value.trim() === ''
+}
+
+/**
+ * Keys that are empty in the live store and present in the backup.
+ *
+ * @param live what idbStorage answered for each key, null when absent
+ * @param backup the parsed store_backup.json, or null when there is none
+ */
+export function idbKeysToRestore(
+ live: Record<string, string | null>,
+ backup: Record<string, unknown> | null,
+): string[] {
+ if (!backup) return []
+ return Object.keys(live).filter((key) => {
+ if (!isEmpty(live[key])) return false
+ const saved = backup[key]
+ return typeof saved === 'string' && !isEmpty(saved)
+ })
+}
+
+/**
+ * A hydrated store cannot pick the restored value up on its own, so the caller
+ * reloads. That must happen at most once per window session: an IndexedDB that
+ * refuses every write would otherwise restore, reload, find nothing, and go
+ * round again forever.
+ */
+export const IDB_RESTORE_ONCE_KEY = 'lu-idb-restored'
+
+export function mayReloadForIdbRestore(session: Pick<Storage, 'getItem' | 'setItem'> | null): boolean {
+ if (!session) return false
+ try {
+ if (session.getItem(IDB_RESTORE_ONCE_KEY)) return false
+ session.setItem(IDB_RESTORE_ONCE_KEY, '1')
+ return true
+ } catch {
+ // No sessionStorage means no way to remember, and a reload loop is worse
+ // than a boot that shows the restored chats only after the next start.
+ return false
+ }
+}
diff --git a/src/stores/__tests__/update-flushes-the-chats.test.ts b/src/stores/__tests__/update-flushes-the-chats.test.ts
new file mode 100644
index 00000000..13d160fd
--- /dev/null
+++ b/src/stores/__tests__/update-flushes-the-chats.test.ts
@@ -0,0 +1,131 @@
+/**
+ * DATA LOSS, aldrich_ironhart on 2.6.5 (Discord #general 18.08. 12:59 "has
+ * anyone lost their chats after a restart??", 16:12 "My code chats are
+ * vaporised", a coding chat around 230k tokens). sockenmonster on the same
+ * build lost nothing, weeks old chats included, so this is not a plain
+ * regression in how LU writes: the persistence layer is unchanged between
+ * 2.6.4 and 2.6.5.
+ *
+ * What IS specific to the update is the handover. installAndRestart calls
+ * install(), which does not return, the installer takes the process down. The
+ * chat store persists through coalescedJSONStorage, whose window closes 250 ms
+ * after the last change, so a multi megabyte IndexedDB put can be in flight at
+ * exactly that moment. A LevelDB killed mid write is the most plausible way to
+ * end up with Chromium discarding the whole database on the next start, and
+ * the bigger the history the wider the window.
+ *
+ * So the store flushes and goes quiet before it hands over. This pins the
+ * ORDER, which is the entire point: flushing after install() has started would
+ * be the same bug with extra steps.
+ *
+ * Run: npx vitest run src/stores/__tests__/update-flushes-the-chats.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const calls: string[] = []
+
+vi.mock('../../api/backend', () => ({
+ isTauri: () => true,
+ openExternal: vi.fn(),
+ backendCall: vi.fn(async (cmd: string) => {
+ calls.push(`backend:${cmd}`)
+ return null
+ }),
+}))
+
+vi.mock('../../api/engine', () => ({
+ stopBundledEngine: vi.fn(async () => { calls.push('stop:engine') }),
+ stopBundledEmbed: vi.fn(async () => { calls.push('stop:embed') }),
+}))
+
+const flushChatPersist = vi.fn(async () => { calls.push('flush:chat') })
+const flushStagedPersist = vi.fn(async () => { calls.push('flush:staged') })
+
+vi.mock('../chatStore', () => ({ flushChatPersist: () => flushChatPersist() }))
+vi.mock('../stagedChangesStore', () => ({ flushStagedPersist: () => flushStagedPersist() }))
+
+vi.mock('../../../package.json', () => ({ version: '2.6.5' }))
+
+const install = vi.fn(async () => { calls.push('install') })
+
+vi.mock('@tauri-apps/plugin-updater', () => ({
+ check: vi.fn(async () => ({ version: '2.6.6', body: 'notes', install, download: vi.fn() })),
+}))
+
+import { useUpdateStore } from '../updateStore'
+
+async function armPendingUpdate() {
+ await useUpdateStore.getState().checkForUpdate(true)
+}
+
+describe('an update puts the chats on disk before it hands the process over', () => {
+ beforeEach(() => {
+ calls.length = 0
+ install.mockClear()
+ flushChatPersist.mockClear()
+ flushStagedPersist.mockClear()
+ flushChatPersist.mockImplementation(async () => { calls.push('flush:chat') })
+ useUpdateStore.setState({
+ downloadStatus: 'downloaded',
+ autoDownload: false,
+ lastChecked: null,
+ latestVersion: null,
+ updateAvailable: false,
+ errorMessage: null,
+ })
+ })
+
+ it('flushes both coalesced stores before install()', async () => {
+ await armPendingUpdate()
+ calls.length = 0
+
+ await useUpdateStore.getState().installAndRestart()
+
+ expect(calls).toContain('flush:chat')
+ expect(calls).toContain('flush:staged')
+ expect(calls.indexOf('flush:chat')).toBeLessThan(calls.indexOf('install'))
+ expect(calls.indexOf('flush:staged')).toBeLessThan(calls.indexOf('install'))
+ })
+
+ it('NEGATIVE CONTROL: freeing the sidecars was never a flush', async () => {
+ // What the path did before: two engine stops and straight into install().
+ // Neither of those touches the persistence layer, so a write started
+ // 249 ms earlier was still in flight when the installer arrived.
+ await armPendingUpdate()
+ calls.length = 0
+
+ await useUpdateStore.getState().installAndRestart()
+
+ const before = calls.slice(0, calls.indexOf('install'))
+ expect(before).toContain('stop:engine')
+ expect(before).toContain('stop:embed')
+ // The old prefix was exactly those two, and that is what this adds to.
+ expect(before.filter((c) => c.startsWith('flush:'))).toHaveLength(2)
+ })
+
+ it('the pause after the flush is real, not zero', async () => {
+ // The flush resolves when the put has landed. What the storage engine
+ // does with its own log after a commit is not something a page can await,
+ // so there is a deliberate quiet moment on top.
+ await armPendingUpdate()
+ calls.length = 0
+
+ const started = Date.now()
+ await useUpdateStore.getState().installAndRestart()
+ expect(Date.now() - started).toBeGreaterThanOrEqual(200)
+ })
+
+ it('a flush that fails does not become the reason the update never happens', async () => {
+ // Same stance as the sidecar stops: best effort, the installer has its own
+ // recovery, and refusing to update would be the worse failure.
+ flushChatPersist.mockRejectedValueOnce(new Error('idb gone'))
+
+ await armPendingUpdate()
+ calls.length = 0
+
+ await useUpdateStore.getState().installAndRestart()
+
+ expect(install).toHaveBeenCalledTimes(1)
+ expect(useUpdateStore.getState().downloadStatus).not.toBe('error')
+ })
+})
diff --git a/src/stores/updateStore.ts b/src/stores/updateStore.ts
index 11a35efd..685b6719 100644
--- a/src/stores/updateStore.ts
+++ b/src/stores/updateStore.ts
@@ -3,8 +3,14 @@ import { persist } from 'zustand/middleware'
import { version as currentVersion } from '../../package.json'
import { isTauri, backendCall, openExternal } from '../api/backend'
import { stopBundledEngine, stopBundledEmbed } from '../api/engine'
+import { flushChatPersist } from './chatStore'
+import { flushStagedPersist } from './stagedChangesStore'
import type { Update } from '@tauri-apps/plugin-updater'
+/** Quiet time between the last persisted write and handing the process to
+ * the installer. See installAndRestart for why it is a hedge. */
+const UPDATE_SETTLE_MS = 250
+
// ── Types ─────────────────────────────────────────────────────
type DownloadStatus = 'idle' | 'downloading' | 'downloaded' | 'installing' | 'error'
@@ -247,6 +253,24 @@ export const useUpdateStore = create<UpdateState>()(
// lose by being early. Best effort: a failure here must not stop the
// update, the installer still has its own recovery.
await Promise.allSettled([stopBundledEngine(), stopBundledEmbed()])
+
+ // Put the chats on disk and go quiet BEFORE handing over. install()
+ // does not return: the installer takes the process down, and both
+ // coalesced stores can have a multi megabyte IndexedDB write in
+ // flight at that moment because the window only closes 250 ms after
+ // the last change. A LevelDB killed mid write is the most plausible
+ // mechanism behind aldrich_ironhart losing every chat across a 2.6.5
+ // update while sockenmonster on the same build lost none, and the
+ // bigger the history the wider that window.
+ //
+ // flush() resolves when the put has landed, so awaiting it is the
+ // real work. The pause after it is a hedge, not a guarantee: what
+ // the engine does with its own log and compaction after a commit is
+ // not something a page can await. A quarter second of an update the
+ // user already agreed to costs nothing.
+ await Promise.allSettled([flushChatPersist(), flushStagedPersist()])
+ await new Promise((r) => setTimeout(r, UPDATE_SETTLE_MS))
+
await _pendingUpdate.install()
// Exit so the installer can overwrite the binary
await backendCall('exit_app')