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(chat): the restore hint stops coming back for deleted chats (A26)

purplecc6898f726b6
diff --git a/dev-server/remote-stubs.ts b/dev-server/remote-stubs.ts
index 2212d1ae..b0e040d5 100644
--- a/dev-server/remote-stubs.ts
+++ b/dev-server/remote-stubs.ts
@@ -102,6 +102,7 @@ export function registerRemoteStubs(routes: RouteMount): void {
'/local-api/verify-model-files', '/local-api/verify-model-files-status', '/local-api/verify-model-files-cancel',
'/local-api/comfy-model-info',
'/local-api/comfy-model-reveal',
+ '/local-api/chat-backup-clear', '/local-api/chat-backup-reveal',
'/local-api/bundled-model-delete-plan',
'/local-api/trash-model-file', '/local-api/set-engine-idle-unload', '/local-api/transcribe-external',
'/local-api/set-gpu-roles', '/local-api/describe-gpu-roles',
diff --git a/src-tauri/src/commands/download.rs b/src-tauri/src/commands/download.rs
index 465c7c63..a9427167 100644
--- a/src-tauri/src/commands/download.rs
+++ b/src-tauri/src/commands/download.rs
@@ -880,7 +880,7 @@ pub async fn comfy_model_reveal(
/// The file selected in Finder or Explorer; on Linux, where there is no
/// common way to select a file, its folder.
#[cfg(desktop)]
-fn reveal_in_file_manager(file: &Path) -> Result<(), String> {
+pub(crate) fn reveal_in_file_manager(file: &Path) -> Result<(), String> {
#[cfg(target_os = "macos")]
let mut cmd = {
let mut c = std::process::Command::new("open");
diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs
index 5ace1277..b00cef7c 100644
--- a/src-tauri/src/commands/system.rs
+++ b/src-tauri/src/commands/system.rs
@@ -752,6 +752,100 @@ pub async fn chat_backup_conversations() -> Result<String, String> {
.map_err(|e| e.to_string())?
}
+/// One writer at a time for the backup files: the snapshot (`backup_stores`)
+/// and "Clear backup" (`chat_backup_clear`, A26) both rewrite them.
+static BACKUP_FILES: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
+/// The backup file `raw` with only the chats whose id is in `keep`, and the
+/// ids it took out. None when there was nothing to take out or the file has
+/// no readable chat list; such a file is left exactly as it is. Every other
+/// store in the file (settings, memories, characters) stays untouched.
+pub(crate) fn backup_with_only(raw: &str, keep: &std::collections::HashSet<String>) -> Option<(String, Vec<String>)> {
+ let key = crate::commands::chat_attachments::CHAT_KEY;
+ let mut outer: serde_json::Value = serde_json::from_str(raw).ok()?;
+ let mut inner: serde_json::Value = serde_json::from_str(outer.get(key)?.as_str()?).ok()?;
+ let list = inner.pointer_mut("/state/conversations")?.as_array_mut()?;
+ let mut removed = Vec::new();
+ list.retain(|c| match c.get("id").and_then(|v| v.as_str()) {
+ Some(id) if !keep.contains(id) => {
+ removed.push(id.to_string());
+ false
+ }
+ _ => true,
+ });
+ if removed.is_empty() {
+ return None;
+ }
+ *outer.get_mut(key)? = serde_json::Value::String(inner.to_string());
+ Some((outer.to_string(), removed))
+}
+
+/// A26 (3.1.0): take every chat out of the backup files that is not in the
+/// chat list (`keep`). The chat archives go as a whole, they exist only to
+/// hold chats that left the list. The live file, the ring and the file set
+/// aside keep everything else they carry. Returns how many different chats
+/// were taken out.
+pub(crate) fn clear_chats_outside(dir: &std::path::Path, keep: &std::collections::HashSet<String>) -> Result<usize, String> {
+ let mut removed: std::collections::HashSet<String> = std::collections::HashSet::new();
+ let archives = chat_archives(dir);
+ for path in backup_candidates(dir) {
+ let Ok(raw) = std::fs::read_to_string(&path) else { continue };
+ if archives.contains(&path) {
+ removed.extend(backup_chat_ids(&raw).unwrap_or_default().into_iter().filter(|id| !keep.contains(id)));
+ std::fs::remove_file(&path)
+ .map_err(|e| format!("could not remove {}: {}", path.display(), os_error::english(&e)))?;
+ continue;
+ }
+ let Some((rewritten, gone)) = backup_with_only(&raw, keep) else { continue };
+ let tmp = path.with_extension("json.clear.tmp");
+ let written = (|| -> std::io::Result<()> {
+ use std::io::Write;
+ let mut file = std::fs::File::create(&tmp)?;
+ file.write_all(rewritten.as_bytes())?;
+ file.sync_all()?;
+ std::fs::rename(&tmp, &path)
+ })();
+ if let Err(e) = written {
+ let _ = std::fs::remove_file(&tmp);
+ return Err(format!("could not rewrite {}: {}", path.display(), os_error::english(&e)));
+ }
+ removed.extend(gone);
+ }
+ Ok(removed.len())
+}
+
+/// "Clear backup" in Settings → Chat Backup (A26). `keep` is the chat list
+/// as it is now; every other chat leaves the backup files for good.
+#[cfg(desktop)]
+#[tauri::command]
+pub async fn chat_backup_clear(keep: Vec<String>) -> Result<usize, String> {
+ tauri::async_runtime::spawn_blocking(move || {
+ let _one = BACKUP_FILES.lock().unwrap_or_else(|e| e.into_inner());
+ let dir = persistent_dir()?;
+ let keep: std::collections::HashSet<String> = keep.into_iter().collect();
+ let n = clear_chats_outside(&dir, &keep)?;
+ if n > 0 {
+ // The images only those chats pointed at can go too.
+ crate::commands::chat_attachments::collect_garbage_soon(dir);
+ }
+ Ok(n)
+ })
+ .await
+ .map_err(|e| e.to_string())?
+}
+
+/// "Open folder" in Settings → Chat Backup (A26): the backup file selected
+/// in Finder or Explorer, its folder on Linux.
+#[cfg(desktop)]
+#[tauri::command]
+pub fn chat_backup_reveal() -> Result<String, String> {
+ let dir = persistent_dir()?;
+ let file = dir.join("store_backup.json");
+ let target = if file.exists() { file } else { dir.clone() };
+ crate::commands::download::reveal_in_file_manager(&target)?;
+ Ok(dir.to_string_lossy().into_owned())
+}
+
/// A backup is worth restoring from when it parses as a JSON object that still
/// carries at least one non-empty string value.
///
@@ -831,6 +925,7 @@ fn rotate_generations(dir: &std::path::Path) {
/// the shape of failure this whole path exists to survive.
#[tauri::command]
pub fn backup_stores(data: String) -> Result<(), String> {
+ let _one = BACKUP_FILES.lock().unwrap_or_else(|e| e.into_inner());
let dir = persistent_dir()?;
std::fs::create_dir_all(&dir).map_err(|e| os_error::english(&e))?;
let target = dir.join("store_backup.json");
@@ -1608,4 +1703,61 @@ mod tests {
assert!(!dir.join("store_backup.1.json").exists());
let _ = std::fs::remove_dir_all(&dir);
}
+
+ // ── A26: "Clear backup" ─────────────────────────────────────
+
+ fn ids_in(raw: &str) -> Vec<String> {
+ let mut v: Vec<String> = backup_chat_ids(raw).unwrap_or_default().into_iter().collect();
+ v.sort();
+ v
+ }
+
+ /// A26 (3.1.0): the backup kept every deleted chat, and "Clear backup"
+ /// takes them out of the live file, the ring and the file set aside, and
+ /// removes the chat archives. The chats in the list and every other
+ /// store in the files stay.
+ #[test]
+ fn clearing_the_backup_keeps_the_chat_list_and_every_other_store() {
+ let dir = scratch_dir("chat-clear");
+ std::fs::write(dir.join("store_backup.json"), backup_with_chats(&["live1", "live2", "gone1"])).unwrap();
+ std::fs::write(dir.join("store_backup.1.json"), backup_with_chats(&["live1", "gone1", "gone2"])).unwrap();
+ std::fs::write(dir.join("store_backup.prev.json"), backup_with_chats(&["gone3"])).unwrap();
+ std::fs::write(dir.join("store_backup.chats-1000.json"), backup_with_chats(&["live2", "gone4"])).unwrap();
+ // A file without a chat list is not touched.
+ std::fs::write(dir.join("store_backup.2.json"), r#"{"chat-settings":"{}"}"#).unwrap();
+
+ let keep: std::collections::HashSet<String> = ["live1", "live2"].iter().map(|s| s.to_string()).collect();
+ assert_eq!(clear_chats_outside(&dir, &keep).unwrap(), 4, "gone1..gone4, each counted once");
+
+ let live = std::fs::read_to_string(dir.join("store_backup.json")).unwrap();
+ assert_eq!(ids_in(&live), vec!["live1", "live2"]);
+ let outer: serde_json::Value = serde_json::from_str(&live).unwrap();
+ assert_eq!(outer["chat-settings"], "{}", "the other stores stay");
+ assert_eq!(outer["__ts"], "t");
+ assert_eq!(ids_in(&std::fs::read_to_string(dir.join("store_backup.1.json")).unwrap()), vec!["live1"]);
+ assert!(ids_in(&std::fs::read_to_string(dir.join("store_backup.prev.json")).unwrap()).is_empty());
+ assert!(chat_archives(&dir).is_empty(), "the chat archives are gone");
+ assert_eq!(std::fs::read_to_string(dir.join("store_backup.2.json")).unwrap(), r#"{"chat-settings":"{}"}"#);
+ let leftovers: Vec<String> = std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok())
+ .map(|e| e.file_name().to_string_lossy().into_owned()).filter(|n| n.ends_with(".tmp")).collect();
+ assert!(leftovers.is_empty(), "no temporary file is left: {leftovers:?}");
+
+ // What the restore reads now offers nothing that is not in the list.
+ 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!["live1", "live2"]);
+
+ // Twice is a no-op.
+ assert_eq!(clear_chats_outside(&dir, &keep).unwrap(), 0);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn a_backup_with_nothing_to_take_out_is_left_byte_for_byte() {
+ let raw = backup_with_chats(&["a", "b"]);
+ let keep: std::collections::HashSet<String> = ["a", "b", "c"].iter().map(|s| s.to_string()).collect();
+ assert!(backup_with_only(&raw, &keep).is_none());
+ assert!(backup_with_only("not json", &keep).is_none());
+ }
}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index e02067f3..bb7442cc 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -913,6 +913,10 @@ pub fn run() {
commands::gallery_files::scan_comfy_output,
commands::system::restore_stores,
commands::system::chat_backup_conversations,
+ #[cfg(desktop)]
+ commands::system::chat_backup_clear,
+ #[cfg(desktop)]
+ commands::system::chat_backup_reveal,
commands::system::backup_rag_chunks,
commands::system::restore_rag_chunks,
commands::system::exit_app,
diff --git a/src/api/backend.ts b/src/api/backend.ts
index 98af7ffb..f3a44844 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -667,6 +667,10 @@ export async function backendCall<T = unknown>(
// C41 / C17: show a model file in the file manager, and what Delete would
// take for an LU Engine row. Rust only, the dev server answers 501.
comfy_model_reveal: { path: "/local-api/comfy-model-reveal", method: "POST" },
+ // A26 (3.1.0): Settings → Chat Backup, clear the chats only the backup
+ // holds and show its folder. Rust only, the dev server answers 501.
+ chat_backup_clear: { path: "/local-api/chat-backup-clear", method: "POST" },
+ chat_backup_reveal: { path: "/local-api/chat-backup-reveal", method: "POST" },
bundled_model_delete_plan: { path: "/local-api/bundled-model-delete-plan", method: "POST" },
// Check files and Repair (GH #113): Rust only, the dev server answers
// 501 (dev-server/remote-stubs.ts).
diff --git a/src/components/layout/ChatRescueHint.tsx b/src/components/layout/ChatRescueHint.tsx
index 797f9430..d7efb54f 100644
--- a/src/components/layout/ChatRescueHint.tsx
+++ b/src/components/layout/ChatRescueHint.tsx
@@ -2,7 +2,7 @@ import { useEffect, useState } from 'react'
import { useChatStore } from '../../stores/chatStore'
import { isTauri } from '../../api/backend'
import {
- countRestorableChats, restoreChatsFromBackup, shouldShowRescueHint, readDismissedAt, rememberDismissed,
+ restorableChatIds, restoreChatsFromBackup, decideRescueHint, rememberDismissed,
} from '../../lib/chat-rescue'
import { installDeletionNote } from '../../lib/chat-deletion-note'
@@ -19,7 +19,8 @@ export function ChatRescueHint() {
// A chat that leaves the list from here on was deleted on purpose: the restore does not offer it back (C46).
// The shell mounts this once for the whole session.
useEffect(() => { installDeletionNote() }, [])
- const [count, setCount] = useState(0)
+ const [offered, setOffered] = useState<string[]>([])
+ const count = offered.length
const [busy, setBusy] = useState(false)
const [done, setDone] = useState<string | null>(null)
@@ -34,9 +35,9 @@ export function ChatRescueHint() {
await new Promise((r) => setTimeout(r, LOOK_AFTER_MS))
if (gone) return
const live = () => useChatStore.getState().conversations
- const restorable = await countRestorableChats(live)
+ const ids = await restorableChatIds(live)
const storage = typeof localStorage !== 'undefined' ? localStorage : null
- if (!gone && shouldShowRescueHint(live().length, restorable, readDismissedAt(storage))) setCount(restorable)
+ if (!gone && decideRescueHint(live().length, ids, storage)) setOffered(ids)
}
look().catch(() => { /* no hint is the old behaviour */ })
return () => { gone = true }
@@ -45,8 +46,9 @@ export function ChatRescueHint() {
if (count === 0 && !done) return null
const dismiss = () => {
- rememberDismissed(typeof localStorage !== 'undefined' ? localStorage : null, count)
- setCount(0)
+ // A26: for these chats, until one goes missing that was not among them.
+ rememberDismissed(typeof localStorage !== 'undefined' ? localStorage : null, offered)
+ setOffered([])
setDone(null)
}
@@ -54,7 +56,7 @@ export function ChatRescueHint() {
setBusy(true)
try {
const added = await restoreChatsFromBackup(() => useChatStore.getState().conversations, importConversations)
- setCount(0)
+ setOffered([])
setDone(`Restored ${added} chat${added === 1 ? '' : 's'} from the backup.`)
} catch (err) {
setDone(err instanceof Error ? err.message : 'Could not read the backup.')
diff --git a/src/components/settings/ChatBackupSettings.tsx b/src/components/settings/ChatBackupSettings.tsx
index 66f79105..a397d01b 100644
--- a/src/components/settings/ChatBackupSettings.tsx
+++ b/src/components/settings/ChatBackupSettings.tsx
@@ -1,9 +1,9 @@
import { useEffect, useRef, useState } from 'react'
-import { Download, Upload, History } from 'lucide-react'
+import { Download, Upload, History, FolderOpen, Trash2 } 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'
+import { countRestorableChats, restoreChatsFromBackup, clearChatBackup, revealChatBackup } from '../../lib/chat-rescue'
/**
* Chat Backup (a user 2026-06-28) — export ALL conversations to one JSON file
@@ -114,6 +114,9 @@ function RestoreFromBackup() {
const [found, setFound] = useState<number | null>(null)
const [busy, setBusy] = useState(false)
const [note, setNote] = useState('')
+ const [confirmClear, setConfirmClear] = useState(false)
+ // A26: counted again after a clear, not only when the list changes.
+ const [looked, setLooked] = useState(0)
useEffect(() => {
let gone = false
@@ -121,7 +124,34 @@ function RestoreFromBackup() {
.then((n) => { if (!gone) setFound(n) })
.catch(() => { if (!gone) setFound(0) })
return () => { gone = true }
- }, [liveCount])
+ }, [liveCount, looked])
+
+ // A26 (3.1.0): the backup keeps every chat that left the list. This takes
+ // them out for good; the chats in the list stay, and so does the rest of
+ // the backup (settings, memories).
+ const clear = async () => {
+ setConfirmClear(false)
+ setBusy(true)
+ try {
+ const removed = await clearChatBackup(() => useChatStore.getState().conversations)
+ setNote(removed > 0
+ ? `Removed ${removed} chat${removed === 1 ? '' : 's'} from the backup. Your chat list is unchanged.`
+ : 'The backup holds no chats that are not in your chat list.')
+ setLooked((n) => n + 1)
+ } catch (err) {
+ setNote(err instanceof Error ? err.message : 'Could not clear the backup.')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ const openFolder = async () => {
+ try {
+ await revealChatBackup()
+ } catch (err) {
+ setNote(err instanceof Error ? err.message : 'Could not open the backup folder.')
+ }
+ }
const restore = async () => {
setBusy(true)
@@ -178,6 +208,45 @@ function RestoreFromBackup() {
>
<Upload size={12} /> Choose a backup file...
</button>
+ <div className="flex gap-2">
+ <button
+ onClick={() => void openFolder()}
+ data-testid="chat-backup-open-folder"
+ className="flex-1 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"
+ >
+ <FolderOpen size={12} /> Open folder
+ </button>
+ <button
+ onClick={() => { setNote(''); setConfirmClear(true) }}
+ disabled={busy || confirmClear}
+ data-testid="chat-backup-clear"
+ className="flex-1 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"
+ >
+ <Trash2 size={12} /> Clear backup...
+ </button>
+ </div>
+ {confirmClear && (
+ <div role="alertdialog" aria-label="Clear backup" data-testid="chat-backup-clear-confirm" className="rounded border border-gray-300 dark:border-white/15 px-2 py-1.5 space-y-1.5">
+ <div className="t-micro text-gray-700 dark:text-gray-200 leading-relaxed">
+ {found
+ ? `This removes the ${found} chat${found === 1 ? '' : 's'} that ${found === 1 ? 'is' : 'are'} only in the backup, for good. They cannot be restored afterwards.`
+ : 'This removes every chat from the backup that is not in your chat list, for good. They cannot be restored afterwards.'}{' '}
+ The chats in your list and your other settings stay as they are.
+ </div>
+ <div className="flex gap-2 justify-end">
+ <button onClick={() => setConfirmClear(false)} className="t-micro px-2 py-1 text-gray-600 dark:text-gray-300 hover:underline">
+ Cancel
+ </button>
+ <button
+ onClick={() => void clear()}
+ data-testid="chat-backup-clear-yes"
+ className="t-micro px-2 py-1 rounded border border-red-500/60 text-red-600 dark:text-red-400 hover:bg-red-500/10"
+ >
+ Clear backup
+ </button>
+ </div>
+ </div>
+ )}
<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>
diff --git a/src/lib/__tests__/chat-rescue-a26.test.ts b/src/lib/__tests__/chat-rescue-a26.test.ts
new file mode 100644
index 00000000..65a2effe
--- /dev/null
+++ b/src/lib/__tests__/chat-rescue-a26.test.ts
@@ -0,0 +1,188 @@
+/**
+ * A26 (3.1.0): the restore hint at every start.
+ *
+ * LU-Admin, on 3.0.10: "Your backup holds N chats that are not in your chat
+ * list. Restore them?" came back at every start. The backup keeps every chat
+ * that leaves the list (that is how perrt's chats were saved), a deleted chat
+ * counted as missing, and Dismiss kept only the count: the next deleted chat
+ * made the count larger and the hint was back.
+ *
+ * Since C46 a chat deleted while LU runs is noted and not offered. What A26
+ * adds: the dismissal holds the ids (it lasts until a chat goes missing that
+ * was not offered then), a 3.0.10 dismissal is carried over once, and the
+ * backup can be cleared and opened from Settings.
+ *
+ * Run: npx vitest run src/lib/__tests__/chat-rescue-a26.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 {
+ RESCUE_HINT_DISMISSED_KEY, RESCUE_HINT_DISMISSED_MAX, clearChatBackup, decideRescueHint, readDismissal,
+ rememberDismissed, restorableChatIds, revealChatBackup, shouldShowRescueHint,
+} from '../chat-rescue'
+import { __resetDeletionNoteForTests, installDeletionNote } from '../chat-deletion-note'
+import { STORE_KEYS } from '../store-backup'
+
+function chat(id: string, updatedAt = 1): Conversation {
+ return {
+ id, title: id, model: 'm', systemPrompt: '', createdAt: 1, updatedAt,
+ messages: [{ id: `${id}-u`, role: 'user', content: 'hi', timestamp: 1 }],
+ } as unknown as Conversation
+}
+
+function memory(init: Record<string, string> = {}) {
+ const mem = new Map(Object.entries(init))
+ return {
+ mem,
+ 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 },
+ }
+}
+
+/** The backup files, as `chat_backup_conversations` hands them back. */
+let backup: Conversation[] = []
+const savedLs = Reflect.get(globalThis, 'localStorage')
+let ls = memory()
+
+beforeEach(() => {
+ backup = []
+ backend.mockReset()
+ backend.mockImplementation(async (cmd: string, args?: { keep?: string[] }) => {
+ if (cmd === 'chat_backup_conversations') return JSON.stringify(backup)
+ if (cmd === 'chat_backup_clear') {
+ const keep = new Set(args?.keep ?? [])
+ const before = backup.length
+ backup = backup.filter((c) => keep.has(c.id))
+ return before - backup.length
+ }
+ if (cmd === 'chat_backup_reveal') return '/data/stores'
+ throw new Error(`unexpected ${cmd}`)
+ })
+ ls = memory()
+ Object.defineProperty(globalThis, 'localStorage', { value: ls, configurable: true, writable: true })
+ __resetDeletionNoteForTests()
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+})
+
+afterEach(() => {
+ __resetDeletionNoteForTests()
+ Object.defineProperty(globalThis, 'localStorage', { value: savedLs, configurable: true, writable: true })
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+})
+
+const live = () => useChatStore.getState().conversations
+
+/** One start of the app: what the hint decides. */
+async function start(): Promise<string[] | null> {
+ const ids = await restorableChatIds(live)
+ return decideRescueHint(live().length, ids, ls) ? ids : null
+}
+
+describe('the 3.0.10 nag, reproduced', () => {
+ it('a count dismissal comes back with every chat deleted under 3.0.10 (the report)', () => {
+ // Under 3.0.10 nothing noted a deletion. The user had 2 chats and 5 in
+ // the backup, dismissed the hint at 3 offered, then deleted 2 more.
+ const at3010 = { ids: new Set<string>(), legacyCount: 3 }
+ expect(shouldShowRescueHint(2, ['d1', 'd2', 'd3'], at3010)).toBe(false)
+ // The old rule, kept for a 3.0.10 value: 5 > 3, the hint is back.
+ expect(shouldShowRescueHint(2, ['d1', 'd2', 'd3', 'd4', 'd5'], at3010)).toBe(true)
+ })
+
+ it('the first start of 3.1.0 carries that dismissal over, and it holds', async () => {
+ useChatStore.setState({ conversations: [chat('a'), chat('b')] })
+ backup = [chat('a'), chat('b'), ...['d1', 'd2', 'd3', 'd4', 'd5'].map((id) => chat(id))]
+ ls.setItem(RESCUE_HINT_DISMISSED_KEY, '3')
+ expect(await start()).toBeNull()
+ expect([...readDismissal(ls).ids].sort()).toEqual(['d1', 'd2', 'd3', 'd4', 'd5'])
+ expect(readDismissal(ls).legacyCount).toBeNull()
+ expect(await start()).toBeNull()
+ expect(await start()).toBeNull()
+ })
+
+ it('NEGATIVE CONTROL: a chat lost after that still brings the hint', async () => {
+ useChatStore.setState({ conversations: [chat('a')] })
+ backup = [chat('a'), chat('d1'), chat('d2')]
+ ls.setItem(RESCUE_HINT_DISMISSED_KEY, '2')
+ expect(await start()).toBeNull()
+ backup.push(chat('lost1'), chat('lost2'))
+ expect(await start()).toEqual(expect.arrayContaining(['lost1', 'lost2']))
+ })
+
+ it('NEGATIVE CONTROL: an empty chat list at the first 3.1.0 start shows, whatever was dismissed (perrt)', async () => {
+ backup = [chat('x'), chat('y')]
+ ls.setItem(RESCUE_HINT_DISMISSED_KEY, '5')
+ expect(await start()).toEqual(['x', 'y'])
+ })
+})
+
+describe('a dismissal lasts', () => {
+ it('deleting chats one by one after Dismiss never brings the hint back', async () => {
+ // perrt's case first: a list that came up with one new chat, three lost.
+ useChatStore.setState({ conversations: [chat('new')] })
+ backup = [chat('l1'), chat('l2'), chat('l3')]
+ installDeletionNote()
+ const offered = await start()
+ expect(offered).toEqual(['l1', 'l2', 'l3'])
+ rememberDismissed(ls, offered!)
+ // The user keeps chatting and deleting; the backup keeps every one.
+ for (const id of ['n1', 'n2', 'n3', 'n4']) {
+ useChatStore.setState({ conversations: [chat(id), ...live()] })
+ backup.push(chat(id))
+ useChatStore.getState().deleteConversation(id)
+ expect(await start()).toBeNull()
+ }
+ })
+
+ it('the backup offering fewer chats (archives rotated out) and then one of the old ones again stays quiet', async () => {
+ useChatStore.setState({ conversations: [] })
+ backup = [chat('l1'), chat('l2'), chat('l3')]
+ rememberDismissed(ls, ['l1', 'l2', 'l3'])
+ backup = [chat('l1')]
+ expect(await start()).toBeNull()
+ backup = [chat('l1'), chat('l2')]
+ expect(await start()).toBeNull()
+ })
+
+ it('the stored list is capped and keeps the newest', () => {
+ const many = Array.from({ length: RESCUE_HINT_DISMISSED_MAX + 20 }, (_, i) => `id${i}`)
+ rememberDismissed(ls, many)
+ const kept = [...readDismissal(ls).ids]
+ expect(kept).toHaveLength(RESCUE_HINT_DISMISSED_MAX)
+ expect(kept.at(-1)).toBe(`id${RESCUE_HINT_DISMISSED_MAX + 19}`)
+ })
+
+ it('an unreadable value counts as never dismissed', () => {
+ ls.setItem(RESCUE_HINT_DISMISSED_KEY, '{garbled')
+ expect(readDismissal(ls)).toEqual({ ids: new Set(), legacyCount: null })
+ })
+
+ it('is in the native backup, so a lost storage does not bring it back', () => {
+ expect(STORE_KEYS).toContain(RESCUE_HINT_DISMISSED_KEY)
+ })
+})
+
+describe('Settings: clear the backup, open its folder', () => {
+ it('clear hands over the chat list as it is now and the hint has nothing left to offer', async () => {
+ useChatStore.setState({ conversations: [chat('a'), chat('b')] })
+ backup = [chat('a'), chat('b'), chat('old1'), chat('old2'), chat('old3')]
+ expect(await restorableChatIds(live)).toEqual(['old1', 'old2', 'old3'])
+ expect(await clearChatBackup(live)).toBe(3)
+ expect(backend).toHaveBeenCalledWith('chat_backup_clear', { keep: ['a', 'b'] })
+ expect(await restorableChatIds(live)).toEqual([])
+ expect(live().map((c) => c.id)).toEqual(['a', 'b'])
+ })
+
+ it('open folder asks the app to show it', async () => {
+ await revealChatBackup()
+ expect(backend).toHaveBeenCalledWith('chat_backup_reveal')
+ })
+})
diff --git a/src/lib/__tests__/chat-rescue.test.ts b/src/lib/__tests__/chat-rescue.test.ts
index 160c7270..964ecddf 100644
--- a/src/lib/__tests__/chat-rescue.test.ts
+++ b/src/lib/__tests__/chat-rescue.test.ts
@@ -12,7 +12,11 @@ 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'
+import { chatsMissingFrom, restoreChatsFromBackup, countRestorableChats, shouldShowRescueHint, readDismissal, rememberDismissed } from '../chat-rescue'
+
+/** No dismissal yet, and N chat ids on offer. */
+const NONE = { ids: new Set<string>(), legacyCount: null }
+const ids = (n: number) => Array.from({ length: n }, (_, i) => `c${i}`)
// Static, like the store: a block below resets the modules, and a dynamic import would watch another store.
import { __resetDeletionNoteForTests, installDeletionNote } from '../chat-deletion-note'
import { readDeletedChats } from '../chat-deletions'
@@ -119,23 +123,23 @@ describe('a store backup picked by hand', () => {
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)
+ expect(shouldShowRescueHint(0, ids(12), NONE)).toBe(true)
+ expect(shouldShowRescueHint(0, ids(0), NONE)).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)
+ expect(shouldShowRescueHint(1, ids(40), NONE)).toBe(true)
// A couple of deleted chats in an archive is not that.
- expect(shouldShowRescueHint(30, 2, null)).toBe(false)
+ expect(shouldShowRescueHint(30, ids(2), NONE)).toBe(false)
})
- it('stays away after Dismiss until the backup holds more', () => {
+ it('stays away after Dismiss until a chat goes missing that was not offered then', () => {
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)
+ rememberDismissed(storage, ids(12))
+ expect([...readDismissal(storage).ids]).toEqual(ids(12))
+ expect(shouldShowRescueHint(0, ids(12), readDismissal(storage))).toBe(false)
+ expect(shouldShowRescueHint(0, ids(13), readDismissal(storage))).toBe(true)
})
})
@@ -257,7 +261,7 @@ describe('a chat deleted on purpose is not offered back, a lost one still is', (
const live = () => useChatStore.getState().conversations
expect(await countRestorableChats(live)).toBe(1)
- expect(shouldShowRescueHint(live().length, 1, null)).toBe(false)
+ expect(shouldShowRescueHint(live().length, ids(1), NONE)).toBe(false)
expect(await restoreChatsFromBackup(live, useChatStore.getState().importConversations)).toBe(1)
expect(live().map((c) => c.id).sort()).toEqual(['a', 'c'])
})
@@ -270,7 +274,7 @@ describe('a chat deleted on purpose is not offered back, a lost one still is', (
backupAnswer([chat308('a', 1), chat308('b', 2), chat308('c', 3)])
const restorable = await countRestorableChats(() => useChatStore.getState().conversations)
expect(restorable).toBe(0)
- expect(shouldShowRescueHint(0, restorable, null)).toBe(false)
+ expect(shouldShowRescueHint(0, ids(restorable), NONE)).toBe(false)
})
it('the check the other way: a list that came up empty is a loss, nothing is noted, every chat is offered', async () => {
@@ -283,7 +287,7 @@ describe('a chat deleted on purpose is not offered back, a lost one still is', (
backupAnswer([chat308('a', 100), chat308('b', 200), chat308('c', 300)])
const live = () => useChatStore.getState().conversations
expect(await countRestorableChats(live)).toBe(3)
- expect(shouldShowRescueHint(live().length, 3, null)).toBe(true)
+ expect(shouldShowRescueHint(live().length, ids(3), NONE)).toBe(true)
expect(await restoreChatsFromBackup(live, useChatStore.getState().importConversations)).toBe(3)
})
diff --git a/src/lib/chat-rescue.ts b/src/lib/chat-rescue.ts
index f6bfd7fa..65e72c18 100644
--- a/src/lib/chat-rescue.ts
+++ b/src/lib/chat-rescue.ts
@@ -58,7 +58,12 @@ export async function readBackupChats(): Promise<unknown[]> {
/** How many chats the backups hold that the store does not and that were not deleted on purpose. */
export async function countRestorableChats(live: () => readonly Conversation[]): Promise<number> {
- return offeredChats(live(), await readBackupChats()).length
+ return (await restorableChatIds(live)).length
+}
+
+/** The ids of those chats, for the launch hint (A26). */
+export async function restorableChatIds(live: () => readonly Conversation[]): Promise<string[]> {
+ return offeredChats(live(), await readBackupChats()).map((c) => c.id)
}
/**
@@ -78,32 +83,105 @@ export async function restoreChatsFromBackup(
// ── The hint at launch ───────────────────────────────────────────────────
-/** The count the user last dismissed the hint at. The hint comes back only for more. */
+/**
+ * What the user dismissed the hint for. Since A26 (3.1.0) a JSON list of the
+ * chat ids it offered then; up to 3.0.10 a bare count.
+ */
export const RESCUE_HINT_DISMISSED_KEY = 'lu-chat-rescue-hint-dismissed'
+/** Like DELETED_CHATS_MAX: a chat older than that is out of every backup file. */
+export const RESCUE_HINT_DISMISSED_MAX = 500
+
+/**
+ * A dismissal as stored. `ids` since A26; `legacyCount` is the 3.0.10 value,
+ * which only said how many chats were on offer when the user said no.
+ */
+export interface RescueDismissal {
+ ids: ReadonlySet<string>
+ legacyCount: number | null
+}
/**
* 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.
+ * among them is one the user has not dismissed the hint for yet.
+ *
+ * A26 (3.1.0, LU-Admin): up to 3.0.10 the dismissal kept only the count, and
+ * every chat deleted afterwards made the count larger and brought the hint
+ * back at the next start. Deleted chats are left out of `offered` since C46;
+ * the dismissal now holds the ids, so it lasts until a chat goes missing that
+ * the user has not seen in the hint.
+ *
+ * A 3.0.10 dismissal (a count, no ids) still counts as one here; the launch
+ * turns it into ids once (decideRescueHint).
*/
-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 shouldShowRescueHint(liveCount: number, offered: readonly string[], dismissed: RescueDismissal): boolean {
+ if (offered.length === 0) return false
+ if (dismissed.legacyCount !== null && offered.length <= dismissed.legacyCount) return false
+ if (offered.every((id) => dismissed.ids.has(id))) return false
+ return liveCount === 0 || offered.length > liveCount
}
-export function readDismissedAt(storage: Pick<Storage, 'getItem'> | null): number | null {
+export function readDismissal(storage: Pick<Storage, 'getItem'> | null): RescueDismissal {
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
- }
+ if (raw == null) return { ids: new Set(), legacyCount: null }
+ const value: unknown = JSON.parse(raw)
+ if (Array.isArray(value)) return { ids: new Set(value.filter((v): v is string => typeof v === 'string')), legacyCount: null }
+ if (typeof value === 'number' && Number.isFinite(value)) return { ids: new Set(), legacyCount: value }
+ } catch { /* unreadable: as if never dismissed */ }
+ return { ids: new Set(), legacyCount: null }
+}
+
+/** Remember that the hint was dismissed for these chats, on top of the ones before. */
+export function rememberDismissed(storage: Pick<Storage, 'getItem' | 'setItem'> | null, offered: readonly string[]): void {
+ try {
+ const before = readDismissal(storage).ids
+ const add = new Set(offered)
+ const list = [...before].filter((id) => !add.has(id)).concat(offered)
+ storage?.setItem(RESCUE_HINT_DISMISSED_KEY, JSON.stringify(list.slice(-RESCUE_HINT_DISMISSED_MAX)))
+ } catch { /* a hint that comes back is harmless */ }
+}
+
+/**
+ * The launch decision in one place: whether the hint shows for these chats.
+ * A 3.0.10 dismissal is turned into ids right here, once: the chats on offer
+ * at the first start after the update count as dismissed, unless the chat
+ * list is empty. A chat that goes missing from then on is new against it.
+ */
+export function decideRescueHint(
+ liveCount: number,
+ offered: readonly string[],
+ storage: Pick<Storage, 'getItem' | 'setItem'> | null,
+): boolean {
+ const dismissed = readDismissal(storage)
+ if (dismissed.legacyCount === null) return shouldShowRescueHint(liveCount, offered, dismissed)
+ try { storage?.setItem(RESCUE_HINT_DISMISSED_KEY, '[]') } catch { /* see rememberDismissed */ }
+ // An empty chat list is the loss the hint is for (perrt): it shows, whatever was dismissed under 3.0.10.
+ if (liveCount === 0) return shouldShowRescueHint(liveCount, offered, readDismissal(storage))
+ // Everything on offer now was there when the user said no under 3.0.10, or
+ // was deleted under 3.0.10 since, which nothing noted then (the nag A26 is about).
+ rememberDismissed(storage, offered)
+ return false
+}
+
+// ── Clear backup, open folder (A26) ──────────────────────────────────────
+
+/**
+ * Take every chat out of the backup files that is not in the chat list now.
+ * Returns how many left. They cannot be restored afterwards; the chat list
+ * itself and every other store in the files stay as they are.
+ */
+export async function clearChatBackup(live: () => readonly Conversation[]): Promise<number> {
+ if (!isTauri()) return 0
+ const keep = live().map((c) => c.id)
+ const removed = await backendCall<number>('chat_backup_clear', { keep })
+ log.warn('[chat-rescue] chats cleared from the backup files', { count: removed })
+ return removed
}
-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 */ }
+/** Show the backup folder in Finder, Explorer or the file manager. */
+export async function revealChatBackup(): Promise<void> {
+ if (!isTauri()) return
+ await backendCall<string>('chat_backup_reveal')
}
diff --git a/src/lib/store-backup.ts b/src/lib/store-backup.ts
index 4f358f1e..4942d191 100644
--- a/src/lib/store-backup.ts
+++ b/src/lib/store-backup.ts
@@ -101,6 +101,10 @@ export const STORE_KEYS = [
// (lib/chat-deletions.ts). The chat archives of the backup keep them; after
// a lost storage this note keeps the restore from offering them back.
'lu-chats-deleted',
+ // A26 (3.1.0): the chats the restore hint was dismissed for
+ // (lib/chat-rescue.ts). Without it a lost storage brought the hint back
+ // for chats the user had already said no to.
+ 'lu-chat-rescue-hint-dismissed',
// Round 3 (M8). Found missing by the review: the text of the backup says
// "chats and settings", and these did not come back.
// lu-mobile-remote the chats held with a paired desktop, on
diff --git a/src/mobile/boot/__tests__/settings-durable.test.ts b/src/mobile/boot/__tests__/settings-durable.test.ts
index 9afbf0fb..a2b9c5a5 100644
--- a/src/mobile/boot/__tests__/settings-durable.test.ts
+++ b/src/mobile/boot/__tests__/settings-durable.test.ts
@@ -118,6 +118,7 @@ describe('which keys are kept', () => {
'lu-mobile-switched-under-answer': 'a note per answer; lost, the chat says "interrupted" instead of "you switched models"',
'lu-mobile-settings-stamp': 'the stamp of this copy itself; in the native backup it dates the settings there (L5)',
'lu-chats-deleted': 'chats deleted on purpose (C46); lost, the restore hint offers them once and Not now keeps it away',
+ 'lu-chat-rescue-hint-dismissed': 'the chats the restore hint was dismissed for (A26); lost, the hint shows once more and Not now keeps it away',
}
for (const key of STORE_KEYS) {
const copied = DURABLE_SETTINGS_KEYS.includes(key)
diff --git a/src/mobile/screens/chat/parts/adapters/chat-rescue-hint.ts b/src/mobile/screens/chat/parts/adapters/chat-rescue-hint.ts
index a8a906b7..4e6861f3 100644
--- a/src/mobile/screens/chat/parts/adapters/chat-rescue-hint.ts
+++ b/src/mobile/screens/chat/parts/adapters/chat-rescue-hint.ts
@@ -2,7 +2,7 @@
* The hint in the chat list (C46, 3.1.0): the automatic backup holds chats
* the list does not. Same rule as the desktop (lib/chat-rescue.ts,
* shouldShowRescueHint): more chats in the backup than in the list, or an
- * empty list, and not dismissed at this count. It only says so; the chats
+ * empty list, and one among them the hint was not dismissed for (A26). It only says so; the chats
* come back when the user taps Restore.
*
* Asked once per start, after the restore at the start has decided (it may
@@ -10,7 +10,7 @@
*/
import { create } from 'zustand'
import { isTauri } from '../../../../../api/backend'
-import { readDismissedAt, rememberDismissed, shouldShowRescueHint } from '../../../../../lib/chat-rescue'
+import { decideRescueHint, rememberDismissed } from '../../../../../lib/chat-rescue'
import { useChatStore } from '../../../../../stores/chatStore'
import { restoreDecided } from '../../../../boot/restore'
import { restorableChats, restoreChatsFromPhoneBackup } from '../../../../lib/chat-rescue'
@@ -24,10 +24,12 @@ export type RescueOutcome = 'restored' | 'not-saved' | 'failed'
interface RescueHintState {
/** Chats the hint offers. 0: no hint. */
count: number
+ /** Their ids, for a dismissal that lasts (A26). */
+ ids: string[]
busy: boolean
}
-export const useRescueHint = create<RescueHintState>(() => ({ count: 0, busy: false }))
+export const useRescueHint = create<RescueHintState>(() => ({ count: 0, ids: [], busy: false }))
function local(): Pick<Storage, 'getItem' | 'setItem'> | null {
try {
@@ -49,8 +51,8 @@ export function lookForRescue(wait: (ms: number) => Promise<void> = (ms) => new
else useChatStore.persist.onFinishHydration(() => resolve())
})
await wait(LOOK_AFTER_MS)
- const restorable = (await restorableChats()).length
- if (shouldShowRescueHint(useChatStore.getState().conversations.length, restorable, readDismissedAt(local()))) useRescueHint.setState({ count: restorable })
+ const ids = (await restorableChats()).map((c) => c.id)
+ if (decideRescueHint(useChatStore.getState().conversations.length, ids, local())) useRescueHint.setState({ count: ids.length, ids })
})().catch(() => {
/* no hint is the behaviour before C46 */
})
@@ -63,7 +65,7 @@ export async function restoreFromHint(): Promise<{ outcome: RescueOutcome; added
try {
const ids = await restoreChatsFromPhoneBackup()
const written = ids.length === 0 || (await chatsAreWritten({ present: ids }))
- useRescueHint.setState({ count: 0 })
+ useRescueHint.setState({ count: 0, ids: [] })
return { outcome: written ? 'restored' : 'not-saved', added: ids.length }
} catch {
return { outcome: 'failed', added: 0 }
@@ -72,14 +74,14 @@ export async function restoreFromHint(): Promise<{ outcome: RescueOutcome; added
}
}
-/** "Not now": the hint comes back only when the backup holds more chats than now. */
+/** "Not now": the hint comes back only for a chat that goes missing after this (A26). */
export function dismissRescueHint(): void {
- rememberDismissed(local(), useRescueHint.getState().count)
- useRescueHint.setState({ count: 0 })
+ rememberDismissed(local(), useRescueHint.getState().ids)
+ useRescueHint.setState({ count: 0, ids: [] })
}
/** Only for tests. */
export function __resetRescueHintForTests(): void {
looked = null
- useRescueHint.setState({ count: 0, busy: false })
+ useRescueHint.setState({ count: 0, ids: [], busy: false })
}