π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Simplify Ensu chat database initialization
Manav Rathi914bf4ca94a4
diff --git a/rust/apps/ensu/src-tauri/src/commands/chat_db.rs b/rust/apps/ensu/src-tauri/src/commands/chat_db.rsindex c59595c48a..a07f44e86d 100644--- a/rust/apps/ensu/src-tauri/src/commands/chat_db.rs+++ b/rust/apps/ensu/src-tauri/src/commands/chat_db.rs@@ -1,5 +1,5 @@-use std::fs::{self, File};-use std::path::{Path, PathBuf};+use std::fs;+use std::path::PathBuf;use std::sync::{Arc, Mutex};use ente_core::crypto;@@ -9,6 +9,7 @@ use tauri::async_runtime;use tauri::{AppHandle, Manager, State};use uuid::Uuid;+use crate::commands::chat_db_migration;use crate::commands::common::{ApiError, app_data_dir};use crate::logging;@@ -18,15 +19,11 @@ pub struct ChatDbState {}struct ChatDbHolder {- key_b64: String,db: Arc<ChatDb<SqliteBackend>>,}const CHAT_DB_FILE_NAME: &str = "ensu_llmchat_v2.db";const ATTACHMENTS_DIR_NAME: &str = "ensu_llmchat_attachments_v2";-const V1_CHAT_DB_FILE_NAME: &str = "ensu_llmchat.db";-const V1_ATTACHMENTS_DB_FILE_NAME: &str = "llmchat_sync.db";-const V1_ATTACHMENTS_DIR_NAME: &str = "ensu_llmchat_attachments";fn chat_db_thread_error() -> ApiError {ApiError::new("db_thread", "Chat DB task failed")@@ -228,17 +225,16 @@ pub struct ChatMessageUpsertInput {#[derive(Deserialize)]#[serde(rename_all = "camelCase")]-pub struct ChatDbImportV1Input {+pub struct ChatDbOpenInput {key_b64: String,+ recovery_keys_b64: Vec<String>,}#[tauri::command]pub async fn chat_db_list_sessions(state: State<'_, ChatDbState>,- app: AppHandle,- key_b64: String,) -> Result<Vec<ChatSessionDto>, ApiError> {- with_chat_db_async(&state, app, key_b64, |db| {+ with_chat_db_async(&state, |db| {Ok(db.list_sessions()?.into_iter()@@ -251,10 +247,8 @@ pub async fn chat_db_list_sessions(#[tauri::command]pub async fn chat_db_list_sessions_with_preview(state: State<'_, ChatDbState>,- app: AppHandle,- key_b64: String,) -> Result<Vec<ChatSessionPreviewDto>, ApiError> {- with_chat_db_async(&state, app, key_b64, |db| {+ with_chat_db_async(&state, |db| {Ok(db.list_sessions_with_preview()?.into_iter()@@ -267,12 +261,10 @@ pub async fn chat_db_list_sessions_with_preview(#[tauri::command]pub async fn chat_db_get_session(state: State<'_, ChatDbState>,- app: AppHandle,- key_b64: String,session_uuid: String,) -> Result<Option<ChatSessionDto>, ApiError> {let uuid = parse_uuid(&session_uuid)?;- with_chat_db_async(&state, app, key_b64, move |db| {+ with_chat_db_async(&state, move |db| {Ok(db.get_session(uuid)?.map(ChatSessionDto::from))}).await@@ -281,11 +273,9 @@ pub async fn chat_db_get_session(#[tauri::command]pub async fn chat_db_create_session(state: State<'_, ChatDbState>,- app: AppHandle,- key_b64: String,title: String,) -> Result<ChatSessionDto, ApiError> {- with_chat_db_async(&state, app, key_b64, move |db| {+ with_chat_db_async(&state, move |db| {Ok(ChatSessionDto::from(db.create_session(&title)?))}).await@@ -294,38 +284,29 @@ pub async fn chat_db_create_session(#[tauri::command]pub async fn chat_db_update_session_title(state: State<'_, ChatDbState>,- app: AppHandle,- key_b64: String,session_uuid: String,title: String,) -> Result<(), ApiError> {let uuid = parse_uuid(&session_uuid)?;- with_chat_db_async(&state, app, key_b64, move |db| {- db.update_session_title(uuid, &title)- })- .await+ with_chat_db_async(&state, move |db| db.update_session_title(uuid, &title)).await}#[tauri::command]pub async fn chat_db_delete_session(state: State<'_, ChatDbState>,- app: AppHandle,- key_b64: String,session_uuid: String,) -> 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+ with_chat_db_async(&state, move |db| db.delete_session(uuid)).await}#[tauri::command]pub async fn chat_db_get_messages(state: State<'_, ChatDbState>,- app: AppHandle,- key_b64: String,session_uuid: String,) -> Result<Vec<ChatMessageDto>, ApiError> {let uuid = parse_uuid(&session_uuid)?;- with_chat_db_async(&state, app, key_b64, move |db| {+ with_chat_db_async(&state, move |db| {Ok(db.get_messages(uuid)?.into_iter()@@ -338,15 +319,13 @@ pub async fn chat_db_get_messages(#[tauri::command]pub async fn chat_db_insert_message(state: State<'_, ChatDbState>,- app: AppHandle,- key_b64: String,input: ChatMessageInsertInput,) -> Result<ChatMessageDto, ApiError> {let session_uuid = parse_uuid(&input.session_uuid)?;let parent = optional_uuid(&input.parent_message_uuid)?;let sender = normalize_sender(&input.sender)?;let attachments = convert_attachments(input.attachments)?;- with_chat_db_async(&state, app, key_b64, move |db| {+ with_chat_db_async(&state, move |db| {Ok(ChatMessageDto::from(db.insert_message(session_uuid,sender,@@ -361,27 +340,20 @@ pub async fn chat_db_insert_message(#[tauri::command]pub async fn chat_db_update_message_text(state: State<'_, ChatDbState>,- app: AppHandle,- key_b64: String,message_uuid: String,text: String,) -> Result<(), ApiError> {let uuid = parse_uuid(&message_uuid)?;- with_chat_db_async(&state, app, key_b64, move |db| {- db.update_message_text(uuid, &text)- })- .await+ with_chat_db_async(&state, move |db| db.update_message_text(uuid, &text)).await}#[tauri::command]pub async fn chat_db_upsert_session(state: State<'_, ChatDbState>,- app: AppHandle,- key_b64: String,input: ChatSessionUpsertInput,) -> Result<ChatSessionDto, ApiError> {let uuid = parse_uuid(&input.session_uuid)?;- with_chat_db_async(&state, app, key_b64, move |db| {+ with_chat_db_async(&state, move |db| {Ok(ChatSessionDto::from(db.upsert_session(uuid,&input.title,@@ -395,8 +367,6 @@ pub async fn chat_db_upsert_session(#[tauri::command]pub async fn chat_db_insert_message_with_uuid(state: State<'_, ChatDbState>,- app: AppHandle,- key_b64: String,input: ChatMessageUpsertInput,) -> Result<ChatMessageDto, ApiError> {let message_uuid = parse_uuid(&input.message_uuid)?;@@ -404,7 +374,7 @@ pub async fn chat_db_insert_message_with_uuid(let parent = optional_uuid(&input.parent_message_uuid)?;let sender = normalize_sender(&input.sender)?;let attachments = convert_attachments(input.attachments)?;- with_chat_db_async(&state, app, key_b64, move |db| {+ with_chat_db_async(&state, move |db| {Ok(ChatMessageDto::from(db.insert_message_with_uuid(message_uuid,session_uuid,@@ -419,43 +389,52 @@ pub async fn chat_db_insert_message_with_uuid(}#[tauri::command]-pub async fn chat_db_import_v1(app: AppHandle, input: ChatDbImportV1Input) -> Result<(), ApiError> {- async_runtime::spawn_blocking(move || import_v1_chat_db(&app, &input))- .await- .map_err(|_| chat_db_thread_error())?-}--#[tauri::command]-pub fn chat_db_cleanup_v1(app: AppHandle) -> Result<(), ApiError> {- cleanup_v1_chat_artifacts(&app)+pub async fn chat_db_open(+ state: State<'_, ChatDbState>,+ app: AppHandle,+ input: ChatDbOpenInput,+) -> Result<(), ApiError> {+ let inner = state.inner.clone();+ async_runtime::spawn_blocking(move || {+ let root = app_data_dir(&app)?;+ let path = chat_db_path(&app)?;+ let attachments = attachments_dir_path(&app)?;+ let key = crypto::decode_b64(&input.key_b64).map_err(ApiError::from)?;+ let recovery_keys = input+ .recovery_keys_b64+ .iter()+ .filter_map(|value| crypto::decode_b64(value).ok())+ .collect::<Vec<_>>();+ chat_db_migration::prepare(&root, &path, &attachments, key.clone(), recovery_keys)?;+ open_chat_db(&inner, path, key)+ })+ .await+ .map_err(|_| chat_db_thread_error())?}#[tauri::command]pub fn chat_db_has_existing_store(app: AppHandle) -> Result<bool, ApiError> {let root = app_data_dir(&app)?;- for name in [CHAT_DB_FILE_NAME, V1_CHAT_DB_FILE_NAME] {- if root- .join(name)- .try_exists()- .map_err(|error| ApiError::new("io", error.to_string()))?- {- return Ok(true);- }+ if root+ .join(CHAT_DB_FILE_NAME)+ .try_exists()+ .map_err(|error| ApiError::new("io", error.to_string()))?+ || chat_db_migration::has_store(&root)?+ {+ return Ok(true);}- for name in [ATTACHMENTS_DIR_NAME, V1_ATTACHMENTS_DIR_NAME] {- let path = root.join(name);- if path- .try_exists()+ let attachments = root.join(ATTACHMENTS_DIR_NAME);+ if attachments+ .try_exists()+ .map_err(|error| ApiError::new("io", error.to_string()))?+ && fs::read_dir(attachments).map_err(|error| ApiError::new("io", error.to_string()))?- && fs::read_dir(path)- .map_err(|error| ApiError::new("io", error.to_string()))?- .next()- .transpose()- .map_err(|error| ApiError::new("io", error.to_string()))?- .is_some()- {- return Ok(true);- }+ .next()+ .transpose()+ .map_err(|error| ApiError::new("io", error.to_string()))?+ .is_some()+ {+ return Ok(true);}Ok(false)}@@ -512,292 +491,46 @@ fn attachments_dir_path(app: &AppHandle) -> Result<PathBuf, ApiError> {Ok(path)}-fn v1_chat_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {- Ok(app_data_dir(app)?.join(V1_CHAT_DB_FILE_NAME))-}--fn v1_attachments_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {- Ok(app_data_dir(app)?.join(V1_ATTACHMENTS_DB_FILE_NAME))-}--fn v1_attachments_dir_path(app: &AppHandle) -> Result<PathBuf, ApiError> {- Ok(app_data_dir(app)?.join(V1_ATTACHMENTS_DIR_NAME))-}--fn remove_sqlite_files(path: &Path) -> Result<(), ApiError> {- for candidate in [- path.to_path_buf(),- PathBuf::from(format!("{}-wal", path.display())),- PathBuf::from(format!("{}-shm", path.display())),- ] {- if candidate- .try_exists()- .map_err(|error| ApiError::new("io", error.to_string()))?- {- fs::remove_file(candidate).map_err(|error| ApiError::new("io", error.to_string()))?;- }- }- Ok(())-}--fn cleanup_v1_chat_artifacts(app: &AppHandle) -> Result<(), ApiError> {- remove_sqlite_files(&v1_chat_db_path(app)?)?;- remove_sqlite_files(&v1_attachments_db_path(app)?)?;- let attachments_dir = v1_attachments_dir_path(app)?;- if attachments_dir- .try_exists()- .map_err(|error| ApiError::new("io", error.to_string()))?- {- fs::remove_dir_all(attachments_dir)- .map_err(|error| ApiError::new("io", error.to_string()))?;- }- Ok(())-}--fn copy_v1_attachment(source: &Path, destination: &Path) -> Result<(), ApiError> {- if destination- .try_exists()- .map_err(|error| ApiError::new("io", error.to_string()))?- {- return Ok(());- }- let temporary = destination.with_extension("migrating");- fs::copy(source, &temporary).map_err(|error| ApiError::new("io", error.to_string()))?;- File::open(&temporary)- .and_then(|file| file.sync_all())- .map_err(|error| ApiError::new("io", error.to_string()))?;- fs::rename(temporary, destination).map_err(|error| ApiError::new("io", error.to_string()))-}--#[cfg(unix)]-fn sync_dir(path: &Path) -> Result<(), ApiError> {- File::open(path)- .and_then(|file| file.sync_all())- .map_err(|error| ApiError::new("io", error.to_string()))-}--#[cfg(not(unix))]-fn sync_dir(_path: &Path) -> Result<(), ApiError> {- Ok(())-}--fn import_v1_chat_db(app: &AppHandle, input: &ChatDbImportV1Input) -> Result<(), ApiError> {- let v1_db_path = v1_chat_db_path(app)?;- if !v1_db_path- .try_exists()- .map_err(|error| ApiError::new("io", error.to_string()))?- {- return Ok(());- }-- 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,+fn open_chat_db(+ inner: &Arc<Mutex<Option<ChatDbHolder>>>,+ path: PathBuf,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(target_db_path, key).map_err(ApiError::from)?;-- for session in v1_db.list_sessions().map_err(ApiError::from)? {- target- .upsert_session(- session.uuid,- &session.title,- session.created_at,- session.updated_at,- )- .map_err(ApiError::from)?;-- for message in v1_db.get_messages(session.uuid).map_err(ApiError::from)? {- target- .insert_message_with_uuid(- message.uuid,- message.session_uuid,- message.sender.as_str(),- &message.text,- message.parent_message_uuid,- message.attachments.clone(),- message.created_at,- )- .map_err(ApiError::from)?;-- for attachment in message.attachments {- let source = v1_attachments_dir.join(&attachment.id);- let destination = target_attachments_dir.join(&attachment.id);- if source- .try_exists()- .map_err(|error| ApiError::new("io", error.to_string()))?- {- copy_v1_attachment(&source, &destination)?;- }- }- }- }- sync_dir(&target_attachments_dir)?;+ logging::log("ChatDb", format!("opening chat DB db={}", path.display()));+ let db = ChatDb::open_sqlite_with_defaults(path, key).map_err(|error| {+ logging::log("ChatDb", format!("failed to open chat DB error={error}"));+ ApiError::from(error)+ })?;+ db.list_sessions().map_err(ApiError::from)?;+ *inner+ .lock()+ .map_err(|_| ApiError::new("lock", "Failed to lock chat DB state"))? =+ Some(ChatDbHolder { db: Arc::new(db) });+ logging::log("ChatDb", "chat DB opened");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,- key_b64: &str,- operation: F,-) -> Result<T, ApiError>+fn with_chat_db<T, F>(inner: &Arc<Mutex<Option<ChatDbHolder>>>, operation: F) -> Result<T, ApiError>whereF: FnOnce(&ChatDb<SqliteBackend>) -> Result<T, DbError>,{- let db = {- let mut guard = inner- .lock()- .map_err(|_| ApiError::new("lock", "Failed to lock chat DB state"))?;- let needs_open = guard- .as_ref()- .map(|holder| holder.key_b64 != key_b64)- .unwrap_or(true);-- if needs_open {- let key = crypto::decode_b64(key_b64).map_err(ApiError::from)?;- let path = chat_db_path(app)?;- logging::log("ChatDb", format!("opening chat DB db={}", path.display()));- let db = ChatDb::open_sqlite_with_defaults(path, key).map_err(|error| {- logging::log("ChatDb", format!("failed to open chat DB error={error}"));- ApiError::from(error)- })?;- *guard = Some(ChatDbHolder {- key_b64: key_b64.to_string(),- db: Arc::new(db),- });- logging::log("ChatDb", "chat DB opened");- }-- guard- .as_ref()- .ok_or_else(|| ApiError::new("db", "Chat DB not initialized"))?- .db- .clone()- };-+ let db = inner+ .lock()+ .map_err(|_| ApiError::new("lock", "Failed to lock chat DB state"))?+ .as_ref()+ .ok_or_else(|| ApiError::new("db", "Chat DB not initialized"))?+ .db+ .clone();operation(db.as_ref()).map_err(ApiError::from)}-async fn with_chat_db_async<T, F>(- state: &ChatDbState,- app: AppHandle,- key_b64: String,- operation: F,-) -> Result<T, ApiError>+async fn with_chat_db_async<T, F>(state: &ChatDbState, operation: F) -> Result<T, ApiError>whereT: Send + 'static,F: FnOnce(&ChatDb<SqliteBackend>) -> Result<T, DbError> + Send + 'static,{let inner = state.inner.clone();- async_runtime::spawn_blocking(move || with_chat_db(&inner, &app, &key_b64, operation))+ async_runtime::spawn_blocking(move || with_chat_db(&inner, operation)).await.map_err(|_| chat_db_thread_error())?}diff --git a/rust/apps/ensu/src-tauri/src/commands/chat_db_migration.rs b/rust/apps/ensu/src-tauri/src/commands/chat_db_migration.rsnew file mode 100644index 0000000000..9c295a2102--- /dev/null+++ b/rust/apps/ensu/src-tauri/src/commands/chat_db_migration.rs@@ -0,0 +1,264 @@+use std::fs::{self, File};+use std::path::{Path, PathBuf};++use ente_ensu::db::{ChatDb, Error as DbError};++use super::common::ApiError;++const SOURCE_DB: &str = "ensu_llmchat.db";+const SOURCE_ATTACHMENTS_DB: &str = "llmchat_sync.db";+const SOURCE_ATTACHMENTS: &str = "ensu_llmchat_attachments";++pub(super) fn has_store(root: &Path) -> Result<bool, ApiError> {+ if exists(&root.join(SOURCE_DB))? {+ return Ok(true);+ }+ let attachments = root.join(SOURCE_ATTACHMENTS);+ Ok(exists(&attachments)?+ && fs::read_dir(attachments)+ .map_err(io_error)?+ .next()+ .transpose()+ .map_err(io_error)?+ .is_some())+}++pub(super) fn prepare(+ root: &Path,+ target_db: &Path,+ target_attachments: &Path,+ target_key: Vec<u8>,+ recovery_keys: Vec<Vec<u8>>,+) -> Result<(), ApiError> {+ let source_db = root.join(SOURCE_DB);+ if exists(&source_db)? {+ let source_key = select_source_key(&source_db, &recovery_keys)?;+ import(+ &source_db,+ &root.join(SOURCE_ATTACHMENTS),+ target_db,+ target_attachments,+ source_key,+ target_key,+ )?;+ }+ cleanup(root)+}++fn select_source_key(path: &Path, keys: &[Vec<u8>]) -> Result<Vec<u8>, ApiError> {+ for key in keys {+ let db = match ChatDb::open_sqlite_with_defaults(path, key.clone()) {+ Ok(db) => db,+ Err(DbError::InvalidKeyLength { .. }) => continue,+ Err(error) => return Err(ApiError::from(error)),+ };+ match db.list_sessions() {+ Ok(_) => return Ok(key.clone()),+ Err(+ DbError::Crypto(_)+ | DbError::InvalidBlobLength { .. }+ | DbError::InvalidEncryptedField+ | DbError::Utf8(_),+ ) => {}+ Err(error) => return Err(ApiError::from(error)),+ }+ }+ Err(ApiError::new(+ "db_crypto",+ "No stored key could decrypt the old chat database",+ ))+}++fn import(+ source_db: &Path,+ source_attachments: &Path,+ target_db: &Path,+ target_attachments: &Path,+ source_key: Vec<u8>,+ target_key: Vec<u8>,+) -> Result<(), ApiError> {+ let source =+ ChatDb::open_sqlite_with_defaults(source_db, source_key).map_err(ApiError::from)?;+ let target =+ ChatDb::open_sqlite_with_defaults(target_db, target_key).map_err(ApiError::from)?;++ for session in source.list_sessions().map_err(ApiError::from)? {+ target+ .upsert_session(+ session.uuid,+ &session.title,+ session.created_at,+ session.updated_at,+ )+ .map_err(ApiError::from)?;+ for message in source.get_messages(session.uuid).map_err(ApiError::from)? {+ target+ .insert_message_with_uuid(+ message.uuid,+ message.session_uuid,+ message.sender.as_str(),+ &message.text,+ message.parent_message_uuid,+ message.attachments.clone(),+ message.created_at,+ )+ .map_err(ApiError::from)?;+ for attachment in message.attachments {+ let from = source_attachments.join(&attachment.id);+ let to = target_attachments.join(&attachment.id);+ if exists(&from)? && !exists(&to)? {+ copy_attachment(&from, &to)?;+ }+ }+ }+ }+ for session in target.list_sessions().map_err(ApiError::from)? {+ target.get_messages(session.uuid).map_err(ApiError::from)?;+ }+ sync_dir(target_attachments)+}++fn copy_attachment(source: &Path, target: &Path) -> Result<(), ApiError> {+ let temporary = target.with_extension("migrating");+ fs::copy(source, &temporary).map_err(io_error)?;+ File::open(&temporary)+ .and_then(|file| file.sync_all())+ .map_err(io_error)?;+ fs::rename(temporary, target).map_err(io_error)+}++#[cfg(unix)]+fn sync_dir(path: &Path) -> Result<(), ApiError> {+ File::open(path)+ .and_then(|file| file.sync_all())+ .map_err(io_error)+}++#[cfg(not(unix))]+fn sync_dir(_path: &Path) -> Result<(), ApiError> {+ Ok(())+}++fn cleanup(root: &Path) -> Result<(), ApiError> {+ remove_sqlite_files(&root.join(SOURCE_DB))?;+ remove_sqlite_files(&root.join(SOURCE_ATTACHMENTS_DB))?;+ let attachments = root.join(SOURCE_ATTACHMENTS);+ if exists(&attachments)? {+ fs::remove_dir_all(attachments).map_err(io_error)?;+ }+ Ok(())+}++fn remove_sqlite_files(path: &Path) -> Result<(), ApiError> {+ for candidate in [+ path.to_path_buf(),+ PathBuf::from(format!("{}-wal", path.display())),+ PathBuf::from(format!("{}-shm", path.display())),+ ] {+ if exists(&candidate)? {+ fs::remove_file(candidate).map_err(io_error)?;+ }+ }+ Ok(())+}++fn exists(path: &Path) -> Result<bool, ApiError> {+ path.try_exists().map_err(io_error)+}++fn io_error(error: std::io::Error) -> ApiError {+ ApiError::new("io", error.to_string())+}++#[cfg(test)]+mod tests {+ use super::*;+ use ente_ensu::db::{AttachmentKind, AttachmentMeta};+ use uuid::Uuid;++ fn fixture(key: &[u8]) -> (PathBuf, Uuid, String) {+ let root = std::env::temp_dir().join(format!("ensu-import-{}", Uuid::new_v4()));+ let attachments = root.join(SOURCE_ATTACHMENTS);+ fs::create_dir_all(&attachments).unwrap();+ 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 = Uuid::new_v4().to_string();+ source+ .insert_message(+ session.uuid,+ "self",+ "Migrated message",+ None,+ vec![AttachmentMeta {+ id: attachment.clone(),+ kind: AttachmentKind::Document,+ size: 7,+ name: "note.txt".to_string(),+ }],+ )+ .unwrap();+ fs::write(attachments.join(&attachment), b"payload").unwrap();+ (root, session.uuid, attachment)+ }++ #[test]+ fn preparation_imports_with_a_recovery_key_and_cleans_up() {+ let source_key = vec![7; 32];+ let target_key = vec![8; 32];+ let (root, session, attachment) = fixture(&source_key);+ let target_db = root.join("target.db");+ let target_attachments = root.join("target-attachments");+ fs::create_dir(&target_attachments).unwrap();++ prepare(+ &root,+ &target_db,+ &target_attachments,+ target_key.clone(),+ vec![vec![9; 32], source_key],+ )+ .unwrap();+ prepare(+ &root,+ &target_db,+ &target_attachments,+ target_key.clone(),+ vec![],+ )+ .unwrap();++ let target = ChatDb::open_sqlite_with_defaults(target_db, target_key).unwrap();+ assert_eq!(+ target.get_messages(session).unwrap()[0].text,+ "Migrated message"+ );+ assert_eq!(+ fs::read(target_attachments.join(attachment)).unwrap(),+ b"payload"+ );+ assert!(!root.join(SOURCE_DB).exists());+ fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn failed_key_recovery_preserves_the_source() {+ let source_key = vec![10; 32];+ let (root, _, attachment) = fixture(&source_key);+ let target_attachments = root.join("target-attachments");+ fs::create_dir(&target_attachments).unwrap();++ assert!(+ prepare(+ &root,+ &root.join("target.db"),+ &target_attachments,+ vec![11; 32],+ vec![vec![12; 32]],+ )+ .is_err()+ );+ assert!(root.join(SOURCE_DB).exists());+ assert!(root.join(SOURCE_ATTACHMENTS).join(attachment).exists());+ fs::remove_dir_all(root).unwrap();+ }+}diff --git a/rust/apps/ensu/src-tauri/src/commands/mod.rs b/rust/apps/ensu/src-tauri/src/commands/mod.rsindex 8898522ab7..84740e7464 100644--- a/rust/apps/ensu/src-tauri/src/commands/mod.rs+++ b/rust/apps/ensu/src-tauri/src/commands/mod.rs@@ -1,4 +1,5 @@pub(crate) mod chat_db;+mod chat_db_migration;mod common;pub(crate) mod config;pub(crate) mod crypto;diff --git a/rust/apps/ensu/src-tauri/src/main.rs b/rust/apps/ensu/src-tauri/src/main.rsindex f1f6999321..0120031eb9 100644--- a/rust/apps/ensu/src-tauri/src/main.rs+++ b/rust/apps/ensu/src-tauri/src/main.rs@@ -52,8 +52,7 @@ fn main() {commands::chat_db::chat_db_upsert_session,commands::chat_db::chat_db_insert_message_with_uuid,commands::chat_db::chat_db_compress_attachment_image_file,- commands::chat_db::chat_db_import_v1,- commands::chat_db::chat_db_cleanup_v1,+ commands::chat_db::chat_db_open,commands::chat_db::chat_db_has_existing_store,commands::llm::llm_init_backend,commands::llm::llm_load_model,diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsxindex f718e061dd..e1907cd3a0 100644--- a/web/apps/ensu/src/pages/chat.tsx+++ b/web/apps/ensu/src/pages/chat.tsx@@ -2314,7 +2314,7 @@ const Page: React.FC = () => {lastGenerationRef.current = null;}- await deleteSession(sessionId, chatKey);+ await deleteSession(sessionId);removeSessionFromState(sessionId);},[chatKey, removeSessionFromState],diff --git a/web/apps/ensu/src/services/chat/chatKey.ts b/web/apps/ensu/src/services/chat/chatKey.tsindex 64c621a8aa..6fc6a426bf 100644--- a/web/apps/ensu/src/services/chat/chatKey.ts+++ b/web/apps/ensu/src/services/chat/chatKey.ts@@ -7,6 +7,7 @@ const LOCAL_KEY = "ensu.chatKey.local";const CURRENT_SECURE_KEY = "localChatKey.v2";let _localKey: string | undefined;+let _migrationSourceKeys: string[] = [];let _initPromise: Promise<void> | undefined;const localGet = (key: string) =>@@ -20,11 +21,13 @@ export const initChatKeyStore = async () => {_initPromise = (async () => {const current = await secureStorageGet(CURRENT_SECURE_KEY);- _localKey = await promoteLocalChatKey(+ const promotion = await promoteLocalChatKey(current,CURRENT_SECURE_KEY,LOCAL_KEY,);+ _localKey = promotion.key;+ _migrationSourceKeys = promotion.sourceKeys;})().catch((error: unknown) => {_initPromise = undefined;throw error;@@ -35,6 +38,8 @@ export const initChatKeyStore = async () => {export const cachedLocalChatKey = () =>isTauriRuntime() ? _localKey : localGet(LOCAL_KEY);+export const localChatMigrationSourceKeys = () => _migrationSourceKeys;+const persistLocalKey = async (key: string) => {if (isTauriRuntime()) {await secureStorageSet(CURRENT_SECURE_KEY, key);diff --git a/web/apps/ensu/src/services/chat/keyMigration.ts b/web/apps/ensu/src/services/chat/keyMigration.tsindex 5fdd3d0e7e..eb576afba9 100644--- a/web/apps/ensu/src/services/chat/keyMigration.ts+++ b/web/apps/ensu/src/services/chat/keyMigration.ts@@ -8,7 +8,6 @@ import {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;@@ -38,19 +37,30 @@ const readKeyFile = async () => {export const isLocalChatMigrationDone = () => localGet(MIGRATION_DONE) === "1";+export interface LocalChatKeyPromotion {+ key?: string;+ sourceKeys: string[];+}+export const promoteLocalChatKey = async (current: string | undefined,currentSecureKey: string,browserKey: string,-) => {- if (isLocalChatMigrationDone()) return current;+): Promise<LocalChatKeyPromotion> => {+ if (isLocalChatMigrationDone()) {+ return { key: current, sourceKeys: current ? [current] : [] };+ }const [oldSecure, file] = await Promise.all([secureStorageGet(OLD_LOCAL_SECURE_KEY),readKeyFile(),]);- const key = current ?? localGet(browserKey) ?? oldSecure ?? file;+ const sourceKeys = [current, localGet(browserKey), oldSecure, file].filter(+ (key, index, keys): key is string =>+ !!key && keys.indexOf(key) === index,+ );+ const key = sourceKeys[0];if (key && key !== current) await secureStorageSet(currentSecureKey, key);- return key;+ return { key, sourceKeys };};export const hasRetiredLocalChatStore = () => !!localGet(LOCAL_STORE);@@ -68,13 +78,10 @@ const retiredUserID = () => {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",...(userIDdiff --git a/web/apps/ensu/src/services/chat/migration.ts b/web/apps/ensu/src/services/chat/migration.tsindex 5812d254d9..fd6079014a 100644--- a/web/apps/ensu/src/services/chat/migration.ts+++ b/web/apps/ensu/src/services/chat/migration.ts@@ -2,20 +2,18 @@ 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 { localChatMigrationSourceKeys } from "./chatKey";import {finalizeLocalChatMigration,isLocalChatMigrationDone,} from "./keyMigration";import {- attachmentBytesExists,chatDb,decryptMessageTextStrict,decryptSessionTitleStrict,deserializeAttachmentsStrict,invokeChat,pruneOrphanedAttachmentBytes,- readAttachmentBytes,writeAttachmentBytes,type StoredAttachment,type StoredMessage,@@ -200,16 +198,35 @@ const importOldBrowserStores = async () => {cleanupOldBrowserStores();};-const importLocalStorageToNative = async (chatKey: string) => {+const localStorageSourceKey = async (+ source: BrowserStore,+ sourceKeys: string[],+) => {+ for (const key of sourceKeys) {+ try {+ if (source.sessions[0]) {+ await decryptSessionTitleStrict(source.sessions[0], key);+ } else if (source.messages[0]) {+ await decryptMessageTextStrict(source.messages[0], key);+ }+ return key;+ } catch {+ // Try the next migration-only key.+ }+ }+ throw new Error("No stored key could decrypt the old local chat store");+};++const importLocalStorageToNative = async (sourceKeys: string[]) => {const source = localStorageStore();+ const sourceKey = await localStorageSourceKey(source, sourceKeys);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),+ title: await decryptSessionTitleStrict(session, sourceKey),createdAt: session.createdAt,updatedAt: session.updatedAt,},@@ -220,16 +237,15 @@ const importLocalStorageToNative = async (chatKey: string) => {)) {const attachments = await deserializeAttachmentsStrict(message.attachments,- chatKey,+ sourceKey,);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),+ text: await decryptMessageTextStrict(message, sourceKey),createdAt: message.createdAt,attachments: attachments.map(({ id, kind, name, size }) => ({id,@@ -245,41 +261,26 @@ const importLocalStorageToNative = async (chatKey: string) => {}};-const verifyNativeAttachments = async (chatKey: string) => {- const sessions = await invokeChat<{ sessionUuid: string }[]>(- "chat_db_list_sessions",- { keyB64: chatKey },+const distinctKeys = (keys: (string | undefined)[]) =>+ keys.filter(+ (key, index, values): key is string =>+ !!key && values.indexOf(key) === index,);- 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 },- });+ const migrationPending = !isLocalChatMigrationDone();+ const sourceKeys = distinctKeys([+ chatKey,+ ...(migrationPending ? localChatMigrationSourceKeys() : []),+ ]);+ await invokeChat("chat_db_open", {+ input: { keyB64: chatKey, recoveryKeysB64: sourceKeys },+ });+ if (migrationPending) {if (hasLocalStorageStore()) {- await importLocalStorageToNative(chatKey);+ await importLocalStorageToNative(sourceKeys);}- await verifyNativeAttachments(chatKey);await finalizeLocalChatMigration();}} else {@@ -287,7 +288,7 @@ const migrate = async (chatKey: string) => {await importOldBrowserStores();}try {- await pruneOrphanedAttachmentBytes(chatKey);+ await pruneOrphanedAttachmentBytes();} catch (error) {log.warn("Failed to prune orphaned attachment payloads", error);}diff --git a/web/apps/ensu/src/services/chat/store.ts b/web/apps/ensu/src/services/chat/store.tsindex 788933017e..099c25e2fd 100644--- a/web/apps/ensu/src/services/chat/store.ts+++ b/web/apps/ensu/src/services/chat/store.ts@@ -367,17 +367,16 @@ export const deserializeAttachmentsStrict = async (})),);-export const pruneOrphanedAttachmentBytes = async (chatKey: string) => {+export const pruneOrphanedAttachmentBytes = async () => {if (isTauriRuntime()) {const sessions = await invokeChat<NativeSession[]>("chat_db_list_sessions",- { keyB64: chatKey },);const referenced = new Set<string>();for (const session of sessions) {const messages = await invokeChat<NativeMessage[]>("chat_db_get_messages",- { keyB64: chatKey, sessionUuid: session.sessionUuid },+ { sessionUuid: session.sessionUuid },);for (const attachment of messages.flatMap(({ attachments }) => attachments ?? [],@@ -436,10 +435,9 @@ export const invokeChat = async <T>(return invoke<T>(command, args);};-const listSessionsNative = async (chatKey: string): Promise<ChatSession[]> => {+const listSessionsNative = async (): Promise<ChatSession[]> => {const sessions = await invokeChat<NativeSession[]>("chat_db_list_sessions_with_preview",- { keyB64: chatKey },);return sessions.map((session) => ({@@ -455,10 +453,8 @@ const listSessionsNative = async (chatKey: string): Promise<ChatSession[]> => {const listMessagesNative = async (sessionUuid: string,- chatKey: string,): Promise<ChatMessage[]> => {const messages = await invokeChat<NativeMessage[]>("chat_db_get_messages", {- keyB64: chatKey,sessionUuid,});@@ -478,36 +474,25 @@ const listMessagesNative = async (}));};-const createSessionNative = async (chatKey: string) => {+const createSessionNative = async () => {const session = await invokeChat<NativeSession>("chat_db_create_session", {- keyB64: chatKey,title: "New chat",});return session.sessionUuid;};-const updateSessionTitleNative = async (- chatKey: string,- sessionUuid: string,- title: string,-) => {- await invokeChat("chat_db_update_session_title", {- keyB64: chatKey,- sessionUuid,- title,- });+const updateSessionTitleNative = async (sessionUuid: string, title: string) => {+ await invokeChat("chat_db_update_session_title", { sessionUuid, title });};const addMessageNative = async (sessionUuid: string,sender: "self" | "assistant",text: string,- chatKey: string,parentMessageUuid?: string,attachments: ChatAttachment[] = [],): Promise<ChatMessage> => {const message = await invokeChat<NativeMessage>("chat_db_insert_message", {- keyB64: chatKey,input: {sessionUuid,sender,@@ -526,14 +511,14 @@ const addMessageNative = async (try {const session = await invokeChat<NativeSession | null>("chat_db_get_session",- { keyB64: chatKey, sessionUuid },+ { sessionUuid },);if (session &&safeTitle(session.title).toLowerCase() === "new chat") {const title = sessionTitleFromText(text, "New chat");- await updateSessionTitleNative(chatKey, sessionUuid, title);+ await updateSessionTitleNative(sessionUuid, title);}} catch (error) {log.error("Failed to update native session title", error);@@ -556,21 +541,12 @@ const addMessageNative = async (};};-const updateMessageNative = async (- messageUuid: string,- text: string,- chatKey: string,-) => {- await invokeChat("chat_db_update_message_text", {- keyB64: chatKey,- messageUuid,- text,- });+const updateMessageNative = async (messageUuid: string, text: string) => {+ await invokeChat("chat_db_update_message_text", { messageUuid, text });};-const deleteSessionNative = async (sessionUuid: string, chatKey: string) => {+const deleteSessionNative = async (sessionUuid: string) => {const attachmentIds = await invokeChat<string[]>("chat_db_delete_session", {- keyB64: chatKey,sessionUuid,});for (const id of attachmentIds) {@@ -585,7 +561,7 @@ const deleteSessionNative = async (sessionUuid: string, chatKey: string) => {export const listSessions = async (chatKey: string): Promise<ChatSession[]> => {if (isTauriRuntime()) {try {- return await listSessionsNative(chatKey);+ return await listSessionsNative();} catch (error) {log.error(`Failed to list native sessions: ${formatLogError(error)}`,@@ -643,7 +619,7 @@ export const listMessages = async (): Promise<ChatMessage[]> => {if (isTauriRuntime()) {try {- return await listMessagesNative(sessionUuid, chatKey);+ return await listMessagesNative(sessionUuid);} catch (error) {log.error(`Failed to list native messages: ${formatLogError(error)}`,@@ -680,7 +656,7 @@ export const listMessages = async (export const createSession = async (chatKey: string) => {if (isTauriRuntime()) {- return createSessionNative(chatKey);+ return createSessionNative();}const db = await chatDb();@@ -714,7 +690,6 @@ export const addMessage = async (sessionUuid,sender,text,- chatKey,parentMessageUuid,attachments,);@@ -776,7 +751,7 @@ export const updateSessionTitle = async () => {const safe = sessionTitleFromText(title, "New chat");if (isTauriRuntime()) {- await updateSessionTitleNative(chatKey, sessionUuid, safe);+ await updateSessionTitleNative(sessionUuid, safe);return;}@@ -797,7 +772,7 @@ export const updateMessage = async (chatKey: string,) => {if (isTauriRuntime()) {- await updateMessageNative(messageUuid, text, chatKey);+ await updateMessageNative(messageUuid, text);return;}@@ -853,9 +828,9 @@ export const setBranchSelection = async (export const deleteBranchSelections = (rootSessionUuid: string) =>removeKV(branchSelectionsKey(rootSessionUuid));-export const deleteSession = async (sessionUuid: string, chatKey: string) => {+export const deleteSession = async (sessionUuid: string) => {if (isTauriRuntime()) {- await deleteSessionNative(sessionUuid, chatKey);+ await deleteSessionNative(sessionUuid);await deleteBranchSelections(sessionUuid);return;}@@ -920,8 +895,7 @@ export const writeAttachmentBytes = async () => {if (isTauriRuntime()) {const { writeFile } = await import("@tauri-apps/plugin-fs");- const path = await attachmentPath(id);- await writeFile(path, data);+ await writeFile(await attachmentPath(id), data);return;}