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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(chat): a chat list that lost its chats no longer takes them out of the backup, and they can be restored
purple995ff7f6ab85
diff --git a/dev-server/__tests__/mlx-media-endpoint-coverage.test.ts b/dev-server/__tests__/mlx-media-endpoint-coverage.test.tsindex ebdb45df..6fb452ed 100644--- a/dev-server/__tests__/mlx-media-endpoint-coverage.test.ts+++ b/dev-server/__tests__/mlx-media-endpoint-coverage.test.ts@@ -220,6 +220,8 @@ describe('endpointMap covers every backendCall/invokeMedia site the frontend can// The tray menu's lines and memory figure (T2, 3.0.9, hooks/useTraySync.ts).// Sent only behind isTauri(): the browser build has no tray.'tray_memory', 'tray_update',+ // Restore chats from backup (3.0.10): reads store_backup*.json, only behind isTauri().+ 'chat_backup_conversations','exit_app', 'file_read', 'find_orphan_downloads', 'fix_comfyui_cors', 'funnel_ping','get_comfy_gpu_status', 'get_current_time', 'import_local_model', 'install_character_trainer','install_lmstudio', 'install_lmstudio_status', 'install_method', 'install_python',diff --git a/src-tauri/src/commands/chat_attachments.rs b/src-tauri/src/commands/chat_attachments.rsindex e3401e99..07f3f54c 100644--- a/src-tauri/src/commands/chat_attachments.rs+++ b/src-tauri/src/commands/chat_attachments.rs@@ -31,7 +31,7 @@ use std::sync::Mutex;use std::time::{Duration, Instant};pub(crate) const PREFIX: &str = "lu-attachment:v1:";-const CHAT_KEY: &str = "chat-conversations";+pub(crate) const CHAT_KEY: &str = "chat-conversations";pub(crate) fn attachment_dir() -> Result<PathBuf, String> {Ok(crate::commands::system::persistent_dir()?.join("chat-attachments"))@@ -99,7 +99,7 @@ pub async fn read_chat_attachment(id: String) -> Result<String, String> {/// Replace every inline image in a list of conversations by a reference./// An image whose file cannot be written keeps its inline data: slower, never/// lost. Returns how many images moved.-fn externalize_conversations(conversations: &mut Value, dir: &Path) -> usize {+pub(crate) fn externalize_conversations(conversations: &mut Value, dir: &Path) -> usize {let mut moved = 0;let Some(list) = conversations.as_array_mut() else { return 0 };for conversation in list {@@ -150,6 +150,14 @@ pub(crate) fn externalize_store_backup(raw: &str, dir: &Path) -> Option<String>/// hands the file back in the same shape.pub(crate) fn externalize_import(raw: &str, dir: &Path) -> Result<String, String> {let mut data: Value = serde_json::from_str(raw).map_err(|_| "That file is not valid JSON.".to_string())?;+ // A store backup (store_backup*.json from the app data folder, perhaps+ // copied back from a rescue folder, 3.0.10): its chats are a JSON string+ // under chat-conversations. They are handed on as a plain list, the shape+ // the import already reads, and the rest of the backup stays out of it.+ if let Some(chat) = data.get(CHAT_KEY).and_then(Value::as_str) {+ let inner: Value = serde_json::from_str(chat).map_err(|_| "The chats in that backup could not be read.".to_string())?;+ data = inner.pointer("/state/conversations").filter(|v| v.is_array()).cloned().unwrap_or(Value::Array(Vec::new()));+ }if data.is_array() {externalize_conversations(&mut data, dir);} else if let Some(list) = data.get_mut("conversations").filter(|v| v.is_array()) {@@ -590,6 +598,19 @@ mod tests {assert!(externalize_store_backup(r#"{"settings":"{}"}"#, dir.path()).is_none());}+ /// A store_backup*.json picked in "Import chats" comes out as the plain+ /// list of its chats (3.0.10, Restore chats from backup).+ #[test]+ fn a_store_backup_imports_as_its_chat_list() {+ let dir = tempfile::tempdir().unwrap();+ let chat = serde_json::json!({ "state": { "conversations": [{ "id": "a", "title": "a", "messages": [] }] } });+ let raw = serde_json::json!({ "__ts": "x", CHAT_KEY: chat.to_string(), "chat-settings": "{}" }).to_string();+ let out: Value = serde_json::from_str(&externalize_import(&raw, dir.path()).unwrap()).unwrap();+ assert_eq!(out, serde_json::json!([{ "id": "a", "title": "a", "messages": [] }]));+ let garbled = serde_json::json!({ CHAT_KEY: "not json" }).to_string();+ assert!(externalize_import(&garbled, dir.path()).is_err());+ }+#[test]fn import_accepts_all_three_shapes() {let dir = tempfile::tempdir().unwrap();diff --git a/src-tauri/src/commands/mobile_guard.rs b/src-tauri/src/commands/mobile_guard.rsindex eecf4cb8..f31d69ec 100644--- a/src-tauri/src/commands/mobile_guard.rs+++ b/src-tauri/src/commands/mobile_guard.rs@@ -195,6 +195,7 @@ pub const ALLOWED: &[&str] = &["get_current_time","backup_stores","restore_stores",+ "chat_backup_conversations","backup_rag_chunks","restore_rag_chunks","saved_characters_backup_missing",diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rsindex f868399c..5ace1277 100644--- a/src-tauri/src/commands/system.rs+++ b/src-tauri/src/commands/system.rs@@ -542,9 +542,216 @@ pub(crate) fn backup_candidates(dir: &std::path::Path) -> Vec<std::path::PathBufpaths.push(dir.join(format!("store_backup.{i}.json")));}paths.push(dir.join("store_backup.prev.json"));+ // The chat archives (archive_dropped_chats) come after everything else:+ // each one is a whole backup from before chats left the store, so it is+ // older than the live file and the ring. Listing them here also keeps the+ // attachment collector from deleting the images their chats point at.+ paths.extend(chat_archives(dir));paths}+/// How many chat archives (`store_backup.chats-<ms>.json`) are kept.+pub(crate) const CHAT_ARCHIVES_KEPT: usize = 5;++const CHAT_ARCHIVE_PREFIX: &str = "store_backup.chats-";++/// The chat archives in `dir`, newest first. A folder that cannot be listed+/// has none.+pub(crate) fn chat_archives(dir: &std::path::Path) -> Vec<std::path::PathBuf> {+ let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };+ let mut found: Vec<(u128, std::path::PathBuf)> = entries+ .filter_map(|e| e.ok())+ .filter_map(|e| {+ let name = e.file_name().to_string_lossy().into_owned();+ let stamp = name.strip_prefix(CHAT_ARCHIVE_PREFIX)?.strip_suffix(".json")?.parse::<u128>().ok()?;+ Some((stamp, e.path()))+ })+ .collect();+ found.sort_by_key(|f| std::cmp::Reverse(f.0));+ found.into_iter().map(|(_, p)| p).collect()+}++/// The conversation list inside a backup file's `chat-conversations` value.+/// None when the file, the value or the list cannot be read.+fn backup_conversation_list(backup: &str) -> Option<Vec<serde_json::Value>> {+ let outer: serde_json::Value = serde_json::from_str(backup).ok()?;+ let chat = outer.get(crate::commands::chat_attachments::CHAT_KEY)?.as_str()?;+ let mut inner: serde_json::Value = serde_json::from_str(chat).ok()?;+ match inner.pointer_mut("/state/conversations")?.take() {+ serde_json::Value::Array(list) => Some(list),+ _ => None,+ }+}++/// The conversation ids in a backup file. None when there is no readable list.+///+/// Runs on every backup write, so it reads into typed shapes that skip+/// everything but the ids instead of building the whole history as a Value.+fn backup_chat_ids(backup: &str) -> Option<std::collections::HashSet<String>> {+ #[derive(serde::Deserialize)]+ struct Outer {+ #[serde(rename = "chat-conversations")]+ chat: Option<String>,+ }+ #[derive(serde::Deserialize)]+ struct Blob {+ state: Option<State>,+ }+ #[derive(serde::Deserialize)]+ struct State {+ conversations: Option<Vec<Option<Entry>>>,+ }+ #[derive(serde::Deserialize)]+ struct Entry {+ id: Option<serde_json::Value>,+ }+ let outer: Outer = serde_json::from_str(backup).ok()?;+ let blob: Blob = serde_json::from_str(&outer.chat?).ok()?;+ let list = blob.state?.conversations?;+ Some(+ list.into_iter()+ .flatten()+ .filter_map(|c| c.id.and_then(|v| v.as_str().map(str::to_string)))+ .collect(),+ )+}++/// The conversation ids the previous backup had and the one about to replace+/// it has not.+///+/// perrt, Discord 05.11.2026, 3.0.8: the chat store came back empty, the+/// merge in `merged_backup` kept the chats while the key was missing, and the+/// moment the store wrote a fresh, nearly empty list the next snapshot carried+/// a valid value again and replaced the only complete copy. A missing key is+/// not the only shape of a loss: a list without the old chats is one too.+///+/// An incoming snapshot without a chat value answers nothing here, that case+/// is the merge's (the old value stays in the file). An unreadable previous+/// list answers nothing as well, there is nothing to compare.+pub(crate) fn chat_ids_dropped(previous: &str, incoming: &str) -> Vec<String> {+ let Some(before) = backup_chat_ids(previous) else { return Vec::new() };+ let incoming_has_chats = serde_json::from_str::<serde_json::Value>(incoming)+ .ok()+ .and_then(|v| v.get(crate::commands::chat_attachments::CHAT_KEY).and_then(|c| c.as_str()).map(|s| !s.is_empty()))+ .unwrap_or(false);+ if !incoming_has_chats {+ return Vec::new();+ }+ let after = backup_chat_ids(incoming).unwrap_or_default();+ let mut dropped: Vec<String> = before.difference(&after).cloned().collect();+ dropped.sort();+ dropped+}++/// Keep the previous backup as a chat archive before chats leave it.+///+/// Not a judgement on whether the loss was wanted: deleting a chat drops its+/// id too, and the archive costs one file. When the newest archive already+/// holds every dropped chat nothing is written, so deleting chats one by one+/// does not rotate the archives through. At most `CHAT_ARCHIVES_KEPT` stay.+/// Returns the archive written, if any. Best effort: an archive that cannot be+/// written must not stop the backup itself.+pub(crate) fn archive_dropped_chats(+ dir: &std::path::Path,+ previous: &str,+ dropped: &[String],+ now_ms: u128,+) -> Option<std::path::PathBuf> {+ if dropped.is_empty() || previous.is_empty() {+ return None;+ }+ let archives = chat_archives(dir);+ if let Some(newest) = archives.first() {+ let held = std::fs::read_to_string(newest).ok().and_then(|raw| backup_chat_ids(&raw));+ if held.is_some_and(|ids| dropped.iter().all(|id| ids.contains(id))) {+ return None;+ }+ }+ // A name that is already taken (two writes in the same millisecond) moves+ // on rather than replacing an archive.+ let mut stamp = now_ms;+ let mut path = dir.join(format!("{CHAT_ARCHIVE_PREFIX}{stamp}.json"));+ while path.exists() {+ stamp += 1;+ path = dir.join(format!("{CHAT_ARCHIVE_PREFIX}{stamp}.json"));+ }+ let tmp = dir.join("store_backup.chats.tmp");+ let written = (|| -> std::io::Result<()> {+ use std::io::Write;+ let mut file = std::fs::File::create(&tmp)?;+ file.write_all(previous.as_bytes())?;+ file.sync_all()?;+ std::fs::rename(&tmp, &path)+ })();+ if let Err(e) = written {+ tracing::warn!("chat archive could not be written: {}", os_error::english(&e));+ let _ = std::fs::remove_file(&tmp);+ return None;+ }+ for old in chat_archives(dir).into_iter().skip(CHAT_ARCHIVES_KEPT) {+ let _ = std::fs::remove_file(old);+ }+ Some(path)+}++/// Every chat in every backup file (the live one, the ring, the file set aside+/// and the chat archives), one entry per id. Where several files hold the same+/// chat the copy with the newest `updatedAt` wins, on a tie the one with more+/// messages.+pub(crate) fn chats_in_backups(raws: impl IntoIterator<Item = String>) -> Vec<serde_json::Value> {+ let mut by_id: std::collections::HashMap<String, serde_json::Value> = std::collections::HashMap::new();+ let rank = |c: &serde_json::Value| {+ (+ c.get("updatedAt").and_then(|v| v.as_f64()).unwrap_or(0.0),+ c.get("messages").and_then(|v| v.as_array()).map(|m| m.len()).unwrap_or(0),+ )+ };+ for raw in raws {+ for chat in backup_conversation_list(&raw).unwrap_or_default() {+ let Some(id) = chat.get("id").and_then(|v| v.as_str()).map(str::to_string) else { continue };+ if !chat.get("messages").is_some_and(|m| m.is_array()) {+ continue;+ }+ let better = match by_id.get(&id) {+ None => true,+ Some(held) => {+ let (a, b) = (rank(&chat), rank(held));+ a.0 > b.0 || (a.0 == b.0 && a.1 > b.1)+ }+ };+ if better {+ by_id.insert(id, chat);+ }+ }+ }+ let mut list: Vec<serde_json::Value> = by_id.into_values().collect();+ let id_of = |c: &serde_json::Value| c.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();+ list.sort_by(|a, b| {+ rank(b).0.partial_cmp(&rank(a).0).unwrap_or(std::cmp::Ordering::Equal).then_with(|| id_of(a).cmp(&id_of(b)))+ });+ list+}++/// The chats of every backup file, for "Restore chats from backup" in+/// Settings and the hint at launch. The WebView decides which of them it is+/// missing. Inline images are moved into the attachment store here, natively,+/// like `restore_stores` does, so an old backup never reaches the renderer as+/// one huge string.+#[tauri::command]+pub async fn chat_backup_conversations() -> Result<String, String> {+ tauri::async_runtime::spawn_blocking(|| {+ let dir = persistent_dir()?;+ let raws = backup_candidates(&dir).into_iter().filter_map(|p| std::fs::read_to_string(p).ok());+ let mut list = serde_json::Value::Array(chats_in_backups(raws));+ if let Ok(attachments) = crate::commands::chat_attachments::attachment_dir() {+ crate::commands::chat_attachments::externalize_conversations(&mut list, &attachments);+ }+ Ok(list.to_string())+ })+ .await+ .map_err(|e| e.to_string())?+}+/// A backup is worth restoring from when it parses as a JSON object that still/// carries at least one non-empty string value.///@@ -646,6 +853,23 @@ pub fn backup_stores(data: String) -> Result<(), String> {merged_backup(&previous, &data, &lost)};+ // Chats that are about to leave the backup go to an archive first, see+ // chat_ids_dropped (perrt, 05.11.2026).+ let dropped = chat_ids_dropped(&previous, &payload);+ if !dropped.is_empty() {+ let now_ms = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_millis())+ .unwrap_or(0);+ if let Some(path) = archive_dropped_chats(&dir, &previous, &dropped, now_ms) {+ tracing::warn!(+ "{} chats left the chat store, the previous backup is kept as {}",+ dropped.len(),+ path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()+ );+ }+ }+rotate_generations(&dir);{@@ -1262,6 +1486,119 @@ mod tests {let _ = std::fs::remove_dir_all(&dir);}+ /// A backup file in the shape 3.0.8 writes: `chat-conversations` is the+ /// zustand blob as a string, with `state.conversations`.+ fn backup_with_chats(ids: &[&str]) -> String {+ let conversations: Vec<serde_json::Value> = ids+ .iter()+ .enumerate()+ .map(|(i, id)| serde_json::json!({ "id": id, "title": id, "createdAt": 1, "updatedAt": 10 + i, "messages": [] }))+ .collect();+ let chat = serde_json::json!({ "state": { "conversations": conversations, "activeConversationId": null } });+ serde_json::json!({ "__ts": "t", "chat-conversations": chat.to_string(), "chat-settings": "{}" }).to_string()+ }++ /// perrt, 05.11.2026: the merge kept the chats while the key was missing,+ /// then the store wrote a fresh list and the next snapshot replaced the+ /// only complete copy. The previous file now goes to an archive first.+ #[test]+ fn a_snapshot_whose_list_lost_chats_archives_the_previous_backup() {+ let dir = scratch_dir("chat-archive");+ let previous = backup_with_chats(&["a", "b", "c"]);+ let incoming = backup_with_chats(&["new"]);++ let dropped = chat_ids_dropped(&previous, &incoming);+ assert_eq!(dropped, vec!["a", "b", "c"]);+ // Negative control: the rule that decides the merge sees no loss here,+ // which is exactly how the chats went.+ assert!(keys_lost(&previous, &incoming).is_empty());++ let path = archive_dropped_chats(&dir, &previous, &dropped, 1000).expect("archived");+ assert_eq!(std::fs::read_to_string(&path).unwrap(), previous);+ assert_eq!(chat_archives(&dir), vec![path.clone()]);+ // And a restore and the attachment collector see it.+ assert!(backup_candidates(&dir).contains(&path));++ // The same chats dropped again: the newest archive has them, no new file.+ assert!(archive_dropped_chats(&dir, &previous, &["b".to_string()], 2000).is_none());+ assert_eq!(chat_archives(&dir).len(), 1);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn no_archive_without_a_dropped_chat() {+ let previous = backup_with_chats(&["a", "b"]);+ // Grown, unchanged, or a snapshot without the key (the merge's case).+ assert!(chat_ids_dropped(&previous, &backup_with_chats(&["a", "b", "c"])).is_empty());+ assert!(chat_ids_dropped(&previous, &previous).is_empty());+ assert!(chat_ids_dropped(&previous, r#"{"chat-settings":"{}"}"#).is_empty());+ // No previous list to compare with.+ assert!(chat_ids_dropped("", &backup_with_chats(&["a"])).is_empty());+ assert!(chat_ids_dropped(r#"{"chat-conversations":"garbled"}"#, &backup_with_chats(&[])).is_empty());+ }++ #[test]+ fn a_stray_null_in_the_list_does_not_hide_the_loss() {+ let chat = serde_json::json!({ "state": { "conversations": [null, { "id": "a", "messages": [] }] } });+ let previous = serde_json::json!({ "chat-conversations": chat.to_string() }).to_string();+ assert_eq!(chat_ids_dropped(&previous, &backup_with_chats(&[])), vec!["a"]);+ }++ #[test]+ fn only_the_newest_five_archives_stay() {+ let dir = scratch_dir("chat-archive-ring");+ for i in 0..7u128 {+ let id = format!("chat{i}");+ let previous = backup_with_chats(&[id.as_str()]);+ archive_dropped_chats(&dir, &previous, &[id], 100 + i).expect("archived");+ }+ let names: Vec<String> = chat_archives(&dir)+ .iter()+ .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())+ .collect();+ assert_eq!(names.len(), CHAT_ARCHIVES_KEPT);+ assert_eq!(names[0], "store_backup.chats-106.json");+ assert_eq!(names[4], "store_backup.chats-102.json");+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// Restore chats from backup: one entry per id across every file, the+ /// newest copy wins, entries without an id or messages are skipped.+ #[test]+ fn chats_in_backups_merges_every_file_by_id() {+ let live = backup_with_chats(&["new"]);+ let older = backup_with_chats(&["a", "b"]);+ let newer_b = serde_json::json!({+ "chat-conversations": serde_json::json!({ "state": { "conversations": [+ { "id": "b", "updatedAt": 99, "messages": [{ "id": "m" }] },+ { "id": "broken" },+ { "title": "no id", "messages": [] }+ ] } }).to_string()+ })+ .to_string();+ let list = chats_in_backups(vec![live, older, newer_b, "not json".to_string()]);+ let ids: Vec<&str> = list.iter().map(|c| c["id"].as_str().unwrap()).collect();+ assert_eq!(ids, vec!["b", "a", "new"]);+ assert_eq!(list[0]["updatedAt"], 99);+ }++ /// perrt's folder after five more hours: the ring holds only the two new+ /// chats, store_backup.prev.json the old ones. Both come back, side by side.+ #[test]+ fn the_file_set_aside_is_read_next_to_an_emptied_ring() {+ let dir = scratch_dir("rescue-prev");+ std::fs::write(dir.join("store_backup.json"), backup_with_chats(&["new1", "new2"])).unwrap();+ for i in 1..=BACKUP_GENERATIONS {+ std::fs::write(dir.join(format!("store_backup.{i}.json")), backup_with_chats(&["new1"])).unwrap();+ }+ std::fs::write(dir.join("store_backup.prev.json"), backup_with_chats(&["old1", "old2", "old3"])).unwrap();+ let raws = backup_candidates(&dir).into_iter().filter_map(|p| std::fs::read_to_string(p).ok());+ let mut ids: Vec<String> = chats_in_backups(raws).iter().map(|c| c["id"].as_str().unwrap().to_string()).collect();+ ids.sort();+ assert_eq!(ids, vec!["new1", "new2", "old1", "old2", "old3"]);+ 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]diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 50f7575e..0661a099 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -900,6 +900,7 @@ pub fn run() {#[cfg(desktop)]commands::gallery_files::trash_comfy_output,commands::system::restore_stores,+ commands::system::chat_backup_conversations,commands::system::backup_rag_chunks,commands::system::restore_rag_chunks,commands::system::exit_app,diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsxindex 9f9e8d61..623aa5d1 100644--- a/src/components/layout/AppShell.tsx+++ b/src/components/layout/AppShell.tsx@@ -40,7 +40,7 @@ import { extractMemoriesFromPair } from '../../hooks/useMemory'import { detectLocalBackends, type DetectedBackend } from '../../lib/backend-detector'import { whenRunsIdle } from '../../lib/run-idle'import { backendCall, isTauri } from '../../api/backend'-import { idbStorage, hasStoredItem } from '../../lib/idbStorage'+import { idbStorage, hasReadableItem } from '../../lib/idbStorage'import { recoverChatsFromBackup } from '../../lib/chat-backup-recovery'import { STORE_KEYS, IDB_STORE_KEYS, backupStoresIfChanged, flushSyncStoreBackup } from '../../lib/store-backup'import { idbKeysToRestore, mayReloadForIdbRestore } from '../../lib/idb-restore'@@ -65,6 +65,7 @@ import { RenderFixupModal } from '../create/experimental/RenderFixupModal'import { CommandPalette } from '../ui/CommandPalette'import { CreditsExhaustedModal } from './CreditsExhaustedModal'import { Titlebar } from './Titlebar'+import { ChatRescueHint } from './ChatRescueHint'import { HfLinkInbox } from '../models/HfLinkInbox'import { useNeuronFollowsPersona } from '../../hooks/useNeuronFollowsPersona'import { NEURONS_ENABLED } from '../../lib/features'@@ -420,14 +421,14 @@ export function AppShell() {try {const live: Record<string, string | null> = {}for (const key of IDB_STORE_KEYS) {- // Presence only. Only an absent store is restored, and reading- // the whole value here doubled the largest string at launch.- const present = await hasStoredItem(key)- live[key] = present === true- ? 'present'- : present === false- ? null- : await Promise.resolve(idbStorage.getItem(key)).catch(() => null)+ // A value hydration can use, not just a row (3.0.10, perrt):+ // a row that is no string, or a leftover localStorage copy,+ // used to count as present while the store hydrated empty, and+ // nothing was restored. A read that failed counts as present:+ // what could not be read must never be written over.+ const readable = await hasReadableItem(key)+ live[key] = readable === false ? null : 'present'+ if (readable === null) log.warn('[AppShell] could not read an IndexedDB store at launch, not restoring it', { key })}if (Object.values(live).some((v) => !v)) {const raw = await backendCall<string | null>('restore_stores')@@ -440,7 +441,10 @@ export function AppShell() {try {await Promise.resolve(idbStorage.setItem(key, (parsed as Record<string, string>)[key]))back++- } catch { /* one key failing must not stop the rest */ }+ } catch (err) {+ // One key failing must not stop the rest.+ log.warn('[AppShell] restoring an IndexedDB store from the appData backup failed', { key, err: String(err) })+ }}if (back > 0) {log.warn('[AppShell] IndexedDB stores were empty, restored from the appData backup', { keys: wanted })@@ -453,7 +457,12 @@ export function AppShell() {}}}- } catch { /* best-effort, the RAG restore below still runs */ }+ } catch (err) {+ // Best effort, the RAG restore below still runs. Said out loud+ // since 3.0.10: this branch failing silently is how a good backup+ // sat unused while the chats looked gone.+ log.warn('[AppShell] the IndexedDB restore at launch failed', { err: String(err) })+ }// Chats a failed IndexedDB save never kept, see chat-backup-recovery.ts.// Before resolveRestoreDecided below: the first backup must not// replace store_backup.json before it has been looked at.@@ -1185,6 +1194,8 @@ export function AppShell() {</button></div>)}+ {/* 3.0.10: the backup files hold chats the list does not (lib/chat-rescue.ts). */}+ <ChatRescueHint /><StorageQuotaToast /><div className="flex-1 flex overflow-hidden gap-2 p-2">{!isComparing && <Sidebar />}diff --git a/src/components/layout/ChatRescueHint.tsx b/src/components/layout/ChatRescueHint.tsxnew file mode 100644index 00000000..e600fda1--- /dev/null+++ b/src/components/layout/ChatRescueHint.tsx@@ -0,0 +1,84 @@+import { useEffect, useState } from 'react'+import { useChatStore } from '../../stores/chatStore'+import { isTauri } from '../../api/backend'+import {+ countRestorableChats, restoreChatsFromBackup, shouldShowRescueHint, readDismissedAt, rememberDismissed,+} from '../../lib/chat-rescue'++/** After the restore at launch has had its turn (it may reload the window). */+const LOOK_AFTER_MS = 4000++/**+ * The hint at launch (3.0.10): the backup files hold chats the chat list does+ * not. It only says so; the chats come back when the user presses Restore.+ * See lib/chat-rescue.ts for when it shows.+ */+export function ChatRescueHint() {+ const importConversations = useChatStore((s) => s.importConversations)+ const [count, setCount] = useState(0)+ const [busy, setBusy] = useState(false)+ const [done, setDone] = useState<string | null>(null)++ useEffect(() => {+ if (!isTauri()) return+ let gone = false+ const look = async () => {+ await new Promise<void>((resolve) => {+ if (useChatStore.persist.hasHydrated()) resolve()+ else useChatStore.persist.onFinishHydration(() => resolve())+ })+ await new Promise((r) => setTimeout(r, LOOK_AFTER_MS))+ if (gone) return+ const live = () => useChatStore.getState().conversations+ const restorable = await countRestorableChats(live)+ const storage = typeof localStorage !== 'undefined' ? localStorage : null+ if (!gone && shouldShowRescueHint(live().length, restorable, readDismissedAt(storage))) setCount(restorable)+ }+ look().catch(() => { /* no hint is the old behaviour */ })+ return () => { gone = true }+ }, [])++ if (count === 0 && !done) return null++ const dismiss = () => {+ rememberDismissed(typeof localStorage !== 'undefined' ? localStorage : null, count)+ setCount(0)+ setDone(null)+ }++ const restore = async () => {+ setBusy(true)+ try {+ const added = await restoreChatsFromBackup(() => useChatStore.getState().conversations, importConversations)+ setCount(0)+ setDone(`Restored ${added} chat${added === 1 ? '' : 's'} from the backup.`)+ } catch (err) {+ setDone(err instanceof Error ? err.message : 'Could not read the backup.')+ } finally {+ setBusy(false)+ }+ }++ return (+ <div data-testid="chat-rescue-hint" className="mx-2 mt-2 flex items-start gap-2 rounded-lg border border-gray-300 dark:border-white/10 bg-white dark:bg-white/[0.04] px-3 py-2">+ <p role="status" className="flex-1 t-micro leading-snug text-gray-700 dark:text-gray-200">+ {done ?? `Your backup holds ${count} chat${count === 1 ? '' : 's'} that ${count === 1 ? 'is' : 'are'} not in your chat list. Restore ${count === 1 ? 'it' : 'them'}? Chats that are here stay as they are.`}+ </p>+ {!done && (+ <button+ onClick={() => void restore()}+ disabled={busy}+ className="shrink-0 t-micro font-medium text-gray-900 dark:text-white hover:underline disabled:opacity-50"+ >+ {busy ? 'Restoring...' : 'Restore'}+ </button>+ )}+ <button+ onClick={dismiss}+ className="shrink-0 t-micro text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition-colors"+ >+ {done ? 'Close' : 'Dismiss'}+ </button>+ </div>+ )+}diff --git a/src/components/settings/ChatBackupSettings.tsx b/src/components/settings/ChatBackupSettings.tsxindex 3813b5e2..66f79105 100644--- a/src/components/settings/ChatBackupSettings.tsx+++ b/src/components/settings/ChatBackupSettings.tsx@@ -1,8 +1,9 @@-import { useRef, useState } from 'react'-import { Download, Upload } from 'lucide-react'+import { useEffect, useRef, useState } from 'react'+import { Download, Upload, History } from 'lucide-react'import { useChatStore } from '../../stores/chatStore'import { exportAllConversations, parseImportedChats, missingImagesNote } from '../../lib/chat-export'import { backendCall, isTauri } from '../../api/backend'+import { countRestorableChats, restoreChatsFromBackup } from '../../lib/chat-rescue'/*** Chat Backup (a user 2026-06-28) — export ALL conversations to one JSON file@@ -97,6 +98,90 @@ export function ChatBackupSettings() {<input ref={fileRef} type="file" accept=".json,application/json" onChange={handleImport} className="hidden" /></div>{msg && <div className="text-[0.6rem] text-gray-500 dark:text-gray-400">{msg}</div>}+ {isTauri() && <RestoreFromBackup />}+ </div>+ )+}++/**+ * Restore chats from backup (3.0.10). LU keeps several copies of its stores+ * in the app data folder; this reads all of them and puts back every chat the+ * list here does not have. Chats that are here stay as they are.+ */+function RestoreFromBackup() {+ const importConversations = useChatStore((s) => s.importConversations)+ const liveCount = useChatStore((s) => s.conversations.length)+ const [found, setFound] = useState<number | null>(null)+ const [busy, setBusy] = useState(false)+ const [note, setNote] = useState('')++ useEffect(() => {+ let gone = false+ countRestorableChats(() => useChatStore.getState().conversations)+ .then((n) => { if (!gone) setFound(n) })+ .catch(() => { if (!gone) setFound(0) })+ return () => { gone = true }+ }, [liveCount])++ const restore = async () => {+ setBusy(true)+ try {+ const added = await restoreChatsFromBackup(() => useChatStore.getState().conversations, importConversations)+ setNote(added > 0 ? `Restored ${added} chat${added === 1 ? '' : 's'} from the backup.` : 'Nothing to restore, every chat in the backup is already here.')+ } catch (err) {+ setNote(err instanceof Error ? err.message : 'Could not read the backup.')+ } finally {+ setBusy(false)+ }+ }++ // A backup the user kept somewhere else (copied out of the app data folder,+ // for example into a rescue folder on the desktop). Read natively, so a+ // store_backup*.json reaches the WebView as its chat list (externalize_import).+ const pickFile = async () => {+ setBusy(true)+ try {+ const content = await backendCall<string | null>('import_chats_dialog')+ if (!content) return+ const { added, skipped } = importConversations(parseImportedChats(content), 'merge')+ setNote(added > 0+ ? `Restored ${added} chat${added === 1 ? '' : 's'} from that file${skipped ? `, ${skipped} were already here` : ''}.`+ : 'Nothing new in that file, every chat in it is already here.')+ } catch (err) {+ setNote(err instanceof Error ? err.message : 'Could not read that file.')+ } finally {+ setBusy(false)+ }+ }++ const label = found === null+ ? 'Looking in the backup...'+ : found === 0+ ? 'No missing chats in the backup'+ : `Restore chats from backup (${found} found)`++ return (+ <div className="pt-2 space-y-1">+ <button+ onClick={() => void restore()}+ disabled={busy || !found}+ data-testid="restore-chats-from-backup"+ className="w-full t-micro flex items-center justify-center gap-1.5 px-2 py-1.5 rounded border border-gray-200 dark:border-white/10 text-gray-600 dark:text-gray-300 hover:border-gray-400 dark:hover:border-white/20 transition-colors disabled:opacity-50 disabled:cursor-default"+ >+ <History size={12} /> {busy ? 'Restoring...' : label}+ </button>+ <button+ onClick={() => void pickFile()}+ disabled={busy}+ data-testid="restore-chats-from-file"+ className="w-full t-micro flex items-center justify-center gap-1.5 px-2 py-1.5 rounded border border-gray-200 dark:border-white/10 text-gray-600 dark:text-gray-300 hover:border-gray-400 dark:hover:border-white/20 transition-colors disabled:opacity-50 disabled:cursor-default"+ >+ <Upload size={12} /> Choose a backup file...+ </button>+ <div className="t-micro text-gray-500 dark:text-gray-500 leading-relaxed">+ LU keeps copies of your chats in its app data folder. This brings back the ones missing here and leaves the others as they are. Kept a copy of that folder somewhere else? Choose a store_backup file from it.+ </div>+ {note && <div className="t-micro text-gray-500 dark:text-gray-400">{note}</div>}</div>)}diff --git a/src/lib/__tests__/chat-rescue.test.ts b/src/lib/__tests__/chat-rescue.test.tsnew file mode 100644index 00000000..8456bc48--- /dev/null+++ b/src/lib/__tests__/chat-rescue.test.ts@@ -0,0 +1,227 @@+/**+ * Restore chats from backup (3.0.10), and the launch check that missed them.+ *+ * perrt, Discord 05.11.2026, on 3.0.8: every chat gone, the memories still+ * there. Run: npx vitest run src/lib/__tests__/chat-rescue.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'++const backend = vi.hoisted(() => vi.fn())+vi.mock('../../api/backend', () => ({ isTauri: () => true, backendCall: backend }))++import { useChatStore } from '../../stores/chatStore'+import type { Conversation } from '../../types/chat'+import { parseImportedChats } from '../chat-export'+import { chatsMissingFrom, restoreChatsFromBackup, countRestorableChats, shouldShowRescueHint, readDismissedAt, rememberDismissed } from '../chat-rescue'++/**+ * Conversations in the shape 3.0.8 persisted them (src/types/chat.ts at+ * v3.0.8): no customParams, no groupSitOut, no historyTrim, compaction+ * records without contextBefore/endMessageId.+ */+function chat308(id: string, updatedAt: number, extra: Record<string, unknown> = {}): Conversation {+ return {+ id,+ title: `chat ${id}`,+ messages: [+ { id: `${id}-u`, role: 'user', content: 'hello', timestamp: updatedAt - 2 },+ { id: `${id}-a`, role: 'assistant', content: 'hi', timestamp: updatedAt - 1, model: 'llama3' },+ ],+ model: 'llama3',+ systemPrompt: '',+ mode: 'lu',+ createdAt: 1,+ updatedAt,+ personaEnabled: false,+ ...extra,+ } as unknown as Conversation+}++/** What `chat_backup_conversations` hands back: one JSON array. */+function backupAnswer(list: unknown[]) {+ backend.mockImplementation(async (cmd: string) => {+ if (cmd === 'chat_backup_conversations') return JSON.stringify(list)+ throw new Error(`unexpected ${cmd}`)+ })+}++describe('restore chats from backup', () => {+ beforeEach(() => {+ backend.mockReset()+ useChatStore.setState({ conversations: [], activeConversationId: null })+ })++ it('brings back the chats the store lost and keeps the one written after the loss', async () => {+ // After the loss: the store has one new chat. The backups hold the old ones,+ // a group chat among them, plus an older copy of the new chat.+ useChatStore.setState({ conversations: [chat308('new', 500)] })+ backupAnswer([+ chat308('a', 100),+ chat308('group', 200, { groupModels: ['llama3', 'qwen'], groupPersonas: { qwen: 'p1' } }),+ chat308('compacted', 300, { compactions: [{ id: 'k1', at: 290, atMessageCount: 2, summary: 's', tokensBefore: 10, tokensAfter: 2 }] }),+ chat308('new', 400),+ { id: 'broken' },+ null,+ ])++ const live = () => useChatStore.getState().conversations+ expect(await countRestorableChats(live)).toBe(3)++ const added = await restoreChatsFromBackup(live, useChatStore.getState().importConversations)+ expect(added).toBe(3)+ const ids = live().map((c) => c.id)+ expect(ids).toEqual(['new', 'compacted', 'group', 'a'])+ expect(new Set(ids).size).toBe(ids.length)+ // The chat written after the loss is the live one, not the backup's older copy.+ expect(live().find((c) => c.id === 'new')!.updatedAt).toBe(500)+ expect(live().find((c) => c.id === 'group')!.groupModels).toEqual(['llama3', 'qwen'])++ // Twice changes nothing.+ expect(await restoreChatsFromBackup(live, useChatStore.getState().importConversations)).toBe(0)+ expect(live()).toHaveLength(4)+ })++ it('an empty or missing backup restores nothing', async () => {+ backupAnswer([])+ expect(await restoreChatsFromBackup(() => [], vi.fn())).toBe(0)+ backend.mockResolvedValue('')+ expect(await countRestorableChats(() => [])).toBe(0)+ })++ it('keeps one entry per id even if the list repeats one', () => {+ const list = chatsMissingFrom([], [chat308('x', 1), chat308('x', 2)])+ expect(list.map((c) => c.id)).toEqual(['x'])+ })+})++describe('a store backup picked by hand', () => {+ it('imports its chats and merges them next to the ones written since', () => {+ // perrt: about five hours on after the loss, two new chats; the old ones+ // only in a store_backup.prev.json he copied out to a rescue folder.+ useChatStore.setState({ conversations: [chat308('new1', 900), chat308('new2', 950)] })+ const file = JSON.stringify({+ __ts: 'x',+ 'chat-conversations': JSON.stringify({ state: { conversations: [chat308('old1', 100), chat308('old2', 200)], activeConversationId: 'old2' } }),+ 'chat-settings': '{}',+ })+ const { added } = useChatStore.getState().importConversations(parseImportedChats(file), 'merge')+ expect(added).toBe(2)+ expect(useChatStore.getState().conversations.map((c) => c.id)).toEqual(['new2', 'new1', 'old2', 'old1'])+ })++ it('a backup whose chats are unreadable says so', () => {+ expect(() => parseImportedChats(JSON.stringify({ 'chat-conversations': 'garbled' }))).toThrow(/could not be read/)+ })+})++describe('the hint at launch', () => {+ it('shows for an empty list with chats in the backup', () => {+ expect(shouldShowRescueHint(0, 12, null)).toBe(true)+ expect(shouldShowRescueHint(0, 0, null)).toBe(false)+ })++ it('shows when the backup holds more chats than the list (a new chat after the loss)', () => {+ expect(shouldShowRescueHint(1, 40, null)).toBe(true)+ // A couple of deleted chats in an archive is not that.+ expect(shouldShowRescueHint(30, 2, null)).toBe(false)+ })++ it('stays away after Dismiss until the backup holds more', () => {+ const mem = new Map<string, string>()+ const storage = { getItem: (k: string) => mem.get(k) ?? null, setItem: (k: string, v: string) => void mem.set(k, v) }+ rememberDismissed(storage, 12)+ expect(readDismissedAt(storage)).toBe(12)+ expect(shouldShowRescueHint(0, 12, readDismissedAt(storage))).toBe(false)+ expect(shouldShowRescueHint(0, 13, readDismissedAt(storage))).toBe(true)+ })+})++// ── The launch check (AppShell) ─────────────────────────────────────────────++/** IndexedDB stand-in that stores any value, string or not. */+function fakeIndexedDB(data: Record<string, unknown>) {+ const request = (result: unknown) => {+ const r: Record<string, unknown> = { onsuccess: null, onerror: null, result, error: null }+ queueMicrotask(() => (r.onsuccess as (() => void) | null)?.())+ return r+ }+ const db = {+ objectStoreNames: { contains: () => true },+ createObjectStore: () => {},+ transaction: () => ({+ objectStore: () => ({+ get: (k: string) => request(data[k]),+ count: (k: string) => request(k in data ? 1 : 0),+ put: (v: unknown, k: string) => { data[k] = v; return {} },+ delete: (k: string) => { delete data[k]; return {} },+ }),+ set oncomplete(fn: () => void) { queueMicrotask(fn) },+ set onerror(_fn: () => void) {},+ set onabort(_fn: () => void) {},+ }),+ }+ return {+ open: () => {+ const req: Record<string, unknown> = { onsuccess: null, onerror: null, onblocked: null, onupgradeneeded: null, result: db, error: null }+ queueMicrotask(() => (req.onsuccess as (() => void) | null)?.())+ return req+ },+ }+}++function fakeLocalStorage(init: Record<string, string> = {}) {+ const mem = new Map(Object.entries(init))+ return {+ getItem: (k: string) => (mem.has(k) ? mem.get(k)! : null),+ setItem: (k: string, v: string) => void mem.set(k, String(v)),+ removeItem: (k: string) => void mem.delete(k),+ clear: () => mem.clear(),+ key: (i: number) => [...mem.keys()][i] ?? null,+ get length() { return mem.size },+ }+}++describe('the launch check sees what hydration sees', () => {+ const saved = { idb: Reflect.get(globalThis, 'indexedDB'), ls: Reflect.get(globalThis, 'localStorage') }++ afterEach(() => {+ Object.defineProperty(globalThis, 'indexedDB', { value: saved.idb, configurable: true, writable: true })+ Object.defineProperty(globalThis, 'localStorage', { value: saved.ls, configurable: true, writable: true })+ vi.resetModules()+ })++ async function load(rows: Record<string, unknown>, ls: Record<string, string> = {}) {+ vi.resetModules()+ Object.defineProperty(globalThis, 'indexedDB', { value: fakeIndexedDB(rows), configurable: true, writable: true })+ Object.defineProperty(globalThis, 'localStorage', { value: fakeLocalStorage(ls), configurable: true, writable: true })+ vi.doMock('../storage-health', () => ({+ requestPersistentStorage: async () => true,+ reportStorageReadFailure: () => {}, reportStorageReadOk: () => {},+ reportStorageWriteFailure: () => {}, reportStorageWriteOk: () => {},+ }))+ return await import('../idbStorage')+ }++ it('a row that is no string: the old check said present, hydration got nothing', async () => {+ const { idbStorage, hasStoredItem, hasReadableItem } = await load({ 'chat-conversations': { state: { conversations: [] } } })+ expect(await idbStorage.getItem('chat-conversations')).toBeNull()+ // The 3.0.8 rule: "present", so nothing was restored.+ expect(await hasStoredItem('chat-conversations')).toBe(true)+ // The 3.0.10 rule: empty, so the backup goes back in.+ expect(await hasReadableItem('chat-conversations')).toBe(false)+ })++ it('a leftover "[object Object]" in localStorage: same blind spot', async () => {+ const { idbStorage, hasStoredItem, hasReadableItem } = await load({}, { 'chat-conversations': '[object Object]' })+ expect(await idbStorage.getItem('chat-conversations')).toBeNull()+ expect(await hasStoredItem('chat-conversations')).toBe(true)+ expect(await hasReadableItem('chat-conversations')).toBe(false)+ })++ it('a real value is present for both', async () => {+ const value = JSON.stringify({ state: { conversations: [chat308('a', 1)] } })+ const { hasStoredItem, hasReadableItem } = await load({ 'chat-conversations': value })+ expect(await hasStoredItem('chat-conversations')).toBe(true)+ expect(await hasReadableItem('chat-conversations')).toBe(true)+ })+})diff --git a/src/lib/chat-export.ts b/src/lib/chat-export.tsindex dcce6517..9a40535a 100644--- a/src/lib/chat-export.ts+++ b/src/lib/chat-export.ts@@ -318,6 +318,20 @@ export function parseImportedChats(json: string): Conversation[] {throw new Error('That file is not valid JSON.')}let raw: unknown[]+ // A store backup (store_backup*.json from the app data folder, 3.0.10): the+ // chats are a JSON string under chat-conversations. The desktop already+ // unpacks it natively (externalize_import); this covers the web build.+ const backupChats = data && typeof data === 'object' && !Array.isArray(data)+ ? (data as Record<string, unknown>)['chat-conversations']+ : undefined+ if (typeof backupChats === 'string') {+ try {+ const inner = JSON.parse(backupChats) as { state?: { conversations?: unknown } }+ data = Array.isArray(inner?.state?.conversations) ? inner.state.conversations : []+ } catch {+ throw new Error('The chats in that backup could not be read.')+ }+ }if (Array.isArray(data)) {raw = data} else if (data && typeof data === 'object' && Array.isArray((data as { conversations?: unknown[] }).conversations)) {diff --git a/src/lib/chat-rescue.ts b/src/lib/chat-rescue.tsnew file mode 100644index 00000000..37df290f--- /dev/null+++ b/src/lib/chat-rescue.ts@@ -0,0 +1,99 @@+/**+ * Restore chats from backup (3.0.10).+ *+ * perrt, Discord 05.11.2026, on 3.0.8: every chat gone, the memories still+ * there. The IndexedDB row of the chat store came back empty, the native+ * backup kept the chats while the key was missing, and then the store wrote a+ * fresh list that replaced them in store_backup.json. The older copies were+ * still on disk (the ring store_backup.1-3.json, store_backup.prev.json, and+ * since 3.0.10 the chat archives store_backup.chats-*.json), but nothing in+ * the app ever read them again.+ *+ * `chat_backup_conversations` reads every one of those files natively and+ * hands back one list, one entry per chat id. This module only decides which+ * of them the live store does not have, and adds exactly those through+ * importConversations('merge'). A chat that is still here is never touched, so+ * running it twice adds nothing the second time.+ *+ * Nothing here runs by itself. The launch hint only counts; the chats come+ * back when the user presses the button (Settings, or the hint).+ */+import { backendCall, isTauri } from '../api/backend'+import { log } from './logger'+import type { Conversation } from '../types/chat'++/** The chats of the backup list that the live store has no chat with that id for. */+export function chatsMissingFrom(live: readonly Conversation[], backup: readonly unknown[]): Conversation[] {+ const have = new Set(live.map((c) => c.id))+ const seen = new Set<string>()+ const out: Conversation[] = []+ for (const entry of backup) {+ if (!entry || typeof entry !== 'object') continue+ const c = entry as Partial<Conversation>+ if (typeof c.id !== 'string' || !c.id || !Array.isArray(c.messages)) continue+ if (have.has(c.id) || seen.has(c.id)) continue+ seen.add(c.id)+ out.push(c as Conversation)+ }+ return out+}++/** Every chat the backup files hold, as one list. Empty outside the desktop app. */+export async function readBackupChats(): Promise<unknown[]> {+ if (!isTauri()) return []+ const raw = await backendCall<string>('chat_backup_conversations')+ const list: unknown = raw ? JSON.parse(raw) : []+ return Array.isArray(list) ? list : []+}++/** How many chats the backups hold that the store does not. */+export async function countRestorableChats(live: () => readonly Conversation[]): Promise<number> {+ return chatsMissingFrom(live(), await readBackupChats()).length+}++/**+ * Put every chat back that the backups have and the store does not.+ * Returns how many came back.+ */+export async function restoreChatsFromBackup(+ live: () => readonly Conversation[],+ importConversations: (chats: Conversation[], mode: 'merge') => { added: number; skipped: number },+): Promise<number> {+ const missing = chatsMissingFrom(live(), await readBackupChats())+ if (missing.length === 0) return 0+ const { added } = importConversations(missing, 'merge')+ log.warn('[chat-rescue] chats restored from the backup files', { count: added })+ return added+}++// ── The hint at launch ───────────────────────────────────────────────────++/** The count the user last dismissed the hint at. The hint comes back only for more. */+export const RESCUE_HINT_DISMISSED_KEY = 'lu-chat-rescue-hint-dismissed'++/**+ * Whether the launch hint should show. The task asks for "the chat list is+ * empty", and perrt's case shows that is too narrow: by the time he looked he+ * had started a new chat. So: the backups hold more chats than the store, and+ * the user has not dismissed the hint at this count or a higher one. Someone+ * who deleted most of their chats on purpose sees it once and dismisses it.+ */+export function shouldShowRescueHint(liveCount: number, restorable: number, dismissedAt: number | null): boolean {+ if (restorable <= 0) return false+ if (dismissedAt !== null && restorable <= dismissedAt) return false+ return liveCount === 0 || restorable > liveCount+}++export function readDismissedAt(storage: Pick<Storage, 'getItem'> | null): number | null {+ try {+ const raw = storage?.getItem(RESCUE_HINT_DISMISSED_KEY)+ const n = raw == null ? NaN : Number(raw)+ return Number.isFinite(n) ? n : null+ } catch {+ return null+ }+}++export function rememberDismissed(storage: Pick<Storage, 'setItem'> | null, count: number): void {+ try { storage?.setItem(RESCUE_HINT_DISMISSED_KEY, String(count)) } catch { /* a hint that comes back is harmless */ }+}diff --git a/src/lib/idbStorage.ts b/src/lib/idbStorage.tsindex 7adc2da5..79d71287 100644--- a/src/lib/idbStorage.ts+++ b/src/lib/idbStorage.ts@@ -315,6 +315,29 @@ export async function hasStoredItem(key: string): Promise<boolean | null> {}}+/**+ * Whether `key` holds a value the stores can actually hydrate from: a+ * non-empty string, read the way hydration reads it. Answers null when the+ * read failed, so the caller can tell "nothing there" from "could not look".+ *+ * perrt, 05.11.2026 (3.0.10): `hasStoredItem` answers yes for a row that is+ * not a string (count() sees it, getItem hands hydration null for it) and for+ * a leftover localStorage copy (the FIX-3 "[object Object]" one getItem+ * refuses). The chat store then hydrated empty while the restore at launch+ * believed the chats were there and restored nothing. This costs one full read+ * of the value; the launch check is the one place where being right about+ * "empty" matters more than that.+ */+export async function hasReadableItem(key: string): Promise<boolean | null> {+ try {+ const value = await Promise.resolve(idbStorage.getItem(key))+ if (hasFailedRead(key)) return null+ return typeof value === 'string' && value.trim() !== ''+ } catch {+ return null+ }+}+let _persistAsked = falsefunction askPersist(): void {if (_persistAsked) return