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): the update waits for the writes, saves a copy, and keeps more than one

purple3c29252675d4
diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs
index 476dcb43..e2803520 100644
--- a/src-tauri/src/commands/system.rs
+++ b/src-tauri/src/commands/system.rs
@@ -324,12 +324,118 @@ pub(crate) fn merged_backup(previous: &str, incoming: &str, lost: &[String]) ->
serde_json::Value::Object(next).to_string()
}
+/// How many rotated generations of the store backup are kept beside the live
+/// one. Three plus the live file plus store_backup.prev.json is a handful of
+/// megabytes on a big history, and it is the difference between one file
+/// standing between a user and their chats and several.
+pub(crate) const BACKUP_GENERATIONS: usize = 3;
+
+/// A generation is only cut when the newest one is at least this old. The
+/// backup triad fires every 5 s and after every chat mutation, so rotating on
+/// every write would burn through the whole ring in under a minute and leave
+/// three copies of the same instant.
+const ROTATE_AFTER_SECS: u64 = 30 * 60;
+
+/// Whether the ring should be shifted. `None` means there is no generation
+/// yet, which is the first rotation.
+pub(crate) fn should_rotate(newest_age: Option<std::time::Duration>) -> bool {
+ match newest_age {
+ None => true,
+ Some(age) => age.as_secs() >= ROTATE_AFTER_SECS,
+ }
+}
+
+/// The backup files a restore may read, newest first.
+///
+/// store_backup.prev.json comes last: it is the one set aside when a snapshot
+/// arrived with a key missing, so it is older than every generation, and it is
+/// only worth reading when nothing newer can be parsed at all.
+pub(crate) fn backup_candidates(dir: &std::path::Path) -> Vec<std::path::PathBuf> {
+ let mut paths = vec![dir.join("store_backup.json")];
+ for i in 1..=BACKUP_GENERATIONS {
+ paths.push(dir.join(format!("store_backup.{i}.json")));
+ }
+ paths.push(dir.join("store_backup.prev.json"));
+ paths
+}
+
+/// A backup is worth restoring from when it parses as a JSON object that still
+/// carries at least one non-empty string value.
+///
+/// The rename below is atomic, so a half written file should not be reachable,
+/// but the payload is not on the platter yet when the rename lands unless the
+/// write was synced, and a machine that loses power there can come back with a
+/// zero length or garbled file under the right name. That is the same class of
+/// event that took the chats in the first place, so the restore path must not
+/// stop at the newest name and call it a day.
+pub(crate) fn is_usable_backup(raw: &str) -> bool {
+ let Ok(serde_json::Value::Object(map)) = serde_json::from_str::<serde_json::Value>(raw) else {
+ return false;
+ };
+ map.iter()
+ .any(|(k, v)| k != "__ts" && !v.as_str().unwrap_or("").is_empty())
+}
+
+/// The candidate to restore from: the first usable one in the order given, or
+/// the newest unusable one when the whole ring reads as nothing.
+///
+/// Handing an unusable file back rather than `None` keeps the caller's own "no
+/// backup at all" branch for the case it was written for, a machine that has
+/// never written one.
+///
+/// Lazy over the iterator on purpose: a full history is a multi megabyte file
+/// and there are up to five of them, so a healthy boot reads exactly one.
+pub(crate) fn pick_backup<I: IntoIterator<Item = String>>(candidates: I) -> Option<String> {
+ let mut newest: Option<String> = None;
+ for raw in candidates {
+ if is_usable_backup(&raw) {
+ return Some(raw);
+ }
+ if newest.is_none() {
+ newest = Some(raw);
+ }
+ }
+ newest
+}
+
+/// Copy the live backup into the ring and drop the oldest generation, but only
+/// when the newest generation has had time to age. Best effort throughout: a
+/// generation that cannot be written is not a reason to refuse the backup that
+/// actually matters.
+fn rotate_generations(dir: &std::path::Path) {
+ let live = dir.join("store_backup.json");
+ if !live.exists() {
+ return;
+ }
+ let newest = dir.join("store_backup.1.json");
+ let age = std::fs::metadata(&newest)
+ .ok()
+ .and_then(|m| m.modified().ok())
+ .and_then(|t| t.elapsed().ok());
+ if !should_rotate(if newest.exists() { age } else { None }) {
+ return;
+ }
+ for i in (1..BACKUP_GENERATIONS).rev() {
+ let from = dir.join(format!("store_backup.{i}.json"));
+ let to = dir.join(format!("store_backup.{}.json", i + 1));
+ if from.exists() {
+ let _ = std::fs::rename(&from, &to);
+ }
+ }
+ let _ = std::fs::copy(&live, &newest);
+}
+
/// 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.
+///
+/// The temp file is synced before the rename. Without that the rename can land
+/// while the bytes are still only in the page cache, and a hard kill there
+/// leaves a file with the right name and no usable contents, which is exactly
+/// the shape of failure this whole path exists to survive.
#[tauri::command]
pub fn backup_stores(data: String) -> Result<(), String> {
let dir = persistent_dir()?;
@@ -354,21 +460,28 @@ pub fn backup_stores(data: String) -> Result<(), String> {
merged_backup(&previous, &data, &lost)
};
- std::fs::write(&tmp, &payload).map_err(|e| os_error::english(&e))?;
+ rotate_generations(&dir);
+
+ {
+ use std::io::Write;
+ let mut file = std::fs::File::create(&tmp).map_err(|e| os_error::english(&e))?;
+ file.write_all(payload.as_bytes()).map_err(|e| os_error::english(&e))?;
+ file.sync_all().map_err(|e| os_error::english(&e))?;
+ }
std::fs::rename(&tmp, &target).map_err(|e| os_error::english(&e))?;
Ok(())
}
-/// Restore stores from %APPDATA% backup
+/// Restore stores from the %APPDATA% backup, falling back through the rotated
+/// generations when the newest file cannot be read as a backup at all.
#[tauri::command]
pub fn restore_stores() -> Result<Option<String>, String> {
- let path = persistent_dir()?.join("store_backup.json");
- if path.exists() {
- let data = std::fs::read_to_string(&path).map_err(|e| os_error::english(&e))?;
- Ok(Some(data))
- } else {
- Ok(None)
- }
+ let dir = persistent_dir()?;
+ Ok(pick_backup(
+ backup_candidates(&dir)
+ .into_iter()
+ .filter_map(|p| std::fs::read_to_string(p).ok()),
+ ))
}
/// Backup the IndexedDB RAG chunks (embedding vectors) to %APPDATA%.
@@ -699,4 +812,145 @@ mod tests {
assert!(SCREENSHOT_TIMEOUT >= std::time::Duration::from_secs(5));
assert!(SCREENSHOT_TIMEOUT <= std::time::Duration::from_secs(60));
}
+
+ // ── Bug A1 (2.6.7): more than one file stands between a user and their
+ // chats, and the newest name is not automatically the usable one.
+
+ fn scratch_dir(tag: &str) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!(
+ "lu-a1-{tag}-{}-{:?}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ /// aldrich_ironhart lost the chats to a boot that came back with the
+ /// IndexedDB gone. The file on disk was fine that time. It does not have
+ /// to be: the rename that publishes store_backup.json is atomic in name
+ /// only, the bytes are not on the platter until they are synced, and a
+ /// hard kill in that window leaves the right name over nothing readable.
+ ///
+ /// So the restore walks the ring instead of stopping at the newest name.
+ #[test]
+ fn a_newest_backup_that_reads_as_nothing_is_stepped_over() {
+ let corrupt = String::from("\u{0}\u{0}\u{0}");
+ let truncated = String::from("{\"chat-conversations\":\"{\\\"chats");
+ let good = String::from(r#"{"__ts":"older","chat-conversations":"{\"chats\":42}"}"#);
+
+ let picked = pick_backup([corrupt.clone(), truncated.clone(), good.clone()]);
+ assert_eq!(picked.as_deref(), Some(good.as_str()));
+
+ // And a ring where nothing is usable still answers with the newest
+ // file, so the caller's "no backup at all" branch stays reserved for a
+ // machine that has never written one.
+ assert_eq!(
+ pick_backup([corrupt.clone(), truncated.clone()]).as_deref(),
+ Some(corrupt.as_str())
+ );
+ assert_eq!(pick_backup(Vec::<String>::new()), None);
+
+ // NEGATIVE CONTROL: the old rule was "read store_backup.json, hand it
+ // over". On this disk that is the corrupt file, and the chats sitting
+ // one generation away are never looked at.
+ let old_rule = corrupt.clone();
+ assert!(!is_usable_backup(&old_rule));
+ assert!(!old_rule.contains("chat-conversations"));
+ }
+
+ /// A backup with nothing but its own timestamp in it is not a backup. It
+ /// is what a boot with wiped storage would produce, and restoring from it
+ /// would be the loss all over again.
+ #[test]
+ fn a_snapshot_with_only_a_timestamp_is_not_usable() {
+ assert!(!is_usable_backup(r#"{"__ts":"2026-08-28T00:00:00.000Z"}"#));
+ assert!(!is_usable_backup(r#"{"__ts":"x","chat-conversations":""}"#));
+ assert!(!is_usable_backup(""));
+ assert!(!is_usable_backup("[1,2,3]"));
+ assert!(is_usable_backup(r#"{"__ts":"x","chat-settings":"{}"}"#));
+ }
+
+ /// Newest first, and the file set aside before a loss is the last resort
+ /// rather than the first answer.
+ #[test]
+ fn the_candidate_order_runs_newest_to_oldest() {
+ let dir = std::path::Path::new("/nowhere");
+ let names: Vec<String> = backup_candidates(dir)
+ .iter()
+ .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
+ .collect();
+ assert_eq!(
+ names,
+ vec![
+ "store_backup.json",
+ "store_backup.1.json",
+ "store_backup.2.json",
+ "store_backup.3.json",
+ "store_backup.prev.json",
+ ]
+ );
+ }
+
+ /// The triad writes every 5 s and after every chat mutation. Rotating on
+ /// each of those would fill the ring with three copies of the same minute
+ /// and throw away the older states that make a ring worth having.
+ #[test]
+ fn the_ring_is_only_cut_when_the_newest_generation_has_aged() {
+ assert!(should_rotate(None));
+ assert!(!should_rotate(Some(std::time::Duration::from_secs(5))));
+ assert!(!should_rotate(Some(std::time::Duration::from_secs(60))));
+ assert!(should_rotate(Some(std::time::Duration::from_secs(ROTATE_AFTER_SECS))));
+ assert!(should_rotate(Some(std::time::Duration::from_secs(60 * 60 * 24))));
+ }
+
+ /// Shifting the ring keeps the agreed number of generations and no more.
+ #[test]
+ fn rotating_shifts_the_ring_and_drops_the_oldest() {
+ let dir = scratch_dir("rotate");
+ std::fs::write(dir.join("store_backup.json"), "live-1").unwrap();
+ rotate_generations(&dir);
+ assert_eq!(
+ std::fs::read_to_string(dir.join("store_backup.1.json")).unwrap(),
+ "live-1"
+ );
+
+ // A second rotation right away is refused, the newest generation is
+ // seconds old.
+ std::fs::write(dir.join("store_backup.json"), "live-2").unwrap();
+ rotate_generations(&dir);
+ assert_eq!(
+ std::fs::read_to_string(dir.join("store_backup.1.json")).unwrap(),
+ "live-1"
+ );
+
+ // Force the shifts the clock would otherwise take an hour and a half
+ // to allow, by moving the ring by hand the way rotate_generations does.
+ std::fs::rename(dir.join("store_backup.1.json"), dir.join("store_backup.2.json")).unwrap();
+ std::fs::write(dir.join("store_backup.1.json"), "gen-1").unwrap();
+ std::fs::write(dir.join("store_backup.3.json"), "gen-3").unwrap();
+ std::fs::remove_file(dir.join("store_backup.1.json")).unwrap();
+ std::fs::write(dir.join("store_backup.json"), "live-3").unwrap();
+ rotate_generations(&dir);
+
+ assert_eq!(std::fs::read_to_string(dir.join("store_backup.1.json")).unwrap(), "live-3");
+ assert_eq!(std::fs::read_to_string(dir.join("store_backup.3.json")).unwrap(), "live-1");
+ // BACKUP_GENERATIONS is the cap, nothing beyond it is written.
+ assert!(!dir.join(format!("store_backup.{}.json", BACKUP_GENERATIONS + 1)).exists());
+
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// Nothing to rotate must not create an empty generation that then reads
+ /// as a backup on the next boot.
+ #[test]
+ fn a_first_run_with_no_live_backup_writes_no_generation() {
+ let dir = scratch_dir("first");
+ rotate_generations(&dir);
+ assert!(!dir.join("store_backup.1.json").exists());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
}
diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsx
index 7701ed90..d9028089 100644
--- a/src/components/layout/AppShell.tsx
+++ b/src/components/layout/AppShell.tsx
@@ -24,6 +24,7 @@ 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 { STORE_KEYS, IDB_STORE_KEYS, collectStoreSnapshot } from '../../lib/store-backup'
import { idbKeysToRestore, mayReloadForIdbRestore } from '../../lib/idb-restore'
import { log } from '../../lib/logger'
import type { AIModel } from '../../types/models'
@@ -160,27 +161,10 @@ export function AppShell() {
}, [settings.comfyGpuMode])
// ── Store backup/restore: survive NSIS updates that wipe WebView2 data ──
- const STORE_KEYS = [
- 'chat-conversations', 'chat-settings', 'chat-models', 'lu-providers',
- 'create-store', 'locally-uncensored-codex',
- 'locally-uncensored-permissions', 'locally-uncensored-mcp-servers',
- 'locally-uncensored-agent-mode', 'locally-uncensored-memory',
- 'locally-uncensored-agent-workflows', 'locally-uncensored-agent',
- 'locally-uncensored-voice', 'lu-benchmark-store', 'lu-update-checker-v2',
- 'rag-store', 'workflow-store', 'lu-cloud-catalog',
- // One-shot notices — back these up so "seen it once" survives an NSIS
- // update that wipes WebView2 localStorage. `lu_cloud_notice` (the Create
- // retention line) claimed in its own comment that it survived an update
- // and did not, because it was never listed here.
- 'lu_cloud_notice', 'locally-uncensored-model-health',
- // The standing goal (/goal) is per conversation and outlives a session.
- 'locally-uncensored-agent-goal',
- ]
+ // The key lists and the snapshot builder live in lib/store-backup so the
+ // update path can ask for a backup too. It used to hand the process to the
+ // installer with whatever the 5 s interval last wrote (Bug A1, 2.6.7).
const STORE_KEYS_SET = new Set(STORE_KEYS)
- // These two persist via idbStorage (IndexedDB) since v2.5.0 — the backup
- // snapshot must read them from there; their localStorage copy is deleted by
- // the one-time idb migration, so localStorage.getItem returns nothing.
- const IDB_STORE_KEYS = new Set(['chat-conversations', 'locally-uncensored-memory'])
// Feature FF: reserved key under which memory embeddings ride inside the RAG
// chunk backup file. Never collides with a real documentId (those are UUIDs).
@@ -406,16 +390,7 @@ export function AppShell() {
if (backupInflight) return
backupInflight = true
try {
- const snapshot: Record<string, string> = { __ts: new Date().toISOString() }
- for (const key of STORE_KEYS) {
- const val = IDB_STORE_KEYS.has(key)
- ? await Promise.resolve(idbStorage.getItem(key))
- : localStorage.getItem(key)
- if (val) {
- snapshot[key] = val
- if (IDB_STORE_KEYS.has(key)) idbCache[key] = val
- }
- }
+ const snapshot = await collectStoreSnapshot(idbCache)
// Always fire — we want backup even if snapshot is mostly empty, and the
// sentinel tells the restore-flow this is a valid backup.
localStorage.setItem('lu-restore-complete', '1')
diff --git a/src/lib/store-backup.ts b/src/lib/store-backup.ts
new file mode 100644
index 00000000..640f2fdd
--- /dev/null
+++ b/src/lib/store-backup.ts
@@ -0,0 +1,84 @@
+/**
+ * The store snapshot that goes to %APPDATA%/store_backup.json, and the two
+ * things a caller ever wants from it: the list of keys, and "write one now".
+ *
+ * WHY IT MOVED OUT OF AppShell (Bug A1, 2.6.7). The backup was reachable only
+ * from the component that owns the triad, so the update path could not ask for
+ * one. It handed the process to the installer with whatever the last interval
+ * happened to have written, up to five seconds and a whole answer old. The
+ * moment a self update is about to take the process down is the single most
+ * valuable moment to have a current copy of the chats on disk, and it was the
+ * one moment nothing asked for one.
+ *
+ * aldrich_ironhart, 2.6.5, Discord #general 18.08.: "has anyone lost their
+ * chats after a restart??", then "My code chats are vaporised", a coding chat
+ * around 230k tokens. sockenmonster on the same build lost nothing.
+ */
+import { backendCall } from '../api/backend'
+import { idbStorage } from './idbStorage'
+
+/** Every store that is worth carrying across an update or a wiped WebView2
+ * profile. Order is irrelevant, presence is not: a key missing from this list
+ * is a store that silently does not survive, which is how `lu_cloud_notice`
+ * came back on every update while its own comment claimed it did not. */
+export const STORE_KEYS = [
+ 'chat-conversations', 'chat-settings', 'chat-models', 'lu-providers',
+ 'create-store', 'locally-uncensored-codex',
+ 'locally-uncensored-permissions', 'locally-uncensored-mcp-servers',
+ 'locally-uncensored-agent-mode', 'locally-uncensored-memory',
+ 'locally-uncensored-agent-workflows', 'locally-uncensored-agent',
+ 'locally-uncensored-voice', 'lu-benchmark-store', 'lu-update-checker-v2',
+ 'rag-store', 'workflow-store', 'lu-cloud-catalog',
+ 'lu_cloud_notice', 'locally-uncensored-model-health',
+ 'locally-uncensored-agent-goal',
+]
+
+/** These two persist through idbStorage (IndexedDB) since 2.5.0, because the
+ * 5 MB localStorage cap could not hold a real history. The snapshot has to
+ * read them from there: the one-time migration deleted their localStorage
+ * copy, so localStorage.getItem answers nothing. */
+export const IDB_STORE_KEYS = new Set(['chat-conversations', 'locally-uncensored-memory'])
+
+/**
+ * Read every store into one flat object.
+ *
+ * @param idbCache when given, every IndexedDB value read is mirrored into it,
+ * so a caller that later has to build a snapshot without awaiting
+ * anything (beforeunload) has something to read from.
+ */
+export async function collectStoreSnapshot(
+ idbCache?: Record<string, string>,
+): Promise<Record<string, string>> {
+ const snapshot: Record<string, string> = { __ts: new Date().toISOString() }
+ for (const key of STORE_KEYS) {
+ const val = IDB_STORE_KEYS.has(key)
+ ? await Promise.resolve(idbStorage.getItem(key))
+ : localStorage.getItem(key)
+ if (val) {
+ snapshot[key] = val
+ if (idbCache && IDB_STORE_KEYS.has(key)) idbCache[key] = val
+ }
+ }
+ return snapshot
+}
+
+/**
+ * Build a snapshot and write it, and resolve only once the file is on disk.
+ *
+ * The triad's own backup is fire and forget on purpose, it must never hold up
+ * a render. This one is awaited, because its whole reason to exist is the
+ * caller that is about to end the process.
+ *
+ * Returns whether the file was written. Never throws: a backup that fails is
+ * not a reason to refuse an update the user already agreed to.
+ */
+export async function backupStoresNow(): Promise<boolean> {
+ try {
+ const snapshot = await collectStoreSnapshot()
+ localStorage.setItem('lu-restore-complete', '1')
+ await backendCall('backup_stores', { data: JSON.stringify(snapshot) })
+ return true
+ } catch {
+ return false
+ }
+}
diff --git a/src/stores/__tests__/update-waits-but-not-forever.test.ts b/src/stores/__tests__/update-waits-but-not-forever.test.ts
new file mode 100644
index 00000000..6a1c510b
--- /dev/null
+++ b/src/stores/__tests__/update-waits-but-not-forever.test.ts
@@ -0,0 +1,184 @@
+/**
+ * Bug A1 (2.6.7), the two halves the 2.6.5 fix left standing.
+ *
+ * aldrich_ironhart on 2.6.5, Discord #general 18.08.: "has anyone lost their
+ * chats after a restart??", then "My code chats are vaporised", a coding chat
+ * around 230k tokens. sockenmonster on the same build lost nothing.
+ *
+ * The update path already flushes the coalesced stores before it hands the
+ * process to the installer. Two things were still wrong with that.
+ *
+ * ONE. It awaited the flush with no deadline. flush() resolves when the
+ * IndexedDB put has landed, and on a database that is blocked, broken or out
+ * of room the put never lands and the promise never settles. That is not an
+ * exotic case here, it is the population this whole fix is aimed at: the
+ * machines whose IndexedDB is already in trouble. The button became a spinner
+ * that never came back, and the way out of that is the user killing the app,
+ * which is the exact hard kill the flush exists to avoid.
+ *
+ * TWO. Nothing wrote a fresh file backup before handing over. The backup triad
+ * writes %APPDATA%/store_backup.json every 5 s and 1 s after a chat mutation,
+ * so what survived an update was whatever the interval happened to catch. The
+ * instant before a self update is the most valuable moment there is to have a
+ * current copy outside the WebView2 profile, and it was the one moment nobody
+ * asked for one.
+ *
+ * Run: npx vitest run src/stores/__tests__/update-waits-but-not-forever.test.ts
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } 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') }),
+}))
+
+vi.mock('../../lib/logger', () => ({
+ log: { warn: vi.fn((m: string) => { calls.push(`warn:${m}`) }), error: vi.fn(), info: vi.fn(), debug: vi.fn() },
+}))
+
+let chatFlush: () => Promise<void> = async () => { calls.push('flush:chat') }
+vi.mock('../chatStore', () => ({ flushChatPersist: () => chatFlush() }))
+vi.mock('../stagedChangesStore', () => ({ flushStagedPersist: async () => { calls.push('flush:staged') } }))
+
+let backupNow: () => Promise<boolean> = async () => { calls.push('backup'); return true }
+vi.mock('../../lib/store-backup', () => ({ backupStoresNow: () => backupNow() }))
+
+vi.mock('../../../package.json', () => ({ version: '2.6.6' }))
+
+const install = vi.fn(async () => { calls.push('install') })
+
+vi.mock('@tauri-apps/plugin-updater', () => ({
+ check: vi.fn(async () => ({ version: '2.6.7', body: 'notes', install, download: vi.fn() })),
+}))
+
+import { useUpdateStore, settledOrTimedOut } from '../updateStore'
+
+/** A promise that is never going to settle, which is what a put into a broken
+ * IndexedDB looks like from here. */
+function neverSettles(): Promise<void> {
+ return new Promise<void>(() => {})
+}
+
+async function armPendingUpdate() {
+ await useUpdateStore.getState().checkForUpdate(true)
+}
+
+function reset() {
+ calls.length = 0
+ install.mockClear()
+ chatFlush = async () => { calls.push('flush:chat') }
+ backupNow = async () => { calls.push('backup'); return true }
+ useUpdateStore.setState({
+ downloadStatus: 'downloaded',
+ autoDownload: false,
+ lastChecked: null,
+ latestVersion: null,
+ updateAvailable: false,
+ errorMessage: null,
+ })
+}
+
+describe('the update waits for the chats to be written, but not forever', () => {
+ beforeEach(reset)
+ afterEach(() => { vi.useRealTimers() })
+
+ it('a flush that never settles does not stop the update', async () => {
+ await armPendingUpdate()
+ reset()
+ chatFlush = neverSettles
+
+ vi.useFakeTimers()
+ const running = useUpdateStore.getState().installAndRestart()
+ // Everything the deadline plus the settle pause can possibly need.
+ await vi.advanceTimersByTimeAsync(30_000)
+ await running
+
+ expect(install).toHaveBeenCalledTimes(1)
+ expect(useUpdateStore.getState().downloadStatus).not.toBe('error')
+ // And it said so, rather than pretending the write had landed.
+ expect(calls.some((c) => c.startsWith('warn:'))).toBe(true)
+ })
+
+ it('NEGATIVE CONTROL: the old rule was a bare await, and it never reached install', async () => {
+ // Exactly what the code did before: allSettled over the flushes with no
+ // deadline. allSettled needs every input to settle, so one that does not
+ // hangs the whole handover. Nothing else about the path changed.
+ vi.useFakeTimers()
+ let reached = false
+ const oldRule = (async () => {
+ await Promise.allSettled([neverSettles(), Promise.resolve()])
+ reached = true
+ })()
+ void oldRule
+ await vi.advanceTimersByTimeAsync(30_000)
+ expect(reached).toBe(false)
+
+ // The new rule, over the same never-settling flush, comes back.
+ const verdict = settledOrTimedOut(Promise.allSettled([neverSettles(), Promise.resolve()]), 10_000)
+ await vi.advanceTimersByTimeAsync(10_001)
+ expect(await verdict).toBe('timeout')
+ })
+
+ it('writes a fresh backup to disk before it hands the process over', async () => {
+ await armPendingUpdate()
+ reset()
+
+ await useUpdateStore.getState().installAndRestart()
+
+ expect(calls).toContain('backup')
+ expect(calls.indexOf('backup')).toBeLessThan(calls.indexOf('install'))
+ // And after the flush, not before it: backing up a store whose newest
+ // messages are still sitting in the coalescing window would snapshot the
+ // history the user is trying to keep, minus the last thing they said.
+ expect(calls.indexOf('flush:chat')).toBeLessThan(calls.indexOf('backup'))
+ })
+
+ it('NEGATIVE CONTROL: without the pre-update backup nothing writes a file on this path', async () => {
+ // What 2.6.6 did: stop the sidecars, flush the two stores, pause, install.
+ // Not one of those puts anything in %APPDATA%, so the copy that had to
+ // survive the update was whatever the 5 s triad interval last caught.
+ await armPendingUpdate()
+ reset()
+ // Stand the old path back up by making the backup a no-op.
+ backupNow = async () => true
+
+ await useUpdateStore.getState().installAndRestart()
+
+ const before = calls.slice(0, calls.indexOf('install'))
+ expect(before).not.toContain('backup')
+ expect(before.filter((c) => c.startsWith('backend:'))).toHaveLength(0)
+ })
+
+ it('a backup that never answers does not stop the update either', async () => {
+ await armPendingUpdate()
+ reset()
+ backupNow = () => neverSettles() as unknown as Promise<boolean>
+
+ vi.useFakeTimers()
+ const running = useUpdateStore.getState().installAndRestart()
+ await vi.advanceTimersByTimeAsync(30_000)
+ await running
+
+ expect(install).toHaveBeenCalledTimes(1)
+ expect(useUpdateStore.getState().downloadStatus).not.toBe('error')
+ })
+
+ it('settledOrTimedOut answers on a rejection instead of passing it on', async () => {
+ // The caller wants to know it may proceed, not what went wrong. A throw
+ // out of here would land in installAndRestart's catch and turn a failed
+ // write into "The update could not be installed."
+ await expect(settledOrTimedOut(Promise.reject(new Error('idb gone')), 1_000)).resolves.toBe('settled')
+ await expect(settledOrTimedOut(Promise.resolve(1), 1_000)).resolves.toBe('settled')
+ })
+})
diff --git a/src/stores/updateStore.ts b/src/stores/updateStore.ts
index 411da312..a8036f92 100644
--- a/src/stores/updateStore.ts
+++ b/src/stores/updateStore.ts
@@ -1,17 +1,55 @@
import { create } from 'zustand'
import { withDetail } from '../lib/error-text'
+import { log } from '../lib/logger'
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'
+// Static on purpose. The next thing that happens after this is called is an
+// installer overwriting the binary, which is the worst imaginable moment to be
+// fetching a chunk off disk for the first time.
+import { backupStoresNow } from '../lib/store-backup'
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
+/** How long the update waits for the persistence layer before it gives up and
+ * hands over anyway.
+ *
+ * flush() resolves when the IndexedDB put has landed, and an IndexedDB put
+ * does not always land. A blocked upgrade, a database Chromium has already
+ * decided is broken, a disk that is full: in every one of those the promise
+ * simply never settles, and `await` on it is forever. Without a deadline the
+ * update button turns into a spinner that never comes back, on exactly the
+ * machines whose storage is in trouble, which is to say on aldrich's. Ten
+ * seconds is far beyond a healthy multi megabyte write and short enough that
+ * nobody thinks the app has died.
+ *
+ * Same reasoning for the pre-update backup: it is worth waiting for, it is
+ * not worth waiting for forever. */
+const UPDATE_FLUSH_TIMEOUT_MS = 10_000
+
+/**
+ * Resolve when `work` resolves, or after `ms`, whichever comes first, and
+ * never reject. The caller wants to know it may proceed, not what happened.
+ *
+ * Exported for the test: a flush that never settles is not something a store
+ * can be talked into from the outside.
+ */
+export function settledOrTimedOut(work: Promise<unknown>, ms: number): Promise<'settled' | 'timeout'> {
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => resolve('timeout'), ms)
+ work.then(
+ () => { clearTimeout(timer); resolve('settled') },
+ () => { clearTimeout(timer); resolve('settled') },
+ )
+ })
+}
+
// ── Types ─────────────────────────────────────────────────────
type DownloadStatus = 'idle' | 'downloading' | 'downloaded' | 'installing' | 'error'
@@ -269,7 +307,29 @@ export const useUpdateStore = create<UpdateState>()(
// 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()])
+ //
+ // Under a deadline, though. An IndexedDB write that never settles is
+ // not a hypothetical on a database that is already in trouble, and
+ // `await` on it would leave the user staring at "installing" until
+ // they kill the app, which is the very kill this path exists to
+ // avoid (Bug A1, 2.6.7).
+ const flushed = await settledOrTimedOut(
+ Promise.allSettled([flushChatPersist(), flushStagedPersist()]),
+ UPDATE_FLUSH_TIMEOUT_MS,
+ )
+ if (flushed === 'timeout') {
+ log.warn('[update] the persisted stores did not finish writing before the install, going ahead with the file backup')
+ }
+
+ // Then put a copy on disk that does NOT live in the WebView2 profile.
+ // The backup triad writes one every 5 s, so what survives an update
+ // is whatever the interval last caught, up to a whole answer old.
+ // This is the moment that copy is worth the most, because the next
+ // thing that happens is a process kill, and it is the one moment
+ // nothing used to ask for one. Awaited, so the file is on disk
+ // before the installer arrives, and under the same deadline.
+ await settledOrTimedOut(backupStoresNow(), UPDATE_FLUSH_TIMEOUT_MS)
+
await new Promise((r) => setTimeout(r, UPDATE_SETTLE_MS))
await _pendingUpdate.install()