π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
fix(ensu): harden v0.1.12 storage migration
Prateek Sunal4ca30467468f
diff --git a/mobile/native/android/apps/ensu/app-ui/build.gradle.kts b/mobile/native/android/apps/ensu/app-ui/build.gradle.ktsindex 9a17ed1523..3e8d8786bb 100644--- a/mobile/native/android/apps/ensu/app-ui/build.gradle.kts+++ b/mobile/native/android/apps/ensu/app-ui/build.gradle.kts@@ -51,8 +51,8 @@ android {applicationId = "io.ente.ensu"minSdk = 24targetSdk = 35- versionCode = 29- versionName = "0.1.11"+ versionCode = 30+ versionName = "0.1.12"buildConfigField("String", "API_ENDPOINT", "\"$apiEndpointOverride\"")}diff --git a/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxproj b/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxprojindex b94c776d20..52b645fa3c 100644--- a/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxproj+++ b/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxproj@@ -534,7 +534,7 @@ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;CODE_SIGN_IDENTITY = "Apple Development";CODE_SIGN_STYLE = Automatic;- CURRENT_PROJECT_VERSION = 27;+ CURRENT_PROJECT_VERSION = 28;DEVELOPMENT_TEAM = 6Z68YJY9Q2;ENABLE_PREVIEWS = YES;ENABLE_USER_SCRIPT_SANDBOXING = NO;@@ -550,7 +550,7 @@"$(inherited)","@executable_path/Frameworks",);- MARKETING_VERSION = 0.1.11;+ MARKETING_VERSION = 0.1.12;PRODUCT_BUNDLE_IDENTIFIER = io.ente.ensu;PRODUCT_NAME = "$(TARGET_NAME)";PROVISIONING_PROFILE_SPECIFIER = "";@@ -595,7 +595,7 @@ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;CODE_SIGN_IDENTITY = "Apple Development";CODE_SIGN_STYLE = Automatic;- CURRENT_PROJECT_VERSION = 27;+ CURRENT_PROJECT_VERSION = 28;DEVELOPMENT_TEAM = 6Z68YJY9Q2;ENABLE_PREVIEWS = YES;ENABLE_USER_SCRIPT_SANDBOXING = NO;@@ -611,7 +611,7 @@"$(inherited)","@executable_path/Frameworks",);- MARKETING_VERSION = 0.1.11;+ MARKETING_VERSION = 0.1.12;PRODUCT_BUNDLE_IDENTIFIER = io.ente.ensu;PRODUCT_NAME = "$(TARGET_NAME)";PROVISIONING_PROFILE_SPECIFIER = "";@@ -656,7 +656,7 @@ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;CODE_SIGN_IDENTITY = "Apple Development";CODE_SIGN_STYLE = Automatic;- CURRENT_PROJECT_VERSION = 11;+ CURRENT_PROJECT_VERSION = 12;DEVELOPMENT_TEAM = 6Z68YJY9Q2;ENABLE_PREVIEWS = YES;ENABLE_USER_SCRIPT_SANDBOXING = NO;@@ -669,7 +669,7 @@"@executable_path/../Frameworks",);MACOSX_DEPLOYMENT_TARGET = 13.0;- MARKETING_VERSION = 0.1.11;+ MARKETING_VERSION = 0.1.12;PRODUCT_BUNDLE_IDENTIFIER = io.ente.ensu;PRODUCT_NAME = Ensu;HEADER_SEARCH_PATHS = (@@ -716,7 +716,7 @@ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;CODE_SIGN_IDENTITY = "Apple Development";CODE_SIGN_STYLE = Automatic;- CURRENT_PROJECT_VERSION = 11;+ CURRENT_PROJECT_VERSION = 12;DEVELOPMENT_TEAM = 6Z68YJY9Q2;ENABLE_PREVIEWS = YES;ENABLE_USER_SCRIPT_SANDBOXING = NO;@@ -729,7 +729,7 @@"@executable_path/../Frameworks",);MACOSX_DEPLOYMENT_TARGET = 13.0;- MARKETING_VERSION = 0.1.11;+ MARKETING_VERSION = 0.1.12;PRODUCT_BUNDLE_IDENTIFIER = io.ente.ensu;PRODUCT_NAME = Ensu;HEADER_SEARCH_PATHS = (diff --git a/mobile/native/darwin/Apps/ensu/ensu/Info-macOS.plist b/mobile/native/darwin/Apps/ensu/ensu/Info-macOS.plistindex 858b32bf5c..44625bd4fb 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Info-macOS.plist+++ b/mobile/native/darwin/Apps/ensu/ensu/Info-macOS.plist@@ -21,10 +21,10 @@<string>APPL</string><key>CFBundleShortVersionString</key>- <string>0.1.11</string>+ <string>0.1.12</string><key>CFBundleVersion</key>- <string>11</string>+ <string>12</string><key>LSApplicationCategoryType</key><string>public.app-category.photography</string>diff --git a/mobile/native/darwin/Apps/ensu/ensu/Info.plist b/mobile/native/darwin/Apps/ensu/ensu/Info.plistindex d3b7d89f32..f983893185 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Info.plist+++ b/mobile/native/darwin/Apps/ensu/ensu/Info.plist@@ -21,10 +21,10 @@<string>APPL</string><key>CFBundleShortVersionString</key>- <string>0.1.11</string>+ <string>0.1.12</string><key>CFBundleVersion</key>- <string>27</string>+ <string>28</string><key>UILaunchStoryboardName</key><string>LaunchScreen</string>diff --git a/rust/apps/ensu/package.json b/rust/apps/ensu/package.jsonindex 74cd3ea874..8631b872fc 100644--- a/rust/apps/ensu/package.json+++ b/rust/apps/ensu/package.json@@ -1,6 +1,6 @@{"name": "ensu-tauri",- "version": "0.1.11",+ "version": "0.1.12","private": true,"scripts": {"dev": "node scripts/tauri-dev.mjs",diff --git a/rust/apps/ensu/src-tauri/Cargo.lock b/rust/apps/ensu/src-tauri/Cargo.lockindex fd18eaa7dc..54bc11f15f 100644--- a/rust/apps/ensu/src-tauri/Cargo.lock+++ b/rust/apps/ensu/src-tauri/Cargo.lock@@ -1090,7 +1090,7 @@ dependencies = [[[package]]name = "ensu-tauri"-version = "0.1.11"+version = "0.1.12"dependencies = ["ensu-db","ensu-sync",diff --git a/rust/apps/ensu/src-tauri/Cargo.toml b/rust/apps/ensu/src-tauri/Cargo.tomlindex ef48497fff..1cdae5dbda 100644--- a/rust/apps/ensu/src-tauri/Cargo.toml+++ b/rust/apps/ensu/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "ensu-tauri"-version = "0.1.11"+version = "0.1.12"description = "Ensu Desktop (Tauri)"edition = "2021"diff --git a/rust/apps/ensu/src-tauri/src/commands.rs b/rust/apps/ensu/src-tauri/src/commands.rsindex 7dce446659..fabad2f59e 100644--- a/rust/apps/ensu/src-tauri/src/commands.rs+++ b/rust/apps/ensu/src-tauri/src/commands.rs@@ -8,7 +8,7 @@ use std::sync::{Arc, Mutex};use std::time::{Duration, Instant};use ensu_db::backend::sqlite::SqliteBackend;-use ensu_db::{EnsuDb, Error as DbError};+use ensu_db::{EnsuDb, Error as DbError, SyncStateDb};use ensu_sync as chat_sync;use ente_core::{auth as core_auth, crypto as core_crypto};use inference_rs as llm;@@ -39,6 +39,15 @@ struct ChatDbHolder {}const SECURE_STORAGE_SERVICE: &str = "io.ente.ensu";+const CHAT_DB_FILE_NAME_V2: &str = "ensu_llmchat_v2.db";+const LEGACY_CHAT_DB_FILE_NAME: &str = "ensu_llmchat.db";+const SYNC_DB_FILE_NAME_V2: &str = "llmchat_sync_v2.db";+const LEGACY_SYNC_DB_FILE_NAME: &str = "llmchat_sync.db";+const ATTACHMENTS_DIR_NAME_V2: &str = "ensu_llmchat_attachments_v2";+const LEGACY_ATTACHMENTS_DIR_NAME: &str = "ensu_llmchat_attachments";+const SYNC_CURSOR_META_KEY: &str = "llmchat.sync.cursor";+const SYNC_CHAT_KEY_META_KEY: &str = "llmchat.chat.key";+const SYNC_OFFLINE_SEED_META_KEY: &str = "llmchat.offline.seeded.v1";#[derive(Debug, Serialize)]pub struct ApiError {@@ -646,6 +655,13 @@ pub struct ChatSyncInput {client_version: Option<String>,}+#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ChatDbMigrateLegacyInput {+ key_b64: String,+ legacy_key_b64: String,+}+#[derive(Serialize)]#[serde(rename_all = "camelCase")]pub struct ChatSyncStatsDto {@@ -682,6 +698,15 @@ impl From<chat_sync::SyncResult> for ChatSyncResultDto {}}+#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ChatDbMigrateLegacyResult {+ did_migrate: bool,+ migrated_sessions: i64,+ migrated_messages: i64,+ migrated_attachments: i64,+}+impl TryFrom<ChatAttachmentInput> for ensu_db::Attachment {type Error = ApiError;@@ -1266,6 +1291,16 @@ pub async fn chat_db_reset(state: State<'_, ChatDbState>, app: AppHandle) -> Res.map_err(|_| chat_db_thread_error())?}+#[tauri::command]+pub async fn chat_db_migrate_legacy(+ app: AppHandle,+ input: ChatDbMigrateLegacyInput,+) -> Result<ChatDbMigrateLegacyResult, ApiError> {+ async_runtime::spawn_blocking(move || migrate_legacy_chat_db(&app, &input))+ .await+ .map_err(|_| chat_db_thread_error())?+}+#[tauri::command]pub async fn chat_sync(app: AppHandle,@@ -1659,45 +1694,352 @@ pub fn secure_storage_delete(key: String) -> Result<(), ApiError> {}}-fn chat_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {+fn app_data_dir(app: &AppHandle) -> Result<PathBuf, ApiError> {let resolver = app.path_resolver();let dir = resolver.app_data_dir().ok_or_else(|| ApiError::new("path", "App data directory unavailable"))?;std::fs::create_dir_all(&dir).map_err(|err| ApiError::new("io", err.to_string()))?;- Ok(dir.join("ensu_llmchat.db"))+ Ok(dir)+}++fn chat_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {+ Ok(app_data_dir(app)?.join(CHAT_DB_FILE_NAME_V2))}fn sync_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {- let resolver = app.path_resolver();- let dir = resolver- .app_data_dir()- .ok_or_else(|| ApiError::new("path", "App data directory unavailable"))?;- std::fs::create_dir_all(&dir).map_err(|err| ApiError::new("io", err.to_string()))?;- Ok(dir.join("llmchat_sync.db"))+ Ok(app_data_dir(app)?.join(SYNC_DB_FILE_NAME_V2))}fn attachments_dir_path(app: &AppHandle) -> Result<PathBuf, ApiError> {- let resolver = app.path_resolver();- let dir = resolver- .app_data_dir()- .ok_or_else(|| ApiError::new("path", "App data directory unavailable"))?;- let attachments_dir = dir.join("ensu_llmchat_attachments");+ let dir = app_data_dir(app)?;+ let attachments_dir = dir.join(ATTACHMENTS_DIR_NAME_V2);std::fs::create_dir_all(&attachments_dir).map_err(|err| ApiError::new("io", err.to_string()))?;Ok(attachments_dir)}fn sync_meta_dir_path(app: &AppHandle) -> Result<PathBuf, ApiError> {- let resolver = app.path_resolver();- let dir = resolver- .app_data_dir()- .ok_or_else(|| ApiError::new("path", "App data directory unavailable"))?;+ let dir = app_data_dir(app)?;let meta_dir = dir.join("sync_meta");std::fs::create_dir_all(&meta_dir).map_err(|err| ApiError::new("io", err.to_string()))?;Ok(meta_dir)}+fn legacy_chat_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {+ Ok(app_data_dir(app)?.join(LEGACY_CHAT_DB_FILE_NAME))+}++fn legacy_sync_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {+ Ok(app_data_dir(app)?.join(LEGACY_SYNC_DB_FILE_NAME))+}++fn legacy_attachments_dir_path(app: &AppHandle) -> Result<PathBuf, ApiError> {+ Ok(app_data_dir(app)?.join(LEGACY_ATTACHMENTS_DIR_NAME))+}++fn cleanup_legacy_chat_artifacts(app: &AppHandle) -> Result<(), ApiError> {+ let legacy_db_path = legacy_chat_db_path(app)?;+ let legacy_sync_path = legacy_sync_db_path(app)?;+ let legacy_attachments_dir = legacy_attachments_dir_path(app)?;++ for candidate in [+ legacy_db_path.clone(),+ PathBuf::from(format!("{}-wal", legacy_db_path.display())),+ PathBuf::from(format!("{}-shm", legacy_db_path.display())),+ legacy_sync_path.clone(),+ PathBuf::from(format!("{}-wal", legacy_sync_path.display())),+ PathBuf::from(format!("{}-shm", legacy_sync_path.display())),+ ] {+ if candidate.exists() {+ fs::remove_file(&candidate).map_err(|err| ApiError::new("io", err.to_string()))?;+ }+ }++ if legacy_attachments_dir.exists() {+ fs::remove_dir_all(&legacy_attachments_dir)+ .map_err(|err| ApiError::new("io", err.to_string()))?;+ }++ Ok(())+}++fn verify_migrated_chat_db(+ target_db: &EnsuDb<SqliteBackend>,+ source_session_ids: &[Uuid],+ source_message_ids_by_session: &HashMap<Uuid, Vec<Uuid>>,+ migrated_meta_keys: &[&str],+ target_sync_state: &SyncStateDb<SqliteBackend>,+ target_attachments_dir: &PathBuf,+ expected_attachment_ids: &[String],+) -> Result<(), ApiError> {+ let target_session_ids = target_db+ .list_all_sessions()+ .map_err(ApiError::from)?+ .into_iter()+ .map(|session| session.uuid)+ .collect::<std::collections::HashSet<_>>();++ for session_uuid in source_session_ids {+ if !target_session_ids.contains(session_uuid) {+ return Err(ApiError::new(+ "db_migration_verification",+ format!("Missing migrated session {session_uuid}"),+ ));+ }+ }++ for (session_uuid, message_ids) in source_message_ids_by_session {+ let target_message_ids = target_db+ .get_messages_for_sync(*session_uuid, true)+ .map_err(ApiError::from)?+ .into_iter()+ .map(|message| message.uuid)+ .collect::<std::collections::HashSet<_>>();++ for message_uuid in message_ids {+ if !target_message_ids.contains(message_uuid) {+ return Err(ApiError::new(+ "db_migration_verification",+ format!("Missing migrated message {message_uuid}"),+ ));+ }+ }+ }++ for meta_key in migrated_meta_keys {+ if target_sync_state+ .get_meta(meta_key)+ .map_err(ApiError::from)?+ .is_none()+ {+ return Err(ApiError::new(+ "db_migration_verification",+ format!("Missing migrated sync meta key {meta_key}"),+ ));+ }+ }++ for attachment_id in expected_attachment_ids {+ let target_path = target_attachments_dir.join(attachment_id);+ if !target_path.exists() {+ return Err(ApiError::new(+ "db_migration_verification",+ format!("Missing migrated attachment {attachment_id}"),+ ));+ }+ }++ Ok(())+}++fn migrate_legacy_chat_db(+ app: &AppHandle,+ input: &ChatDbMigrateLegacyInput,+) -> Result<ChatDbMigrateLegacyResult, ApiError> {+ let legacy_db_path = legacy_chat_db_path(app)?;+ if !legacy_db_path.exists() {+ return Ok(ChatDbMigrateLegacyResult {+ did_migrate: false,+ migrated_sessions: 0,+ migrated_messages: 0,+ migrated_attachments: 0,+ });+ }++ let legacy_sync_path = legacy_sync_db_path(app)?;+ let legacy_attachments_dir = legacy_attachments_dir_path(app)?;+ let target_db_path = chat_db_path(app)?;+ let target_sync_path = sync_db_path(app)?;+ let target_attachments_dir = attachments_dir_path(app)?;++ let legacy_key = core_crypto::decode_b64(&input.legacy_key_b64).map_err(ApiError::from)?;+ let key = core_crypto::decode_b64(&input.key_b64).map_err(ApiError::from)?;++ let legacy_db =+ EnsuDb::open_sqlite_with_defaults(&legacy_db_path, &legacy_sync_path, legacy_key)+ .map_err(ApiError::from)?;+ let target_db = EnsuDb::open_sqlite_with_defaults(&target_db_path, &target_sync_path, key)+ .map_err(ApiError::from)?;+ let legacy_sync_state =+ SyncStateDb::open_sqlite_with_defaults(&legacy_sync_path).map_err(ApiError::from)?;+ let target_sync_state =+ SyncStateDb::open_sqlite_with_defaults(&target_sync_path).map_err(ApiError::from)?;++ let mut migrated_sessions = 0_i64;+ let mut migrated_messages = 0_i64;+ let mut migrated_attachments = 0_i64;+ let mut migrated_meta_keys = Vec::new();+ let mut source_session_ids = Vec::new();+ let mut source_message_ids_by_session = HashMap::new();+ let mut expected_attachment_ids = Vec::new();++ for meta_key in [+ SYNC_CURSOR_META_KEY,+ SYNC_CHAT_KEY_META_KEY,+ SYNC_OFFLINE_SEED_META_KEY,+ ] {+ if let Some(value) = legacy_sync_state+ .get_meta(meta_key)+ .map_err(ApiError::from)?+ {+ target_sync_state+ .set_meta(meta_key, &value)+ .map_err(ApiError::from)?;+ migrated_meta_keys.push(meta_key);+ }+ }++ for session in legacy_db.list_all_sessions().map_err(ApiError::from)? {+ source_session_ids.push(session.uuid);+ target_db+ .upsert_session(+ session.uuid,+ &session.title,+ session.created_at,+ session.updated_at,+ session.remote_id.clone(),+ session.needs_sync,+ session.deleted_at,+ )+ .map_err(ApiError::from)?;+ if let Some(state) = legacy_sync_state+ .get_session_state(session.uuid)+ .map_err(ApiError::from)?+ {+ target_sync_state+ .set_session_state(+ session.uuid,+ state.remote_id.as_deref(),+ state.server_updated_at,+ )+ .map_err(ApiError::from)?;+ }+ migrated_sessions += 1;++ for message in legacy_db+ .get_messages_for_sync(session.uuid, true)+ .map_err(ApiError::from)?+ {+ source_message_ids_by_session+ .entry(session.uuid)+ .or_insert_with(Vec::new)+ .push(message.uuid);+ let uploads = legacy_db+ .get_uploads_for_message(message.uuid)+ .map_err(ApiError::from)?;+ let uploaded_at_by_id = uploads+ .into_iter()+ .map(|upload| (upload.attachment_id, upload.uploaded_at))+ .collect::<HashMap<_, _>>();+ let attachments = message+ .attachments+ .iter()+ .cloned()+ .map(|attachment| {+ let uploaded_at = uploaded_at_by_id+ .get(&attachment.id)+ .and_then(|value| *value);+ ensu_db::Attachment {+ id: attachment.id,+ kind: attachment.kind,+ size: attachment.size,+ name: attachment.name,+ uploaded_at,+ }+ })+ .collect::<Vec<_>>();++ target_db+ .insert_message_with_uuid_and_state(+ message.uuid,+ message.session_uuid,+ message.sender.as_str(),+ &message.text,+ message.parent_message_uuid,+ attachments.clone(),+ message.created_at,+ message.deleted_at,+ message.needs_sync,+ )+ .map_err(ApiError::from)?;++ if let Some(remote_id) = message.remote_id.as_deref() {+ target_db+ .set_message_remote_id(message.uuid, remote_id)+ .map_err(ApiError::from)?;+ }+ if let Some(state) = legacy_sync_state+ .get_message_state(message.uuid)+ .map_err(ApiError::from)?+ {+ target_sync_state+ .set_message_state(+ message.uuid,+ state.remote_id.as_deref(),+ state.server_updated_at,+ )+ .map_err(ApiError::from)?;+ }++ for attachment in attachments {+ if let Some(remote_id) = legacy_db+ .get_attachment_remote_id(&attachment.id)+ .map_err(ApiError::from)?+ {+ target_db+ .set_attachment_remote_id(&attachment.id, Some(&remote_id))+ .map_err(ApiError::from)?;+ }++ if let Some(state) = legacy_db+ .get_attachment_upload_state(&attachment.id)+ .map_err(ApiError::from)?+ {+ target_db+ .set_attachment_upload_state(&attachment.id, state)+ .map_err(ApiError::from)?;+ }++ let source_path = legacy_attachments_dir.join(&attachment.id);+ let target_path = target_attachments_dir.join(&attachment.id);+ if source_path.exists() && !target_path.exists() {+ fs::copy(&source_path, &target_path)+ .map_err(|err| ApiError::new("io", err.to_string()))?;+ migrated_attachments += 1;+ }+ if source_path.exists() {+ expected_attachment_ids.push(attachment.id.clone());+ }+ }++ migrated_messages += 1;+ }+ }++ verify_migrated_chat_db(+ &target_db,+ &source_session_ids,+ &source_message_ids_by_session,+ &migrated_meta_keys,+ &target_sync_state,+ &target_attachments_dir,+ &expected_attachment_ids,+ )?;++ drop(legacy_sync_state);+ drop(legacy_db);++ cleanup_legacy_chat_artifacts(app)?;++ Ok(ChatDbMigrateLegacyResult {+ did_migrate: true,+ migrated_sessions,+ migrated_messages,+ migrated_attachments,+ })+}+fn with_chat_db<T, F>(inner: &Arc<Mutex<Option<ChatDbHolder>>>,app: &AppHandle,diff --git a/rust/apps/ensu/src-tauri/src/main.rs b/rust/apps/ensu/src-tauri/src/main.rsindex 93ae87d47e..b3436ea567 100644--- a/rust/apps/ensu/src-tauri/src/main.rs+++ b/rust/apps/ensu/src-tauri/src/main.rs@@ -54,6 +54,7 @@ fn main() {commands::chat_db_get_pending_deletions,commands::chat_db_hard_delete,commands::chat_db_reset,+ commands::chat_db_migrate_legacy,commands::chat_sync,commands::llm_init_backend,commands::llm_load_model,diff --git a/rust/apps/ensu/src-tauri/tauri.conf.json b/rust/apps/ensu/src-tauri/tauri.conf.jsonindex 205bab6419..7c3256f1ee 100644--- a/rust/apps/ensu/src-tauri/tauri.conf.json+++ b/rust/apps/ensu/src-tauri/tauri.conf.json@@ -7,7 +7,7 @@},"package": {"productName": "Ensu",- "version": "0.1.11"+ "version": "0.1.12"},"tauri": {"windows": [diff --git a/rust/ensu/db/src/db.rs b/rust/ensu/db/src/db.rsindex f416d0fc49..3f8c78f86b 100644--- a/rust/ensu/db/src/db.rs+++ b/rust/ensu/db/src/db.rs@@ -102,6 +102,15 @@ impl<B: Backend> ChatDb<B> {rows.iter().map(|row| self.session_from_row(row)).collect()}+ pub fn list_all_sessions(&self) -> Result<Vec<Session>> {+ let rows = self.backend.query(+ "SELECT session_uuid, title, created_at, updated_at, server_updated_at, remote_id, needs_sync, deleted_at \+ FROM sessions ORDER BY updated_at DESC",+ &[],+ )?;+ rows.iter().map(|row| self.session_from_row(row)).collect()+ }+pub fn list_sessions_with_preview(&self) -> Result<Vec<SessionWithPreview>> {let sessions = self.list_sessions()?;let mut with_preview = Vec::with_capacity(sessions.len());diff --git a/rust/ensu/db/src/ensu.rs b/rust/ensu/db/src/ensu.rsindex 5763d07a3b..4370952c6d 100644--- a/rust/ensu/db/src/ensu.rs+++ b/rust/ensu/db/src/ensu.rs@@ -31,6 +31,10 @@ impl<B: crate::Backend> EnsuDb<B> {self.chat.list_sessions()}+ pub fn list_all_sessions(&self) -> Result<Vec<Session>> {+ self.chat.list_all_sessions()+ }+pub fn list_sessions_with_preview(&self) -> Result<Vec<SessionWithPreview>> {self.chat.list_sessions_with_preview()}diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsxindex d46d0ee38d..69b24c1460 100644--- a/web/apps/ensu/src/pages/chat.tsx+++ b/web/apps/ensu/src/pages/chat.tsx@@ -2866,13 +2866,19 @@ const Page: React.FC = () => {import("@tauri-apps/api/shell"),]);const root = await appDataDir();- const dir = await join(root, "ensu_llmchat_attachments");+ const dir = await join(root, "ensu_llmchat_attachments_v2");await createDir(dir, { recursive: true });const filePath = await join(dir, filename);await writeBinaryFile({ path: filePath, contents: bytes });- await open(filePath);+ const normalizedPath = filePath.replace(/\\/g, "/");+ const fileUrl = new URL("file:///");+ fileUrl.pathname = normalizedPath.startsWith("/")+ ? normalizedPath+ : `/${normalizedPath}`;+ const openTarget = fileUrl.toString();+ await open(openTarget);return;}diff --git a/web/apps/ensu/src/services/chat/chatKey.ts b/web/apps/ensu/src/services/chat/chatKey.tsindex e21dd67dd6..4ed15811c4 100644--- a/web/apps/ensu/src/services/chat/chatKey.ts+++ b/web/apps/ensu/src/services/chat/chatKey.ts@@ -1,5 +1,6 @@import { savedLocalUser } from "ente-accounts/services/accounts-db";import { HTTPError } from "ente-base/http";+import log from "ente-base/log";import {isTauriAppRuntime,secureStorageDelete,@@ -12,12 +13,15 @@ import { ChatKeyNotFoundError, createChatKey, getChatKey } from "./gateway";const CHAT_KEY_LOCAL_STORAGE_KEY = "ensu.chatKey";const LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY = "ensu.chatKey.local";const CHAT_KEY_FILE_NAME = "chat-keys.json";-const REMOTE_CHAT_KEY_SECURE_STORAGE_KEY = "remoteChatKey";-const LOCAL_CHAT_KEY_SECURE_STORAGE_KEY = "localChatKey";+const REMOTE_CHAT_KEY_SECURE_STORAGE_KEY = "remoteChatKey.v2";+const LOCAL_CHAT_KEY_SECURE_STORAGE_KEY = "localChatKey.v2";+const LEGACY_REMOTE_CHAT_KEY_SECURE_STORAGE_KEY = "remoteChatKey";+const LEGACY_LOCAL_CHAT_KEY_SECURE_STORAGE_KEY = "localChatKey";type PersistedChatKeys = { remoteChatKey?: string; localChatKey?: string };let _persistedChatKeys: PersistedChatKeys = {};+let _legacyPersistedChatKeys: PersistedChatKeys = {};let _chatKeyStoreInitPromise: Promise<void> | undefined;let _chatKeyStoreInitUserID: number | undefined;@@ -48,6 +52,13 @@ const scopedRemoteChatKeySecureStorageKey = () => {: undefined;};+const scopedLegacyRemoteChatKeySecureStorageKey = () => {+ const userID = savedLocalUser()?.id;+ return userID+ ? `${LEGACY_REMOTE_CHAT_KEY_SECURE_STORAGE_KEY}.${userID}`+ : undefined;+};+const clearLegacyRemoteChatKeyLocalStorage = () =>removeLocalStorageKey(CHAT_KEY_LOCAL_STORAGE_KEY);@@ -98,9 +109,7 @@ const readNativeChatKeys = async (): Promise<PersistedChatKeys> => {const persistNativeChatKeys = async () => {if (!isTauriAppRuntime()) return;- const operations: Promise<void>[] = [- secureStorageDelete(REMOTE_CHAT_KEY_SECURE_STORAGE_KEY),- ];+ const operations: Promise<void>[] = [];const remoteStorageKey = scopedRemoteChatKeySecureStorageKey();if (remoteStorageKey) {if (_persistedChatKeys.remoteChatKey) {@@ -135,6 +144,20 @@ const persistNativeChatKeysSoon = () => {});};+const cleanupLegacyChatKeyCopies = async () => {+ clearLegacyRemoteChatKeyLocalStorage();+ clearScopedRemoteChatKeyLocalStorage();+ removeLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);++ try {+ const { removeFile } = await import("@tauri-apps/api/fs");+ const path = await nativeChatKeyPath();+ await removeFile(path);+ } catch {+ // ignore missing legacy file+ }+};+export const initChatKeyStore = async () => {if (!isTauriAppRuntime()) return;@@ -146,8 +169,15 @@ export const initChatKeyStore = async () => {_chatKeyStoreInitUserID = userID;_chatKeyStoreInitPromise = (async () => {const remoteStorageKey = scopedRemoteChatKeySecureStorageKey();+ const legacyRemoteStorageKey = scopedLegacyRemoteChatKeySecureStorageKey();const remoteLocalStorageKey = scopedRemoteChatKeyLocalStorageKey();- const [secureRemoteChatKey, secureLocalChatKey, nativeKeys] =+ const [+ secureRemoteChatKey,+ secureLocalChatKey,+ legacySecureRemoteChatKey,+ legacySecureLocalChatKey,+ nativeKeys,+ ] =await Promise.all([remoteStorageKey? secureStorageGet(remoteStorageKey).catch(() => undefined)@@ -155,25 +185,33 @@ export const initChatKeyStore = async () => {secureStorageGet(LOCAL_CHAT_KEY_SECURE_STORAGE_KEY).catch(() => undefined,),+ legacyRemoteStorageKey+ ? secureStorageGet(legacyRemoteStorageKey).catch(+ () => undefined,+ )+ : Promise.resolve(undefined),+ secureStorageGet(LEGACY_LOCAL_CHAT_KEY_SECURE_STORAGE_KEY).catch(+ () => undefined,+ ),readNativeChatKeys(),]);- const remoteChatKey =- secureRemoteChatKey ??+ const legacyRemoteChatKey =+ legacySecureRemoteChatKey ??(remoteLocalStorageKey? readLocalStorageKey(remoteLocalStorageKey): undefined);- const localChatKey =- secureLocalChatKey ??+ const legacyLocalChatKey =+ legacySecureLocalChatKey ??nativeKeys.localChatKey ??readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);+ const remoteChatKey = secureRemoteChatKey ?? legacyRemoteChatKey;+ const localChatKey = secureLocalChatKey ?? legacyLocalChatKey;_persistedChatKeys = { remoteChatKey, localChatKey };-- try {- await secureStorageDelete(REMOTE_CHAT_KEY_SECURE_STORAGE_KEY);- } catch {- // Ignore legacy secure storage cleanup failures.- }+ _legacyPersistedChatKeys = {+ remoteChatKey: legacyRemoteChatKey,+ localChatKey: legacyLocalChatKey,+ };if (secureRemoteChatKey !== remoteChatKey ||@@ -181,25 +219,19 @@ export const initChatKeyStore = async () => {) {try {await persistNativeChatKeys();- clearLegacyRemoteChatKeyLocalStorage();- clearScopedRemoteChatKeyLocalStorage();- removeLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);- } catch {- clearLegacyRemoteChatKeyLocalStorage();- // Keep scoped localStorage keys when secure storage is unavailable.+ } catch (error) {+ log.warn(+ "Failed to persist chat keys to secure storage; continuing with in-memory keys",+ error,+ );+ return;}- } else {- clearLegacyRemoteChatKeyLocalStorage();- clearScopedRemoteChatKeyLocalStorage();- removeLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);}try {- const { removeFile } = await import("@tauri-apps/api/fs");- const path = await nativeChatKeyPath();- await removeFile(path);- } catch {- // ignore missing legacy file+ await cleanupLegacyChatKeyCopies();+ } catch (error) {+ log.warn("Failed to clean up legacy chat key copies", error);}})().catch((error: unknown) => {_chatKeyStoreInitPromise = undefined;@@ -245,6 +277,15 @@ export const cachedChatKey = (): string | undefined => {return storageKey ? readLocalStorageKey(storageKey) : undefined;};+export const legacyCachedChatKey = (): string | undefined => {+ if (isTauriAppRuntime()) {+ return _legacyPersistedChatKeys.remoteChatKey;+ }++ const storageKey = scopedRemoteChatKeyLocalStorageKey();+ return storageKey ? readLocalStorageKey(storageKey) : undefined;+};+/*** Return the cached local-only chat key (base64), if present.*/@@ -256,6 +297,14 @@ export const cachedLocalChatKey = (): string | undefined => {return readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);};+export const legacyLocalChatKey = (): string | undefined => {+ if (isTauriAppRuntime()) {+ return _legacyPersistedChatKeys.localChatKey;+ }++ return readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);+};+export const clearCachedChatKey = () => {if (isTauriAppRuntime()) {delete _persistedChatKeys.remoteChatKey;diff --git a/web/apps/ensu/src/services/chat/store.ts b/web/apps/ensu/src/services/chat/store.tsindex 7d1d0f5cba..4006eadc96 100644--- a/web/apps/ensu/src/services/chat/store.ts+++ b/web/apps/ensu/src/services/chat/store.ts@@ -3,7 +3,11 @@ import log from "ente-base/log";import { deleteDB, openDB, type DBSchema, type IDBPDatabase } from "idb";import { base64ToBytes } from "services/base64";import { decryptAttachmentBytes, encryptAttachmentBytes } from "./attachments";-import { cachedLocalChatKey } from "./chatKey";+import {+ cachedLocalChatKey,+ legacyCachedChatKey,+ legacyLocalChatKey,+} from "./chatKey";import {decryptChatField,decryptChatPayload,@@ -12,7 +16,7 @@ import {} from "./crypto";const STORAGE_KEY = "ensu.chat.store.v1";-const NATIVE_MIGRATION_KEY = "ensu.chat.nativeMigration.v1";+const NATIVE_MIGRATION_KEY = "ensu.chat.nativeMigration.v2";const CHAT_DB_NAME = "ensu-chat";const LEGACY_WEB_CHAT_DB_NAME = "ensu.chat.db";@@ -201,6 +205,13 @@ interface NativeMessage {deletedAt?: number | null;}+interface NativeLegacyMigrationResult {+ didMigrate: boolean;+ migratedSessions: number;+ migratedMessages: number;+ migratedAttachments: number;+}+const nowMicros = () => Date.now() * 1000;const isTauriRuntime = () =>@@ -220,22 +231,6 @@ const formatLogError = (error: unknown) => {}};-const getErrorMessage = (error: unknown) => {- if (error instanceof Error) return error.message || error.name;- if (typeof error === "string") return error;- if (error && typeof error === "object") {- const maybeMessage = (error as { message?: unknown }).message;- if (typeof maybeMessage === "string" && maybeMessage.trim()) {- return maybeMessage;- }- }- try {- return JSON.stringify(error);- } catch {- return String(error);- }-};-const getErrorCode = (error: unknown) => {if (!error || typeof error !== "object") return undefined;const code = (error as { code?: unknown }).code;@@ -244,18 +239,10 @@ const getErrorCode = (error: unknown) => {const shouldResetDbError = (error: unknown) => {const code = getErrorCode(error);- if (+ return (code === "db_crypto" ||code === "db_invalid_blob_length" ||code === "db_invalid_encrypted_field"- ) {- return true;- }- const message = getErrorMessage(error).toLowerCase();- return (- message.includes("stream pull failed") ||- message.includes("invalid blob") ||- message.includes("invalid encrypted"));};@@ -541,7 +528,7 @@ const deserializeAttachments = async (): Promise<ChatAttachment[]> => {if (!attachments?.length || !isTauriRuntime()) return [];- const localKey = cachedLocalChatKey();+ const localKey = cachedLocalChatKey() ?? legacyLocalChatKey();return Promise.all(attachments.map(async (attachment) => {@@ -768,7 +755,6 @@ const migrateLegacyChatStoreToNative = async (chatKey: string) => {!legacy.attachmentBytes.length) {localStorage.removeItem(STORAGE_KEY);- markNativeMigrationDone();return;}@@ -843,10 +829,57 @@ const migrateLegacyChatStoreToNative = async (chatKey: string) => {}localStorage.removeItem(STORAGE_KEY);- markNativeMigrationDone();log.info("Finished migrating legacy local chat store to native DB");};+const migrateLegacyNativeChatStoreToV2 = async (chatKey: string) => {+ if (!isTauriRuntime()) return;++ const attemptedKeys = new Set<string>();+ const candidateKeys: string[] = [];+ for (const candidate of [+ legacyCachedChatKey(),+ legacyLocalChatKey(),+ chatKey,+ ]) {+ if (!candidate || attemptedKeys.has(candidate)) continue;+ attemptedKeys.add(candidate);+ candidateKeys.push(candidate);+ }++ for (const candidateKey of candidateKeys) {+ try {+ const result = await invokeChat<NativeLegacyMigrationResult>(+ "chat_db_migrate_legacy",+ {+ input: {+ keyB64: chatKey,+ legacyKeyB64: candidateKey,+ },+ },+ );+ if (result.didMigrate) {+ log.info("Migrated legacy native chat store to v2 DB", result);+ }+ return;+ } catch (error) {+ const code = getErrorCode(error);+ if (+ code === "db_crypto" ||+ code === "db_invalid_blob_length" ||+ code === "db_invalid_encrypted_field"+ ) {+ continue;+ }+ throw error;+ }+ }++ log.warn(+ "Skipping legacy native chat migration because the available legacy keys could not decrypt the legacy DB",+ );+};+export const initializeChatStorePersistence = async (chatKey: string) => {if (_chatPersistenceInitKey === chatKey && _chatPersistenceInitPromise) {return _chatPersistenceInitPromise;@@ -855,8 +888,13 @@ export const initializeChatStorePersistence = async (chatKey: string) => {_chatPersistenceInitKey = chatKey;const initPromise = (async () => {if (isTauriRuntime()) {- if (!hasLegacyChatStore() && isNativeMigrationDone()) return;- await migrateLegacyChatStoreToNative(chatKey);+ if (!isNativeMigrationDone()) {+ await migrateLegacyNativeChatStoreToV2(chatKey);+ if (hasLegacyChatStore()) {+ await migrateLegacyChatStoreToNative(chatKey);+ }+ markNativeMigrationDone();+ }return;}@@ -1412,7 +1450,7 @@ const attachmentDir = async () => {const { appDataDir, join } = await import("@tauri-apps/api/path");const { createDir } = await import("@tauri-apps/api/fs");const root = await appDataDir();- const dir = await join(root, "ensu_llmchat_attachments");+ const dir = await join(root, "ensu_llmchat_attachments_v2");await createDir(dir, { recursive: true });return dir;})();@@ -1474,7 +1512,7 @@ export const readDecryptedAttachmentBytes = async (try {return await decryptAttachmentBytes(encrypted, chatKey, sessionUuid);} catch (error) {- const localKey = cachedLocalChatKey();+ const localKey = cachedLocalChatKey() ?? legacyLocalChatKey();if (!localKey || localKey === chatKey) {throw error;}