π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Clean up Ensu chat storage lifecycle
Manav Rathi7776c5b75484
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/AttachmentStoreActions.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/AttachmentStoreActions.ktindex b29f59edef..8999477237 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/AttachmentStoreActions.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/AttachmentStoreActions.kt@@ -39,6 +39,7 @@ internal class AttachmentStoreActions(}fun addAttachment(attachment: Attachment) {+ var accepted = falsestate.update { appState ->val chat = appState.chatval imageLimitReached = attachment.type == AttachmentType.Image &&@@ -53,6 +54,7 @@ internal class AttachmentStoreActions(chat = chat.copy(isProcessingAttachments = false))} else {+ accepted = trueappState.copy(chat = chat.copy(attachments = chat.attachments + attachment,@@ -61,6 +63,7 @@ internal class AttachmentStoreActions()}}+ if (!accepted) deleteIfUnstored(attachment)}fun removeAttachment(attachment: Attachment) {@@ -71,6 +74,11 @@ internal class AttachmentStoreActions())}+ deleteIfUnstored(attachment)+ }++ fun discardAttachments(attachments: List<Attachment>) {+ attachments.forEach(::deleteIfUnstored)}fun cancelAttachmentDownload(attachmentId: String) {@@ -143,6 +151,13 @@ internal class AttachmentStoreActions(updateAttachmentDownloadState()}+ private fun deleteIfUnstored(attachment: Attachment) {+ val stored = messageStore.values.any { messages ->+ messages.any { message -> message.attachments.any { it.id == attachment.id } }+ }+ if (!stored) attachment.localPath?.let { File(it).delete() }+ }+private fun queueAttachmentDownloads(items: List<AttachmentDownloadItem>) {items.forEach { item ->val existing = attachmentDownloads[item.id]diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.ktindex 604449d6a2..a7ef2bb2da 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.kt@@ -27,6 +27,10 @@ class ChatRepository(private val dbKey = credentialStore.getOrCreateChatDbKey(filePaths.hasChatData)private var db: EnsuDb = openDb(dbFile, dbKey)+ init {+ pruneOrphanedAttachments()+ }+fun listSessions(): List<ChatSession> = withDbRecovery {val sessions = db.listSessions()sessions.map { session ->@@ -55,7 +59,9 @@ class ChatRepository(}fun deleteSession(sessionId: String) = withDbRecovery {- db.deleteSession(sessionId)+ db.deleteSession(sessionId).forEach { id ->+ File(attachmentsDir, id).delete()+ }}fun getMessages(sessionId: String): List<ChatMessage> = withDbRecovery {@@ -165,6 +171,19 @@ class ChatRepository(db = openDb(dbFile, dbKey)}+ private fun pruneOrphanedAttachments() {+ val referenced = try {+ db.listSessions().flatMap { session -> db.getMessages(session.uuid) }+ .flatMap { message -> message.attachments }+ .mapTo(mutableSetOf()) { attachment -> attachment.id }+ } catch (_: DbException) {+ return+ }+ attachmentsDir.listFiles()?.forEach { file ->+ if (file.isFile && file.name !in referenced) file.delete()+ }+ }+private fun isReadonlyDbError(error: DbException): Boolean {return error is DbException.ReadonlyDatabase}diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.ktindex e2b4586cea..38aa783bde 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt@@ -124,6 +124,7 @@ internal class ChatStoreActions(if (state.value.chat.isDownloading) returnresetGenerationState()+ attachmentActions.discardAttachments(state.value.chat.attachments)state.update { appState ->appState.copy(chat = appState.chat.copy(@@ -165,6 +166,7 @@ internal class ChatStoreActions(}chatRepository.deleteSession(sessionId)+ if (isCurrent) attachmentActions.discardAttachments(currentState.chat.attachments)removeSessionCaches(sessionId)attachmentActions.purgeAttachmentDownloads(sessionId)sessionSummaries.remove(sessionKey(sessionId))@@ -271,6 +273,7 @@ internal class ChatStoreActions(}fun cancelEditing() {+ attachmentActions.discardAttachments(state.value.chat.attachments)state.update { appState ->appState.copy(chat = appState.chat.copy(diff --git a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swiftindex e8bf035a52..f48158354f 100644--- a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift+++ b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift@@ -151,7 +151,15 @@ final class ChatViewModel: ObservableObject {}// Load sessions/messages.- let loaded = (try? chatDb.listSessions()) ?? []+ let loadedResult = try? chatDb.listSessions()+ if let loadedResult {+ Self.pruneOrphanedAttachments(+ sessions: loadedResult,+ chatDb: chatDb,+ attachmentsDir: attachmentsDir+ )+ }+ let loaded = loadedResult ?? []let sessions = Self.buildSessions(from: loaded, chatDb: chatDb, summaries: summaries)// Stored properties.@@ -204,6 +212,7 @@ final class ChatViewModel: ObservableObject {downloadProgressMonitorTask?.cancel()sharedModelReadyTask?.cancel()clearSharedModelReadyTask()+ discardUnstoredAttachments(draftAttachments)editingMessageId = nildraftText = ""draftAttachments = []@@ -309,6 +318,7 @@ final class ChatViewModel: ObservableObject {resetGenerationState()cancelVoiceInput()+ discardUnstoredAttachments(draftAttachments)draftText = ""draftAttachments = []editingMessageId = nil@@ -337,7 +347,15 @@ final class ChatViewModel: ObservableObject {}}logger.info("Session deleted", details: "id=\(session.id.uuidString)")- try? chatDb.deleteSession(uuid: session.id.uuidString)+ guard let attachmentIds = try? chatDb.deleteSession(uuid: session.id.uuidString) else {+ return+ }+ if currentSessionId == session.id {+ discardUnstoredAttachments(draftAttachments)+ }+ for id in attachmentIds {+ try? FileManager.default.removeItem(at: attachmentsDir.appendingPathComponent(id))+ }sessionSummaries.removeValue(forKey: sessionSummaryKey(session.id))persistSessionSummaries()@@ -370,6 +388,7 @@ final class ChatViewModel: ObservableObject {}func cancelEditing() {+ discardUnstoredAttachments(draftAttachments)editingMessageId = nildraftText = ""draftAttachments = []@@ -542,6 +561,41 @@ final class ChatViewModel: ObservableObject {func removeAttachment(_ attachment: ChatAttachment) {draftAttachments.removeAll { $0.id == attachment.id }+ discardUnstoredAttachments([attachment])+ }++ private func discardUnstoredAttachments(_ attachments: [ChatAttachment]) {+ let storedIds = Set(messageStore.values.flatMap { messages in+ messages.flatMap { $0.attachments.map(\.id) }+ })+ for attachment in attachments where !storedIds.contains(attachment.id) {+ if let url = attachment.url {+ try? FileManager.default.removeItem(at: url)+ }+ }+ }++ private static func pruneOrphanedAttachments(+ sessions: [DbSession],+ chatDb: EnsuDb,+ attachmentsDir: URL+ ) {+ let referenced: Set<String>+ do {+ referenced = Set(try sessions.flatMap { session in+ try chatDb.getMessages(sessionUuid: session.uuid)+ .flatMap { $0.attachments.map(\.id) }+ })+ } catch {+ return+ }+ guard let files = try? FileManager.default.contentsOfDirectory(+ at: attachmentsDir,+ includingPropertiesForKeys: nil+ ) else { return }+ for file in files where !referenced.contains(file.lastPathComponent) {+ try? FileManager.default.removeItem(at: file)+ }}func sendDraft() {diff --git a/rust/apps/ensu/src-tauri/src/commands/chat_db.rs b/rust/apps/ensu/src-tauri/src/commands/chat_db.rsindex 31e4d9ec18..c59595c48a 100644--- a/rust/apps/ensu/src-tauri/src/commands/chat_db.rs+++ b/rust/apps/ensu/src-tauri/src/commands/chat_db.rs@@ -312,7 +312,7 @@ pub async fn chat_db_delete_session(app: AppHandle,key_b64: String,session_uuid: String,-) -> Result<(), ApiError> {+) -> Result<Vec<String>, ApiError> {let uuid = parse_uuid(&session_uuid)?;with_chat_db_async(&state, app, key_b64, move |db| db.delete_session(uuid)).await}@@ -590,13 +590,26 @@ fn import_v1_chat_db(app: &AppHandle, input: &ChatDbImportV1Input) -> Result<(),return Ok(());}- let v1_attachments_dir = v1_attachments_dir_path(app)?;- let target_attachments_dir = attachments_dir_path(app)?;let key = crypto::decode_b64(&input.key_b64).map_err(ApiError::from)?;+ import_v1_chat_db_paths(+ &v1_db_path,+ &v1_attachments_dir_path(app)?,+ &chat_db_path(app)?,+ &attachments_dir_path(app)?,+ key,+ )+}++fn import_v1_chat_db_paths(+ v1_db_path: &Path,+ v1_attachments_dir: &Path,+ target_db_path: &Path,+ target_attachments_dir: &Path,+ key: Vec<u8>,+) -> Result<(), ApiError> {let v1_db =ChatDb::open_sqlite_with_defaults(&v1_db_path, key.clone()).map_err(ApiError::from)?;- let target =- ChatDb::open_sqlite_with_defaults(chat_db_path(app)?, key).map_err(ApiError::from)?;+ let target = ChatDb::open_sqlite_with_defaults(target_db_path, key).map_err(ApiError::from)?;for session in v1_db.list_sessions().map_err(ApiError::from)? {target@@ -637,6 +650,99 @@ fn import_v1_chat_db(app: &AppHandle, input: &ChatDbImportV1Input) -> Result<(),Ok(())}+#[cfg(test)]+mod tests {+ use super::*;+ use ente_ensu::db::{AttachmentKind, AttachmentMeta};++ fn migration_fixture() -> PathBuf {+ let root = std::env::temp_dir().join(format!("ensu-import-{}", Uuid::new_v4()));+ fs::create_dir_all(root.join("source-attachments")).unwrap();+ fs::create_dir_all(root.join("target-attachments")).unwrap();+ root+ }++ fn seed_source(root: &Path, key: &[u8]) -> (Uuid, String) {+ let source =+ ChatDb::open_sqlite_with_defaults(root.join("source.db"), key.to_vec()).unwrap();+ let session = source.create_session("Migrated chat").unwrap();+ let attachment_id = Uuid::new_v4().to_string();+ source+ .insert_message(+ session.uuid,+ "self",+ "Migrated message",+ None,+ vec![AttachmentMeta {+ id: attachment_id.clone(),+ kind: AttachmentKind::Document,+ size: 7,+ name: "note.txt".to_string(),+ }],+ )+ .unwrap();+ fs::write(+ root.join("source-attachments").join(&attachment_id),+ b"payload",+ )+ .unwrap();+ (session.uuid, attachment_id)+ }++ fn import_fixture(root: &Path, key: Vec<u8>) -> Result<(), ApiError> {+ import_v1_chat_db_paths(+ &root.join("source.db"),+ &root.join("source-attachments"),+ &root.join("target.db"),+ &root.join("target-attachments"),+ key,+ )+ }++ #[test]+ fn v1_import_is_restart_safe() {+ let root = migration_fixture();+ let key = vec![7; 32];+ let (session_id, attachment_id) = seed_source(&root, &key);++ import_fixture(&root, key.clone()).unwrap();+ import_fixture(&root, key.clone()).unwrap();++ let target = ChatDb::open_sqlite_with_defaults(root.join("target.db"), key).unwrap();+ assert_eq!(target.list_sessions().unwrap()[0].title, "Migrated chat");+ let messages = target.get_messages(session_id).unwrap();+ assert_eq!(messages.len(), 1);+ assert_eq!(messages[0].text, "Migrated message");+ assert_eq!(messages[0].attachments[0].name, "note.txt");+ assert_eq!(+ fs::read(root.join("target-attachments").join(attachment_id)).unwrap(),+ b"payload"+ );+ assert!(root.join("source.db").exists());+ fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn v1_import_recovers_after_wrong_key() {+ let root = migration_fixture();+ let key = vec![8; 32];+ let (session_id, attachment_id) = seed_source(&root, &key);++ assert!(import_fixture(&root, vec![9; 32]).is_err());+ assert!(root.join("source.db").exists());+ assert!(+ root.join("source-attachments")+ .join(&attachment_id)+ .exists()+ );++ import_fixture(&root, key.clone()).unwrap();+ let target = ChatDb::open_sqlite_with_defaults(root.join("target.db"), key).unwrap();+ assert_eq!(target.get_messages(session_id).unwrap().len(), 1);+ fs::remove_dir_all(root).unwrap();+ }+}+fn with_chat_db<T, F>(inner: &Arc<Mutex<Option<ChatDbHolder>>>,app: &AppHandle,diff --git a/rust/bindings/uniffi/ensu/src/db.rs b/rust/bindings/uniffi/ensu/src/db.rsindex 5a2a63abc2..df864b53ae 100644--- a/rust/bindings/uniffi/ensu/src/db.rs+++ b/rust/bindings/uniffi/ensu/src/db.rs@@ -232,7 +232,7 @@ impl EnsuDb {Ok(self.inner.get_session(uuid)?.map(to_session))}- pub fn delete_session(&self, uuid: String) -> Result<(), DbError> {+ pub fn delete_session(&self, uuid: String) -> Result<Vec<String>, DbError> {let uuid = Uuid::parse_str(&uuid).map_err(invalid_uuid)?;Ok(self.inner.delete_session(uuid)?)}diff --git a/rust/crates/ensu/src/db/chat/mod.rs b/rust/crates/ensu/src/db/chat/mod.rsindex ca61ee7f94..d6a4f8ba21 100644--- a/rust/crates/ensu/src/db/chat/mod.rs+++ b/rust/crates/ensu/src/db/chat/mod.rs@@ -1,6 +1,7 @@pub mod migrations;pub mod schema;+use std::collections::BTreeSet;use std::sync::Arc;use uuid::Uuid;@@ -110,12 +111,26 @@ impl<B: Backend> ChatDb<B> {ensure_row_updated(affected, EntityType::Session, uuid)}- pub fn delete_session(&self, uuid: Uuid) -> Result<()> {- let affected = self.backend.execute(- "DELETE FROM sessions WHERE session_uuid = ?",- &[Value::Text(uuid.to_string())],- )?;- ensure_row_updated(affected, EntityType::Session, uuid)+ pub fn delete_session(&self, uuid: Uuid) -> Result<Vec<String>> {+ self.backend.transaction(|tx| {+ let rows = tx.query(+ "SELECT attachments FROM messages WHERE session_uuid = ?",+ &[Value::Text(uuid.to_string())],+ )?;+ let mut attachment_ids = BTreeSet::new();+ for row in rows {+ for attachment in parse_stored_attachments(row.get_optional_string(0)?)? {+ attachment_ids.insert(attachment.id);+ }+ }++ let affected = tx.execute(+ "DELETE FROM sessions WHERE session_uuid = ?",+ &[Value::Text(uuid.to_string())],+ )?;+ ensure_row_updated(affected, EntityType::Session, uuid)?;+ Ok(attachment_ids.into_iter().collect())+ })}pub fn upsert_session(@@ -383,16 +398,22 @@ impl ChatDb<crate::db::backend::sqlite::SqliteBackend> {clock: Arc<dyn Clock>,uuid_gen: Arc<dyn UuidGen>,) -> Result<Self> {+ let path = path.as_ref();let backend = crate::db::backend::sqlite::SqliteBackend::open(path)?;- Self::new(backend, key, clock, uuid_gen)+ let db = Self::new(backend, key, clock, uuid_gen)?;+ cleanup_obsolete_sync_storage(path);+ Ok(db)}pub fn open_sqlite_with_defaults(path: impl AsRef<std::path::Path>,key: Vec<u8>,) -> Result<Self> {+ let path = path.as_ref();let backend = crate::db::backend::sqlite::SqliteBackend::open(path)?;- Self::new_with_defaults(backend, key)+ let db = Self::new_with_defaults(backend, key)?;+ cleanup_obsolete_sync_storage(path);+ Ok(db)}pub fn open_in_memory(key: Vec<u8>) -> Result<Self> {@@ -401,6 +422,21 @@ impl ChatDb<crate::db::backend::sqlite::SqliteBackend> {}}+#[cfg(feature = "sqlite")]+fn cleanup_obsolete_sync_storage(db_path: &std::path::Path) {+ let Some(root) = db_path.parent() else {+ return;+ };+ for name in ["llmchat_sync.db", "llmchat_sync_v2.db", "llmchat_online.db"] {+ for suffix in ["", "-wal", "-shm"] {+ let _ = std::fs::remove_file(root.join(format!("{name}{suffix}")));+ }+ }+ for name in ["llmchat", "sync_meta"] {+ let _ = std::fs::remove_dir_all(root.join(name));+ }+}+fn validate_key(key: Vec<u8>) -> Result<Zeroizing<Vec<u8>>> {if key.len() != crypto::KEY_BYTES {return Err(Error::InvalidKeyLength {@@ -561,14 +597,98 @@ mod tests {let db = make_db(vec![session_id, message_id], Arc::new(StepClock::new(1, 1)));db.create_session("title").unwrap();- db.insert_message(session_id, "other", "hi", None, Vec::new())- .unwrap();- db.delete_session(session_id).unwrap();+ db.insert_message(+ session_id,+ "other",+ "hi",+ None,+ vec![AttachmentMeta {+ id: "attachment".to_string(),+ kind: AttachmentKind::Document,+ size: 1,+ name: "note.txt".to_string(),+ }],+ )+ .unwrap();+ assert_eq!(+ db.delete_session(session_id).unwrap(),+ vec!["attachment".to_string()]+ );assert!(db.get_session(session_id).unwrap().is_none());assert!(db.get_message(message_id).unwrap().is_none());}+ #[test]+ fn sqlite_open_removes_obsolete_sync_storage() {+ let root = std::env::temp_dir().join(format!("ensu-db-{}", Uuid::new_v4()));+ std::fs::create_dir_all(root.join("sync_meta")).unwrap();+ std::fs::create_dir_all(root.join("llmchat")).unwrap();+ for name in [+ "llmchat_sync.db",+ "llmchat_sync.db-wal",+ "llmchat_sync_v2.db",+ "llmchat_online.db",+ ] {+ std::fs::write(root.join(name), b"obsolete").unwrap();+ }++ ChatDb::open_sqlite_with_defaults(root.join("llmchat.db"), vec![1u8; KEY_BYTES]).unwrap();++ assert!(!root.join("llmchat_sync.db").exists());+ assert!(!root.join("llmchat_sync.db-wal").exists());+ assert!(!root.join("llmchat_sync_v2.db").exists());+ assert!(!root.join("llmchat_online.db").exists());+ assert!(!root.join("sync_meta").exists());+ assert!(!root.join("llmchat").exists());+ std::fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn on_disk_v4_migration_survives_reopen() {+ let root = std::env::temp_dir().join(format!("ensu-v4-{}", Uuid::new_v4()));+ std::fs::create_dir_all(&root).unwrap();+ let path = root.join("llmchat.db");+ let key = vec![2u8; KEY_BYTES];+ let (session_id, message_id) = {+ let db = ChatDb::open_sqlite_with_defaults(&path, key.clone()).unwrap();+ let session = db.create_session("Before migration").unwrap();+ let message = db+ .insert_message(session.uuid, "self", "Still here", None, Vec::new())+ .unwrap();+ (session.uuid, message.uuid)+ };+ {+ let backend = SqliteBackend::open(&path).unwrap();+ backend+ .execute_batch(+ "ALTER TABLE sessions ADD COLUMN server_updated_at INTEGER;+ ALTER TABLE sessions ADD COLUMN remote_id TEXT;+ ALTER TABLE sessions ADD COLUMN needs_sync INTEGER NOT NULL DEFAULT 1;+ ALTER TABLE sessions ADD COLUMN deleted_at INTEGER;+ ALTER TABLE messages ADD COLUMN remote_id TEXT;+ ALTER TABLE messages ADD COLUMN server_updated_at INTEGER;+ ALTER TABLE messages ADD COLUMN needs_sync INTEGER NOT NULL DEFAULT 1;+ ALTER TABLE messages ADD COLUMN deleted_at INTEGER;+ PRAGMA user_version = 4;",+ )+ .unwrap();+ }++ for _ in 0..2 {+ let db = ChatDb::open_sqlite_with_defaults(&path, key.clone()).unwrap();+ assert_eq!(+ db.get_session(session_id).unwrap().unwrap().title,+ "Before migration"+ );+ assert_eq!(+ db.get_message(message_id).unwrap().unwrap().text,+ "Still here"+ );+ }+ std::fs::remove_dir_all(root).unwrap();+ }+#[test]fn attachment_metadata_is_encrypted_in_json() {let session_id = Uuid::from_u128(6);diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsxindex 7a7699dab4..f718e061dd 100644--- a/web/apps/ensu/src/pages/chat.tsx+++ b/web/apps/ensu/src/pages/chat.tsx@@ -15,12 +15,13 @@ import {getOrCreateLocalChatKey,initChatKeyStore,} from "@/services/chat/chatKey";+import { initializeChatStorePersistence } from "@/services/chat/migration";import {addMessage,createSession,+ deleteAttachmentBytes,deleteSession,getBranchSelections,- initializeChatStorePersistence,listMessages,listSessions,readDecryptedAttachmentBytes,@@ -3707,6 +3708,27 @@ const Page: React.FC = () => {trimmed.replace(/\u0000/g, ""),pendingDocuments,);+ const persistedAttachmentIds = new Set(+ (editingMessage?.attachments ?? []).map(({ id }) => id),+ );+ const newAttachmentIds = [+ ...pendingDocuments.map(({ id }) => id),+ ...pendingImages.map(({ id }) => id),+ ].filter((id) => !persistedAttachmentIds.has(id));+ const cleanupUnstoredAttachments = async () => {+ await Promise.all(+ newAttachmentIds.map(async (id) => {+ try {+ await deleteAttachmentBytes(id);+ } catch (error) {+ log.warn(+ `Failed to clean up attachment payload ${id}`,+ error,+ );+ }+ }),+ );+ };let inferenceImagePaths: string[] = [];let attachments: ChatAttachment[] = [];@@ -3759,6 +3781,7 @@ const Page: React.FC = () => {);attachments = [...documentAttachments, ...imageAttachments];} catch (error) {+ await cleanupUnstoredAttachments();log.error("Failed to store attachments", error);showMiniDialog({title: "Attachment error",@@ -3772,6 +3795,7 @@ const Page: React.FC = () => {try {inferenceImagePaths = await writeInferenceImages(pendingImages);} catch (error) {+ await cleanupUnstoredAttachments();log.error("Failed to prepare images for inference", error);showMiniDialog({title: "Attachment error",@@ -3789,6 +3813,7 @@ const Page: React.FC = () => {setInput("");+ let messageStored = false;try {if (editingMessage) {const parentUuid = editingMessage.parentMessageUuid;@@ -3805,6 +3830,7 @@ const Page: React.FC = () => {parentUuid,attachments,);+ messageStored = true;void updateBranchSelectionState(selectionKey,@@ -3840,6 +3866,7 @@ const Page: React.FC = () => {parentUuid,attachments,);+ messageStored = true;void updateBranchSelectionState(selectionKey,@@ -3859,6 +3886,7 @@ const Page: React.FC = () => {mediaMarker: MEDIA_MARKER,});} catch (error) {+ if (!messageStored) await cleanupUnstoredAttachments();log.error("Failed to store chat message", error);} finally {await cleanupInferenceImages(inferenceImagePaths);diff --git a/web/apps/ensu/src/services/chat/chatKey.ts b/web/apps/ensu/src/services/chat/chatKey.tsindex 4317be3370..64c621a8aa 100644--- a/web/apps/ensu/src/services/chat/chatKey.ts+++ b/web/apps/ensu/src/services/chat/chatKey.ts@@ -1,21 +1,10 @@import { isTauriRuntime } from "@/services/tauri-runtime";-import { removeKV } from "ente-base/kv";-import {- secureStorageDelete,- secureStorageGet,- secureStorageSet,-} from "../secure-storage";+import { secureStorageGet, secureStorageSet } from "../secure-storage";import { ensureCryptoInit, enteWasm } from "../wasm";+import { hasRetiredLocalChatStore, promoteLocalChatKey } from "./keyMigration";const LOCAL_KEY = "ensu.chatKey.local";-const LOCAL_STORE = "ensu.chat.store.v1";-const MIGRATION_DONE = "ensu.chat.localMigration.v3";const CURRENT_SECURE_KEY = "localChatKey.v2";-const V1_LOCAL_SECURE_KEY = "localChatKey";-const V1_ATTACHMENT_SECURE_KEY = "legacyAttachmentKey.v2";-const KEY_FILE = "chat-keys.json";--type NativeChatKeys = { localChatKey?: string };let _localKey: string | undefined;let _initPromise: Promise<void> | undefined;@@ -25,49 +14,17 @@ const localGet = (key: string) =>? undefined: (localStorage.getItem(key) ?? undefined);-const keyFilePath = async () => {- const { appDataDir, join } = await import("@tauri-apps/api/path");- return join(await appDataDir(), KEY_FILE);-};--const readKeyFile = async (): Promise<NativeChatKeys> => {- const [{ exists, readFile }, path] = await Promise.all([- import("@tauri-apps/plugin-fs"),- keyFilePath(),- ]);- if (!(await exists(path))) return {};- try {- const parsed = JSON.parse(- new TextDecoder().decode(await readFile(path)),- ) as NativeChatKeys;- return typeof parsed.localChatKey === "string" ? parsed : {};- } catch {- return {};- }-};--export const isLocalChatMigrationDone = () => localGet(MIGRATION_DONE) === "1";-export const initChatKeyStore = async () => {if (!isTauriRuntime()) return;if (_initPromise) return _initPromise;_initPromise = (async () => {const current = await secureStorageGet(CURRENT_SECURE_KEY);- if (isLocalChatMigrationDone()) {- _localKey = current;- return;- }-- const [v1Local, file] = await Promise.all([- secureStorageGet(V1_LOCAL_SECURE_KEY),- readKeyFile(),- ]);- _localKey =- current ?? localGet(LOCAL_KEY) ?? v1Local ?? file.localChatKey;- if (_localKey && current !== _localKey) {- await secureStorageSet(CURRENT_SECURE_KEY, _localKey);- }+ _localKey = await promoteLocalChatKey(+ current,+ CURRENT_SECURE_KEY,+ LOCAL_KEY,+ );})().catch((error: unknown) => {_initPromise = undefined;throw error;@@ -97,7 +54,7 @@ export const getOrCreateLocalChatKey = async () => {const cached = cachedLocalChatKey();if (cached) return cached;if (- localGet(LOCAL_STORE) ||+ hasRetiredLocalChatStore() ||(isTauriRuntime() && (await hasNativeChatStore()))) {throw new Error("Existing chat data has no encryption key");@@ -108,59 +65,3 @@ export const getOrCreateLocalChatKey = async () => {await persistLocalKey(chatKey);return chatKey;};--const retiredUserID = () => {- try {- const user = JSON.parse(localStorage.getItem("user") ?? "null") as {- id?: unknown;- } | null;- const id = user?.id;- return typeof id === "number" ? id : undefined;- } catch {- return undefined;- }-};--export const finalizeLocalChatMigration = async () => {- if (!isTauriRuntime()) return;- const userID = retiredUserID();-- // The target DB and attachments have already been verified at this point.- const { invoke } = await import("@tauri-apps/api/core");- await invoke("chat_db_cleanup_v1");- localStorage.removeItem(LOCAL_STORE);- const secureKeys = [- V1_LOCAL_SECURE_KEY,- V1_ATTACHMENT_SECURE_KEY,- "masterKey",- "remoteChatKey",- ...(userID- ? [`remoteChatKey.${userID}`, `remoteChatKey.v2.${userID}`]- : []),- ];- await Promise.all(secureKeys.map(secureStorageDelete));-- const [{ exists, remove }, { appDataDir, join }] = await Promise.all([- import("@tauri-apps/plugin-fs"),- import("@tauri-apps/api/path"),- ]);- const root = await appDataDir();- const keyFile = await join(root, KEY_FILE);- const syncMeta = await join(root, "sync_meta");- if (await exists(keyFile)) await remove(keyFile);- if (await exists(syncMeta)) await remove(syncMeta, { recursive: true });-- for (const key of Object.keys(localStorage)) {- if (key.startsWith("ensu.chatKey")) localStorage.removeItem(key);- }- [- "user",- "srpAttributes",- "keyAttributes",- "originalKeyAttributes",- "isFirstLogin",- "ensu.chat.nativeMigration.v2",- ].forEach((key) => localStorage.removeItem(key));- await removeKV("token");- localStorage.setItem(MIGRATION_DONE, "1");-};diff --git a/web/apps/ensu/src/services/chat/keyMigration.ts b/web/apps/ensu/src/services/chat/keyMigration.tsnew file mode 100644index 0000000000..5fdd3d0e7e--- /dev/null+++ b/web/apps/ensu/src/services/chat/keyMigration.ts@@ -0,0 +1,107 @@+import { removeKV } from "ente-base/kv";+import {+ secureStorageDelete,+ secureStorageGet,+ secureStorageSet,+} from "../secure-storage";++const LOCAL_STORE = "ensu.chat.store.v1";+const MIGRATION_DONE = "ensu.chat.localMigration.v3";+const OLD_LOCAL_SECURE_KEY = "localChatKey";+const OLD_ATTACHMENT_SECURE_KEY = "legacyAttachmentKey.v2";+const KEY_FILE = "chat-keys.json";++const localGet = (key: string) => localStorage.getItem(key) ?? undefined;++const keyFilePath = async () => {+ const { appDataDir, join } = await import("@tauri-apps/api/path");+ return join(await appDataDir(), KEY_FILE);+};++const readKeyFile = async () => {+ const [{ exists, readFile }, path] = await Promise.all([+ import("@tauri-apps/plugin-fs"),+ keyFilePath(),+ ]);+ if (!(await exists(path))) return undefined;+ try {+ const value = JSON.parse(+ new TextDecoder().decode(await readFile(path)),+ ) as { localChatKey?: unknown };+ return typeof value.localChatKey === "string"+ ? value.localChatKey+ : undefined;+ } catch {+ return undefined;+ }+};++export const isLocalChatMigrationDone = () => localGet(MIGRATION_DONE) === "1";++export const promoteLocalChatKey = async (+ current: string | undefined,+ currentSecureKey: string,+ browserKey: string,+) => {+ if (isLocalChatMigrationDone()) return current;+ const [oldSecure, file] = await Promise.all([+ secureStorageGet(OLD_LOCAL_SECURE_KEY),+ readKeyFile(),+ ]);+ const key = current ?? localGet(browserKey) ?? oldSecure ?? file;+ if (key && key !== current) await secureStorageSet(currentSecureKey, key);+ return key;+};++export const hasRetiredLocalChatStore = () => !!localGet(LOCAL_STORE);++const retiredUserID = () => {+ try {+ const user = JSON.parse(localStorage.getItem("user") ?? "null") as {+ id?: unknown;+ } | null;+ return typeof user?.id === "number" ? user.id : undefined;+ } catch {+ return undefined;+ }+};++export const finalizeLocalChatMigration = async () => {+ const userID = retiredUserID();+ const { invoke } = await import("@tauri-apps/api/core");+ await invoke("chat_db_cleanup_v1");+ localStorage.removeItem(LOCAL_STORE);+ await Promise.all(+ [+ OLD_LOCAL_SECURE_KEY,+ OLD_ATTACHMENT_SECURE_KEY,+ "masterKey",+ "remoteChatKey",+ ...(userID+ ? [`remoteChatKey.${userID}`, `remoteChatKey.v2.${userID}`]+ : []),+ ].map(secureStorageDelete),+ );++ const [{ exists, remove }, { appDataDir, join }] = await Promise.all([+ import("@tauri-apps/plugin-fs"),+ import("@tauri-apps/api/path"),+ ]);+ const root = await appDataDir();+ const keyFile = await join(root, KEY_FILE);+ if (await exists(keyFile)) await remove(keyFile);++ for (const key of Object.keys(localStorage)) {+ if (key.startsWith("ensu.chatKey")) localStorage.removeItem(key);+ }+ [+ "user",+ "srpAttributes",+ "keyAttributes",+ "originalKeyAttributes",+ "isFirstLogin",+ "ensu.chat.nativeMigration.v2",+ ].forEach((key) => localStorage.removeItem(key));+ await removeKV("token");+ localStorage.setItem(MIGRATION_DONE, "1");+};diff --git a/web/apps/ensu/src/services/chat/migration.ts b/web/apps/ensu/src/services/chat/migration.tsnew file mode 100644index 0000000000..5812d254d9--- /dev/null+++ b/web/apps/ensu/src/services/chat/migration.ts@@ -0,0 +1,307 @@+import { base64ToBytes } from "@/services/base64";+import { isTauriRuntime } from "@/services/tauri-runtime";+import log from "ente-base/log";+import { deleteDB, openDB, type DBSchema } from "idb";+import { decryptAttachmentBytes } from "./attachments";+import {+ finalizeLocalChatMigration,+ isLocalChatMigrationDone,+} from "./keyMigration";+import {+ attachmentBytesExists,+ chatDb,+ decryptMessageTextStrict,+ decryptSessionTitleStrict,+ deserializeAttachmentsStrict,+ invokeChat,+ pruneOrphanedAttachmentBytes,+ readAttachmentBytes,+ writeAttachmentBytes,+ type StoredAttachment,+ type StoredMessage,+ type StoredSession,+} from "./store";++const LOCAL_STORAGE_STORE = "ensu.chat.store.v1";+const TOMBSTONE_MIGRATION = "ensu.chat.localMigration.v2";+const OLD_INDEXED_DB = "ensu.chat.db";++type OldSession = StoredSession & {+ deletedAt?: number | null;+ isDeleted?: boolean;+};+type OldMessage = Omit<StoredMessage, "attachments"> & {+ attachments?: (StoredAttachment & { uploadedAt?: number | null })[];+ deletedAt?: number | null;+ isDeleted?: boolean;+};+type AttachmentBytes = { id: string; data: Uint8Array<ArrayBuffer> };+type BrowserStore = {+ sessions: OldSession[];+ messages: OldMessage[];+ attachmentBytes: AttachmentBytes[];+};++interface OldIndexedDb extends DBSchema {+ sessions: { key: string; value: OldSession };+ messages: { key: string; value: OldMessage };+ attachmentBytes: { key: string; value: AttachmentBytes };+}++let _initPromise: Promise<void> | undefined;++const liveStore = (+ sessions: OldSession[],+ messages: OldMessage[],+ attachmentBytes: AttachmentBytes[],+): BrowserStore => {+ const liveSessions = sessions.filter(+ ({ deletedAt, isDeleted }) => !deletedAt && !isDeleted,+ );+ const sessionIDs = new Set(+ liveSessions.map(({ sessionUuid }) => sessionUuid),+ );+ return {+ sessions: liveSessions,+ messages: messages.filter(+ ({ sessionUuid, deletedAt, isDeleted }) =>+ !deletedAt && !isDeleted && sessionIDs.has(sessionUuid),+ ),+ attachmentBytes,+ };+};++const localStorageStore = (): BrowserStore => {+ const json = localStorage.getItem(LOCAL_STORAGE_STORE);+ if (!json) return { sessions: [], messages: [], attachmentBytes: [] };+ const parsed = JSON.parse(json) as Partial<{+ sessions: OldSession[];+ messages: OldMessage[];+ attachmentBytes: { id: string; data: string }[];+ }>;+ return liveStore(+ parsed.sessions ?? [],+ parsed.messages ?? [],+ (parsed.attachmentBytes ?? []).map(({ id, data }) => ({+ id,+ data: base64ToBytes(data),+ })),+ );+};++const hasLocalStorageStore = () => !!localStorage.getItem(LOCAL_STORAGE_STORE);++const writeBrowserStore = async (source: BrowserStore) => {+ const db = await chatDb();+ const tx = db.transaction(+ ["sessions", "messages", "attachmentBytes"],+ "readwrite",+ );+ await Promise.all([+ ...source.sessions.map((session) =>+ tx.objectStore("sessions").put(session),+ ),+ ...source.messages.map((message) =>+ tx.objectStore("messages").put(message),+ ),+ ...source.attachmentBytes.map((attachment) =>+ tx.objectStore("attachmentBytes").put(attachment),+ ),+ tx.done,+ ]);+};++const removeCurrentBrowserTombstones = async () => {+ if (localStorage.getItem(TOMBSTONE_MIGRATION) === "1") return;+ const db = await chatDb();+ const [sessions, messages] = await Promise.all([+ db.getAll("sessions") as Promise<OldSession[]>,+ db.getAll("messages") as Promise<OldMessage[]>,+ ]);+ const deletedSessions = new Set(+ sessions+ .filter(({ deletedAt, isDeleted }) => deletedAt || isDeleted)+ .map(({ sessionUuid }) => sessionUuid),+ );+ const deletedMessages = messages.filter(+ ({ sessionUuid, deletedAt, isDeleted }) =>+ deletedAt || isDeleted || deletedSessions.has(sessionUuid),+ );+ const tx = db.transaction(["sessions", "messages"], "readwrite");+ await Promise.all([+ ...deletedSessions+ .values()+ .map((id) => tx.objectStore("sessions").delete(id)),+ ...deletedMessages.map(({ messageUuid }) =>+ tx.objectStore("messages").delete(messageUuid),+ ),+ tx.done,+ ]);+ localStorage.setItem(TOMBSTONE_MIGRATION, "1");+};++const hasIndexedDb = async (name: string) => {+ return (await indexedDB.databases()).some(+ (database) => database.name === name,+ );+};++const readOldIndexedDb = async () => {+ if (!(await hasIndexedDb(OLD_INDEXED_DB))) return undefined;+ const source = await openDB<OldIndexedDb>(OLD_INDEXED_DB);+ try {+ return liveStore(+ await source.getAll("sessions"),+ await source.getAll("messages"),+ await source.getAll("attachmentBytes"),+ );+ } finally {+ source.close();+ }+};++const hasChatData = ({ sessions, messages }: BrowserStore) =>+ sessions.length > 0 || messages.length > 0;++const cleanupOldBrowserStores = () => {+ try {+ localStorage.removeItem(LOCAL_STORAGE_STORE);+ } catch (error) {+ log.warn("Failed to remove the old local chat store", error);+ }+ void deleteDB(OLD_INDEXED_DB, {+ blocked: () => log.warn("Waiting for the old chat DB to close"),+ }).catch((error: unknown) =>+ log.warn("Failed to remove the old chat DB", error),+ );+};++const importOldBrowserStores = async () => {+ const current = await chatDb();+ const [sessions, messages] = await Promise.all([+ current.getAll("sessions"),+ current.getAll("messages"),+ ]);+ if (sessions.length || messages.length) {+ cleanupOldBrowserStores();+ return;+ }++ const indexedDbStore = await readOldIndexedDb();+ const source =+ indexedDbStore && hasChatData(indexedDbStore)+ ? indexedDbStore+ : hasLocalStorageStore()+ ? localStorageStore()+ : undefined;+ if (source && hasChatData(source)) {+ await writeBrowserStore(source);+ }+ cleanupOldBrowserStores();+};++const importLocalStorageToNative = async (chatKey: string) => {+ const source = localStorageStore();+ for (const session of source.sessions.sort(+ (left, right) => left.createdAt - right.createdAt,+ )) {+ await invokeChat("chat_db_upsert_session", {+ keyB64: chatKey,+ input: {+ sessionUuid: session.sessionUuid,+ title: await decryptSessionTitleStrict(session, chatKey),+ createdAt: session.createdAt,+ updatedAt: session.updatedAt,+ },+ });+ }+ for (const message of source.messages.sort(+ (left, right) => left.createdAt - right.createdAt,+ )) {+ const attachments = await deserializeAttachmentsStrict(+ message.attachments,+ chatKey,+ );+ await invokeChat("chat_db_insert_message_with_uuid", {+ keyB64: chatKey,+ input: {+ messageUuid: message.messageUuid,+ sessionUuid: message.sessionUuid,+ parentMessageUuid: message.parentMessageUuid ?? null,+ sender: message.sender,+ text: await decryptMessageTextStrict(message, chatKey),+ createdAt: message.createdAt,+ attachments: attachments.map(({ id, kind, name, size }) => ({+ id,+ kind,+ name,+ size,+ })),+ },+ });+ }+ for (const { id, data } of source.attachmentBytes) {+ await writeAttachmentBytes(id, data);+ }+};++const verifyNativeAttachments = async (chatKey: string) => {+ const sessions = await invokeChat<{ sessionUuid: string }[]>(+ "chat_db_list_sessions",+ { keyB64: chatKey },+ );+ const seen = new Set<string>();+ for (const { sessionUuid } of sessions) {+ const messages = await invokeChat<{ attachments?: { id: string }[] }[]>(+ "chat_db_get_messages",+ { keyB64: chatKey, sessionUuid },+ );+ for (const { id } of messages.flatMap(+ ({ attachments }) => attachments ?? [],+ )) {+ if (seen.has(id) || !(await attachmentBytesExists(id))) continue;+ seen.add(id);+ await decryptAttachmentBytes(+ await readAttachmentBytes(id),+ chatKey,+ sessionUuid,+ );+ }+ }+};++const migrate = async (chatKey: string) => {+ if (isTauriRuntime()) {+ if (!isLocalChatMigrationDone()) {+ await invokeChat("chat_db_import_v1", {+ input: { keyB64: chatKey },+ });+ if (hasLocalStorageStore()) {+ await importLocalStorageToNative(chatKey);+ }+ await verifyNativeAttachments(chatKey);+ await finalizeLocalChatMigration();+ }+ } else {+ await removeCurrentBrowserTombstones();+ await importOldBrowserStores();+ }+ try {+ await pruneOrphanedAttachmentBytes(chatKey);+ } catch (error) {+ log.warn("Failed to prune orphaned attachment payloads", error);+ }+};++export const initializeChatStorePersistence = async (chatKey: string) => {+ if (_initPromise) return _initPromise;+ const promise = migrate(chatKey).catch((error: unknown) => {+ if (_initPromise === promise) {+ _initPromise = undefined;+ }+ log.error("Failed to initialize chat persistence", error);+ throw error;+ });+ _initPromise = promise;+ return promise;+};diff --git a/web/apps/ensu/src/services/chat/store.ts b/web/apps/ensu/src/services/chat/store.tsindex 9ab197233b..788933017e 100644--- a/web/apps/ensu/src/services/chat/store.ts+++ b/web/apps/ensu/src/services/chat/store.ts@@ -1,13 +1,8 @@-import { base64ToBytes } from "@/services/base64";import { isTauriRuntime } from "@/services/tauri-runtime";import { getKV, removeKV, setKV } from "ente-base/kv";import log from "ente-base/log";-import { deleteDB, openDB, type DBSchema, type IDBPDatabase } from "idb";+import { openDB, type DBSchema, type IDBPDatabase } from "idb";import { decryptAttachmentBytes, encryptAttachmentBytes } from "./attachments";-import {- finalizeLocalChatMigration,- isLocalChatMigrationDone,-} from "./chatKey";import {decryptChatField,decryptChatPayload,@@ -15,10 +10,7 @@ import {encryptChatPayload,} from "./crypto";-const STORAGE_KEY = "ensu.chat.store.v1";-const LOCAL_SCHEMA_MIGRATION_KEY = "ensu.chat.localMigration.v2";const CHAT_DB_NAME = "ensu-chat";-const V1_WEB_CHAT_DB_NAME = "ensu.chat.db";export type AttachmentKind = "image" | "document";@@ -30,14 +22,14 @@ export interface ChatAttachment {encryptedName?: string;}-interface StoredAttachment {+export interface StoredAttachment {id: string;kind: AttachmentKind;size: number;encryptedName: string;}-interface StoredSession {+export interface StoredSession {sessionUuid: string;createdAt: number;updatedAt: number;@@ -45,7 +37,7 @@ interface StoredSession {header: string;}-interface StoredMessage {+export interface StoredMessage {messageUuid: string;sessionUuid: string;parentMessageUuid?: string;@@ -56,19 +48,6 @@ interface StoredMessage {attachments?: StoredAttachment[];}-type OldStoredAttachment = StoredAttachment & { uploadedAt?: number | null };--type OldStoredSession = StoredSession & {- deletedAt?: number | null;- isDeleted?: boolean;-};--type OldStoredMessage = Omit<StoredMessage, "attachments"> & {- attachments?: OldStoredAttachment[];- deletedAt?: number | null;- isDeleted?: boolean;-};-interface StoredAttachmentBytes {id: string;data: Uint8Array<ArrayBuffer>;@@ -82,20 +61,6 @@ interface ChatDbSchema {type ChatStoreName = keyof ChatDbSchema;-type PersistedAttachmentBytes = { id: string; data: string };--type PersistedChatStore = {- sessions: OldStoredSession[];- messages: OldStoredMessage[];- attachmentBytes: PersistedAttachmentBytes[];-};--type ChatStoreState = {- sessions: StoredSession[];- messages: StoredMessage[];- attachmentBytes: StoredAttachmentBytes[];-};-interface IndexedChatDBSchema extends DBSchema {sessions: { key: string; value: StoredSession };messages: { key: string; value: StoredMessage };@@ -189,45 +154,6 @@ const formatLogError = (error: unknown) => {}};-const loadChatStoreState = (): ChatStoreState => {- if (typeof localStorage === "undefined") {- return { sessions: [], messages: [], attachmentBytes: [] };- }-- const json = localStorage.getItem(STORAGE_KEY);- if (!json) {- return { sessions: [], messages: [], attachmentBytes: [] };- }-- try {- const parsed = JSON.parse(json) as Partial<PersistedChatStore>;- const sessions = (parsed.sessions ?? [])- .map(normalizeOldSession)- .filter((session): session is StoredSession => !!session);- const sessionIDs = new Set(- sessions.map((session) => session.sessionUuid),- );- return {- sessions,- messages: (parsed.messages ?? [])- .map(normalizeOldMessage)- .filter(- (message): message is StoredMessage =>- !!message && sessionIDs.has(message.sessionUuid),- ),- attachmentBytes: (parsed.attachmentBytes ?? []).map(- (attachment) => ({- id: attachment.id,- data: base64ToBytes(attachment.data),- }),- ),- };- } catch (error) {- log.error("Failed to parse chat store", error);- throw error;- }-};-const cloneStoreEntry = <K extends ChatStoreName>(name: K,value: ChatDbSchema[K],@@ -251,42 +177,6 @@ const cloneStoreEntry = <K extends ChatStoreName>(};let _chatDb: Promise<ChatDbLike> | undefined;-let _chatPersistenceInitPromise: Promise<void> | undefined;-let _chatPersistenceInitKey: string | undefined;--const normalizeOldSession = (- session: OldStoredSession,-): StoredSession | undefined => {- if (session.deletedAt || session.isDeleted) return undefined;- return {- sessionUuid: session.sessionUuid,- createdAt: session.createdAt,- updatedAt: session.updatedAt,- encryptedData: session.encryptedData,- header: session.header,- };-};--const normalizeOldMessage = (- message: OldStoredMessage,-): StoredMessage | undefined => {- if (message.deletedAt || message.isDeleted) return undefined;- return {- messageUuid: message.messageUuid,- sessionUuid: message.sessionUuid,- parentMessageUuid: message.parentMessageUuid,- sender: message.sender,- createdAt: message.createdAt,- encryptedData: message.encryptedData,- header: message.header,- attachments: message.attachments?.map((attachment) => ({- id: attachment.id,- kind: attachment.kind,- size: attachment.size,- encryptedName: attachment.encryptedName,- })),- };-};const createIndexedDbChatDb = (db: IDBPDatabase<IndexedChatDBSchema>,@@ -339,46 +229,6 @@ const createIndexedDbChatDb = (close: () => db.close(),});-const migrateIndexedDbToLocalOnly = async (- db: IDBPDatabase<IndexedChatDBSchema>,-) => {- if (localStorage.getItem(LOCAL_SCHEMA_MIGRATION_KEY) === "1") return;-- const [oldSessions, oldMessages] = await Promise.all([- db.getAll("sessions") as Promise<OldStoredSession[]>,- db.getAll("messages") as Promise<OldStoredMessage[]>,- ]);- const removedSessionIDs = new Set(- oldSessions- .filter((session) => !normalizeOldSession(session))- .map((session) => session.sessionUuid),- );- const tx = db.transaction(["sessions", "messages"], "readwrite");- const sessionStore = tx.objectStore("sessions");- const messageStore = tx.objectStore("messages");- const operations: Promise<unknown>[] = [];-- for (const oldSession of oldSessions) {- const session = normalizeOldSession(oldSession);- operations.push(- session- ? sessionStore.put(session)- : sessionStore.delete(oldSession.sessionUuid),- );- }- for (const oldMessage of oldMessages) {- const message = normalizeOldMessage(oldMessage);- operations.push(- message && !removedSessionIDs.has(message.sessionUuid)- ? messageStore.put(message)- : messageStore.delete(oldMessage.messageUuid),- );- }-- await Promise.all([...operations, tx.done]);- localStorage.setItem(LOCAL_SCHEMA_MIGRATION_KEY, "1");-};-const openChatDb = async () => {const db = await openDB<IndexedChatDBSchema>(CHAT_DB_NAME, 1, {upgrade(db) {@@ -394,11 +244,10 @@ const openChatDb = async () => {},});- await migrateIndexedDbToLocalOnly(db);return createIndexedDbChatDb(db);};-const chatDb = () => (_chatDb ??= openChatDb());+export const chatDb = () => (_chatDb ??= openChatDb());const normalizeTitleText = (value: string) => value.replace(/\s+/g, " ").trim();@@ -414,7 +263,7 @@ const safeTitle = (value: unknown) =>? sessionTitleFromText(value, "New chat"): "New chat";-const decryptSessionTitleStrict = async (+export const decryptSessionTitleStrict = async (session: StoredSession,chatKey: string,) => {@@ -431,7 +280,7 @@ const decryptSessionTitle = (session: StoredSession, chatKey: string) =>return "New chat";});-const decryptMessageTextStrict = async (+export const decryptMessageTextStrict = async (message: StoredMessage,chatKey: string,) => {@@ -505,7 +354,7 @@ const deserializeAttachments = async ();};-const deserializeAttachmentsStrict = async (+export const deserializeAttachmentsStrict = async (attachments: StoredAttachment[] | undefined,chatKey: string,): Promise<ChatAttachment[]> =>@@ -518,293 +367,56 @@ const deserializeAttachmentsStrict = async (})),);-const hasLocalStorageChatStore = () =>- typeof localStorage !== "undefined" && !!localStorage.getItem(STORAGE_KEY);--const hasIndexedDbDatabase = async (name: string) => {- if (typeof indexedDB === "undefined") return false;-- if ("databases" in indexedDB && typeof indexedDB.databases === "function") {- const databases = await indexedDB.databases();- return databases.some((database) => database.name === name);- }-- return new Promise<boolean>((resolve, reject) => {- let created = false;- const request = indexedDB.open(name);-- request.onupgradeneeded = () => {- created = true;- };-- request.onsuccess = () => {- const db = request.result;- db.close();-- if (!created) {- resolve(true);- return;- }-- const deleteRequest = indexedDB.deleteDatabase(name);- deleteRequest.onsuccess = () => resolve(false);- deleteRequest.onerror = () => reject(deleteRequest.error);- deleteRequest.onblocked = () => resolve(false);- };-- request.onerror = () => reject(request.error);- });-};--const importLocalStorageChatStoreToIndexedDb = async () => {- if (typeof localStorage === "undefined") return;-- const localStorageStore = loadChatStoreState();- if (- !localStorageStore.sessions.length &&- !localStorageStore.messages.length &&- !localStorageStore.attachmentBytes.length- ) {- localStorage.removeItem(STORAGE_KEY);- return;- }-- log.info("Migrating localStorage chat store to IndexedDB", {- sessions: localStorageStore.sessions.length,- messages: localStorageStore.messages.length,- attachmentBytes: localStorageStore.attachmentBytes.length,- });-- const db = await chatDb();- const tx = db.transaction(- ["sessions", "messages", "attachmentBytes"],- "readwrite",- );-- for (const session of localStorageStore.sessions) {- await tx.objectStore("sessions").put(session);- }-- for (const message of localStorageStore.messages) {- await tx.objectStore("messages").put(message);- }-- for (const attachment of localStorageStore.attachmentBytes) {- await tx- .objectStore("attachmentBytes")- .put({ id: attachment.id, data: new Uint8Array(attachment.data) });- }-- await tx.done;- localStorage.removeItem(STORAGE_KEY);- log.info("Finished migrating localStorage chat store to IndexedDB");-};--const importV1IndexedDbChatStore = async () => {- if (typeof indexedDB === "undefined") return;- if (!(await hasIndexedDbDatabase(V1_WEB_CHAT_DB_NAME))) return;-- log.info("Migrating v1 IndexedDB chat store", {- from: V1_WEB_CHAT_DB_NAME,- to: CHAT_DB_NAME,- });-- const [v1Db, db] = await Promise.all([- openDB<IndexedChatDBSchema>(V1_WEB_CHAT_DB_NAME),- chatDb(),- ]);-- let migratedAnyEntries: boolean;- try {- const [oldSessions, oldMessages, attachmentBytes] = await Promise.all([- v1Db.getAll("sessions") as Promise<OldStoredSession[]>,- v1Db.getAll("messages") as Promise<OldStoredMessage[]>,- v1Db.getAll("attachmentBytes"),- ]);- const sessions = oldSessions- .map(normalizeOldSession)- .filter((session): session is StoredSession => !!session);- const sessionIDs = new Set(- sessions.map((session) => session.sessionUuid),- );- const messages = oldMessages- .map(normalizeOldMessage)- .filter(- (message): message is StoredMessage =>- !!message && sessionIDs.has(message.sessionUuid),- );- migratedAnyEntries =- sessions.length > 0 ||- messages.length > 0 ||- attachmentBytes.length > 0;-- const tx = db.transaction(- ["sessions", "messages", "attachmentBytes"],- "readwrite",+export const pruneOrphanedAttachmentBytes = async (chatKey: string) => {+ if (isTauriRuntime()) {+ const sessions = await invokeChat<NativeSession[]>(+ "chat_db_list_sessions",+ { keyB64: chatKey },);-+ const referenced = new Set<string>();for (const session of sessions) {- await tx.objectStore("sessions").put(session);- }-- for (const message of messages) {- await tx.objectStore("messages").put(message);+ const messages = await invokeChat<NativeMessage[]>(+ "chat_db_get_messages",+ { keyB64: chatKey, sessionUuid: session.sessionUuid },+ );+ for (const attachment of messages.flatMap(+ ({ attachments }) => attachments ?? [],+ )) {+ referenced.add(attachment.id);+ }}- for (const attachment of attachmentBytes) {- await tx- .objectStore("attachmentBytes")- .put({- id: attachment.id,- data: new Uint8Array(attachment.data),- });+ const { readDir } = await import("@tauri-apps/plugin-fs");+ for (const entry of await readDir(await attachmentDir())) {+ if (entry.isFile && !referenced.has(entry.name)) {+ await deleteAttachmentBytes(entry.name);+ }}-- await tx.done;- } finally {- v1Db.close();- }-- await deleteDB(V1_WEB_CHAT_DB_NAME, {- blocked() {- log.warn("Waiting for an existing client to close the v1 chat DB");- },- });-- log.info(- migratedAnyEntries- ? "Finished migrating v1 IndexedDB chat store"- : "Removed empty v1 IndexedDB chat store",- );-};--const importLocalStorageChatStoreToNative = async (chatKey: string) => {- if (!isTauriRuntime() || typeof localStorage === "undefined") return;-- const localStorageStore = loadChatStoreState();- if (- !localStorageStore.sessions.length &&- !localStorageStore.messages.length &&- !localStorageStore.attachmentBytes.length- ) {return;}- log.info("Migrating localStorage chat store to native DB", {- sessions: localStorageStore.sessions.length,- messages: localStorageStore.messages.length,- attachmentBytes: localStorageStore.attachmentBytes.length,- });-- const sessions = [...localStorageStore.sessions].sort(- (left, right) => left.createdAt - right.createdAt,+ const db = await chatDb();+ const [messages, attachments] = await Promise.all([+ db.getAll("messages"),+ db.getAll("attachmentBytes"),+ ]);+ const referenced = new Set(+ messages.flatMap((message) =>+ (message.attachments ?? []).map((attachment) => attachment.id),+ ),);- for (const session of sessions) {- await invokeChat("chat_db_upsert_session", {- keyB64: chatKey,- input: {- sessionUuid: session.sessionUuid,- title: await decryptSessionTitleStrict(session, chatKey),- createdAt: session.createdAt,- updatedAt: session.updatedAt,- },- });- }-- const messages = [...localStorageStore.messages].sort(- (left, right) => left.createdAt - right.createdAt,+ const orphaned = attachments.filter(+ (attachment) => !referenced.has(attachment.id),);- for (const message of messages) {- const attachments = await deserializeAttachmentsStrict(- message.attachments,- chatKey,- );- await invokeChat("chat_db_insert_message_with_uuid", {- keyB64: chatKey,- input: {- messageUuid: message.messageUuid,- sessionUuid: message.sessionUuid,- parentMessageUuid: message.parentMessageUuid ?? null,- sender: message.sender,- text: await decryptMessageTextStrict(message, chatKey),- createdAt: message.createdAt,- attachments: attachments.map((attachment) => ({- id: attachment.id,- kind: attachment.kind,- name: attachment.name,- size: attachment.size,- })),- },- });- }-- for (const attachment of localStorageStore.attachmentBytes) {- await writeAttachmentBytes(attachment.id, attachment.data);- }-- log.info("Finished migrating localStorage chat store to native DB");-};+ if (!orphaned.length) return;-const verifyNativeAttachments = async (chatKey: string) => {- const sessions = await invokeChat<NativeSession[]>(- "chat_db_list_sessions",- { keyB64: chatKey },+ const tx = db.transaction(["attachmentBytes"], "readwrite");+ await Promise.all(+ orphaned.map((attachment) =>+ tx.objectStore("attachmentBytes").delete(attachment.id),+ ),);- const seen = new Set<string>();- for (const session of sessions) {- const messages = await invokeChat<NativeMessage[]>(- "chat_db_get_messages",- { keyB64: chatKey, sessionUuid: session.sessionUuid },- );- for (const attachment of messages.flatMap(- ({ attachments }) => attachments ?? [],- )) {- if (seen.has(attachment.id)) continue;- seen.add(attachment.id);- if (!(await attachmentBytesExists(attachment.id))) continue;- await decryptAttachmentBytes(- await readAttachmentBytes(attachment.id),- chatKey,- session.sessionUuid,- );- }- }-};--export const initializeChatStorePersistence = async (chatKey: string) => {- if (_chatPersistenceInitKey === chatKey && _chatPersistenceInitPromise) {- return _chatPersistenceInitPromise;- }-- _chatPersistenceInitKey = chatKey;- const initPromise = (async () => {- if (isTauriRuntime()) {- if (!isLocalChatMigrationDone()) {- await invokeChat("chat_db_import_v1", {- input: { keyB64: chatKey },- });- if (hasLocalStorageChatStore()) {- await importLocalStorageChatStoreToNative(chatKey);- }- await verifyNativeAttachments(chatKey);- await finalizeLocalChatMigration();- }- } else if (hasLocalStorageChatStore()) {- await importLocalStorageChatStoreToIndexedDb();- } else {- await importV1IndexedDbChatStore();- }- })().catch((error: unknown) => {- if (_chatPersistenceInitPromise === initPromise) {- _chatPersistenceInitPromise = undefined;- _chatPersistenceInitKey = undefined;- }- log.error("Failed to initialize chat persistence", error);- throw error;- });-- _chatPersistenceInitPromise = initPromise;- return initPromise;+ await tx.done;};const fetchStore = async () => {@@ -816,7 +428,7 @@ const fetchStore = async () => {return { sessions, messages };};-const invokeChat = async <T>(+export const invokeChat = async <T>(command: string,args?: Record<string, unknown>,) => {@@ -957,10 +569,17 @@ const updateMessageNative = async (};const deleteSessionNative = async (sessionUuid: string, chatKey: string) => {- await invokeChat("chat_db_delete_session", {+ const attachmentIds = await invokeChat<string[]>("chat_db_delete_session", {keyB64: chatKey,sessionUuid,});+ for (const id of attachmentIds) {+ try {+ await deleteAttachmentBytes(id);+ } catch (error) {+ log.warn(`Failed to delete attachment payload ${id}`, error);+ }+ }};export const listSessions = async (chatKey: string): Promise<ChatSession[]> => {@@ -1243,14 +862,27 @@ export const deleteSession = async (sessionUuid: string, chatKey: string) => {const db = await chatDb();const messages = await db.getAll("messages");- const tx = db.transaction(["sessions", "messages"], "readwrite");+ const sessionMessages = messages.filter(+ (message) => message.sessionUuid === sessionUuid,+ );+ const attachmentIds = new Set(+ sessionMessages.flatMap((message) =>+ (message.attachments ?? []).map((attachment) => attachment.id),+ ),+ );+ const tx = db.transaction(+ ["sessions", "messages", "attachmentBytes"],+ "readwrite",+ );const sessionStore = tx.objectStore("sessions");const messageStore = tx.objectStore("messages");+ const attachmentStore = tx.objectStore("attachmentBytes");await Promise.all([sessionStore.delete(sessionUuid),- ...messages- .filter((message) => message.sessionUuid === sessionUuid)- .map((message) => messageStore.delete(message.messageUuid)),+ ...sessionMessages.map((message) =>+ messageStore.delete(message.messageUuid),+ ),+ ...[...attachmentIds].map((id) => attachmentStore.delete(id)),]);await tx.done;@@ -1297,6 +929,20 @@ export const writeAttachmentBytes = async (await db.put("attachmentBytes", { id, data });};+export const deleteAttachmentBytes = async (id: string) => {+ if (isTauriRuntime()) {+ const { exists, remove } = await import("@tauri-apps/plugin-fs");+ const path = await attachmentPath(id);+ if (await exists(path)) await remove(path);+ return;+ }++ const db = await chatDb();+ const tx = db.transaction(["attachmentBytes"], "readwrite");+ await tx.objectStore("attachmentBytes").delete(id);+ await tx.done;+};+export const storeEncryptedAttachmentBytes = async (id: string,data: Uint8Array,