π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Simplify Ensu chat storage
Manav Rathi280a72c7cb1b
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 28ec5ced3f..c08b8dcb91 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@@ -24,7 +24,6 @@ class ChatRepository(private val filePaths = FilePathManager(context)private val attachmentsDir = filePaths.attachmentsDirprivate val dbFile = filePaths.mainDbFile- private val attachmentsDbFile = filePaths.attachmentsDbFileprivate val dbKey = credentialStore.getOrCreateChatDbKey()private var db: EnsuDb = openDb(dbFile, dbKey)@@ -141,13 +140,12 @@ class ChatRepository(private fun openDb(dbFile: File, key: ByteArray): EnsuDb {return EnsuDb.open(dbFile.absolutePath,- attachmentsDbFile.absolutePath,key)}private fun <T> withDbRecovery(block: () -> T): T {- if (!attachmentsDbFile.exists() || !dbFile.exists()) {+ if (!dbFile.exists()) {reopenDb()}return try {@@ -163,9 +161,7 @@ class ChatRepository(private fun reopenDb() {dbFile.parentFile?.mkdirs()- attachmentsDbFile.parentFile?.mkdirs()dbFile.setWritable(true)- attachmentsDbFile.setWritable(true)db = openDb(dbFile, dbKey)}diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/FilePathManager.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/FilePathManager.ktindex 1e4ee1d08c..3334e9e72b 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/FilePathManager.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/FilePathManager.kt@@ -7,7 +7,6 @@ class FilePathManager(context: Context) {private val appDataDir: File = ensureDir(context.filesDir)val attachmentsDir: File = ensureDir(File(appDataDir, "attachments"))val mainDbFile: File = File(appDataDir, "llmchat.db")- val attachmentsDbFile: File = File(appDataDir, "llmchat_sync.db")private fun ensureDir(dir: File): File {if (!dir.exists()) {diff --git a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swiftindex 5a93d8508f..6a1191b975 100644--- a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift+++ b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift@@ -82,7 +82,6 @@ final class ChatViewModel: ObservableObject {private var chatDb: EnsuDbprivate let attachmentsDir: URLprivate let chatDbPath: String- private let attachmentsDbPath: Stringprivate let chatDbKey: Dataprivate let modelSettings = ModelSettingsStore.shared@@ -136,11 +135,10 @@ final class ChatViewModel: ObservableObject {let chatDbKey = CredentialStore.shared.getOrCreateChatDbKey()let chatDbPath = dbDir.appendingPathComponent("llmchat.db").path- let attachmentsDbPath = dbDir.appendingPathComponent("llmchat_sync.db").pathlet chatDb: EnsuDbdo {- chatDb = try EnsuDb.open(mainDbPath: chatDbPath, attachmentsDbPath: attachmentsDbPath, key: chatDbKey)+ chatDb = try EnsuDb.open(mainDbPath: chatDbPath, key: chatDbKey)} catch {fatalError("Failed to open chat DB: \(error)")}@@ -155,7 +153,6 @@ final class ChatViewModel: ObservableObject {self.chatDb = chatDbself.attachmentsDir = attachmentsDirself.chatDbPath = chatDbPath- self.attachmentsDbPath = attachmentsDbPathself.chatDbKey = chatDbKeyself.sessionSummaries = summaries@@ -215,9 +212,8 @@ final class ChatViewModel: ObservableObject {"You can view existing chats, but can't send new messages."private func reopenChatStoreIfNeeded(force: Bool = false) {- let hasAttachmentsDb = FileManager.default.fileExists(atPath: attachmentsDbPath)let hasChatDb = FileManager.default.fileExists(atPath: chatDbPath)- if !force && hasAttachmentsDb && hasChatDb {+ if !force && hasChatDb {return}@@ -230,7 +226,6 @@ final class ChatViewModel: ObservableObject {chatDb = try EnsuDb.open(mainDbPath: chatDbPath,- attachmentsDbPath: attachmentsDbPath,key: chatDbKey)} catch {diff --git a/rust/apps/ensu/src-tauri/src/commands/chat_db.rs b/rust/apps/ensu/src-tauri/src/commands/chat_db.rsindex acd3a57d2b..00a27fc167 100644--- a/rust/apps/ensu/src-tauri/src/commands/chat_db.rs+++ b/rust/apps/ensu/src-tauri/src/commands/chat_db.rs@@ -1,10 +1,10 @@-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use std::fs;use std::path::{Path, PathBuf};use std::sync::{Arc, Mutex};use ente_core::crypto;-use ente_ensu::db::{self, Db, Error as DbError, SqliteBackend};+use ente_ensu::db::{self, ChatDb, Error as DbError, SqliteBackend};use serde::{Deserialize, Serialize};use tauri::async_runtime;use tauri::{AppHandle, Manager, State};@@ -20,15 +20,14 @@ pub struct ChatDbState {struct ChatDbHolder {key_b64: String,- db: Arc<Db<SqliteBackend>>,+ db: Arc<ChatDb<SqliteBackend>>,}-const CHAT_DB_FILE_NAME_V2: &str = "ensu_llmchat_v2.db";-const LEGACY_CHAT_DB_FILE_NAME: &str = "ensu_llmchat.db";-const ATTACHMENTS_DB_FILE_NAME_V2: &str = "llmchat_sync_v2.db";-const LEGACY_ATTACHMENTS_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 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")@@ -39,10 +38,10 @@ fn image_thread_error() -> ApiError {}impl From<DbError> for ApiError {- fn from(e: DbError) -> Self {+ fn from(error: DbError) -> Self {use db::Error as E;- let code = match &e {+ let code = match &error {E::InvalidKeyLength { .. } => "db_invalid_key_length",E::InvalidBlobLength { .. } => "db_invalid_blob_length",E::InvalidEncryptedField => "db_invalid_encrypted_field",@@ -61,7 +60,7 @@ impl From<DbError> for ApiError {E::Migration(_) => "db_migration",};- ApiError::new(code, e.to_string())+ ApiError::new(code, error.to_string())}}@@ -72,9 +71,6 @@ pub struct ChatSessionDto {title: String,created_at: i64,updated_at: i64,- remote_id: Option<String>,- needs_sync: bool,- deleted_at: Option<i64>,}impl From<db::Session> for ChatSessionDto {@@ -84,9 +80,6 @@ impl From<db::Session> for ChatSessionDto {title: session.title,created_at: session.created_at,updated_at: session.updated_at,- remote_id: session.remote_id,- needs_sync: session.needs_sync,- deleted_at: session.deleted_at,}}}@@ -98,9 +91,6 @@ pub struct ChatSessionPreviewDto {title: String,created_at: i64,updated_at: i64,- remote_id: Option<String>,- needs_sync: bool,- deleted_at: Option<i64>,last_message_preview: Option<String>,}@@ -111,9 +101,6 @@ impl From<db::SessionWithPreview> for ChatSessionPreviewDto {title: session.title,created_at: session.created_at,updated_at: session.updated_at,- remote_id: session.remote_id,- needs_sync: session.needs_sync,- deleted_at: session.deleted_at,last_message_preview: session.last_message_preview,}}@@ -126,22 +113,19 @@ pub struct ChatAttachmentDto {kind: String,size: i64,name: String,- uploaded_at: Option<i64>,}-impl From<db::Attachment> for ChatAttachmentDto {- fn from(attachment: db::Attachment) -> Self {+impl From<db::AttachmentMeta> for ChatAttachmentDto {+ fn from(attachment: db::AttachmentMeta) -> Self {let kind = match attachment.kind {db::AttachmentKind::Image => "image",db::AttachmentKind::Document => "document",};-Self {id: attachment.id,kind: kind.to_string(),size: attachment.size,name: attachment.name,- uploaded_at: attachment.uploaded_at,}}}@@ -153,26 +137,9 @@ pub struct ChatAttachmentInput {kind: String,size: i64,name: String,- uploaded_at: Option<i64>,-}--#[derive(Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct ChatDbMigrateLegacyInput {- key_b64: String,- legacy_key_b64: String,}-#[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 db::Attachment {+impl TryFrom<ChatAttachmentInput> for db::AttachmentMeta {type Error = ApiError;fn try_from(value: ChatAttachmentInput) -> Result<Self, Self::Error> {@@ -186,13 +153,11 @@ impl TryFrom<ChatAttachmentInput> for db::Attachment {));}};-Ok(Self {id: value.id,kind,size: value.size,name: value.name,- uploaded_at: value.uploaded_at,})}}@@ -207,50 +172,6 @@ pub struct ChatMessageDto {text: String,created_at: i64,attachments: Vec<ChatAttachmentDto>,- deleted_at: Option<i64>,-}--fn build_message_dto(- db: &Db<SqliteBackend>,- message: db::Message,-) -> Result<ChatMessageDto, DbError> {- let uploads = db.get_uploads_for_message(message.uuid)?;- let mut uploads_by_id = HashMap::new();- for upload in uploads {- uploads_by_id.insert(upload.attachment_id, upload.uploaded_at);- }-- let sender = match message.sender {- db::Sender::SelfUser => "self",- db::Sender::Other => "assistant",- };-- let attachments = message- .attachments- .into_iter()- .map(|meta| {- let uploaded_at = uploads_by_id.get(&meta.id).and_then(|value| *value);- db::Attachment {- id: meta.id,- kind: meta.kind,- size: meta.size,- name: meta.name,- uploaded_at,- }- })- .map(ChatAttachmentDto::from)- .collect();-- Ok(ChatMessageDto {- message_uuid: message.uuid.to_string(),- session_uuid: message.session_uuid.to_string(),- parent_message_uuid: message.parent_message_uuid.map(|value| value.to_string()),- sender: sender.to_string(),- text: message.text,- created_at: message.created_at,- attachments,- deleted_at: message.deleted_at,- })}impl From<db::Message> for ChatMessageDto {@@ -259,7 +180,6 @@ impl From<db::Message> for ChatMessageDto {db::Sender::SelfUser => "self",db::Sender::Other => "assistant",};-Self {message_uuid: message.uuid.to_string(),session_uuid: message.session_uuid.to_string(),@@ -270,10 +190,8 @@ impl From<db::Message> for ChatMessageDto {attachments: message.attachments.into_iter()- .map(db::Attachment::from).map(ChatAttachmentDto::from).collect(),- deleted_at: message.deleted_at,}}}@@ -295,9 +213,6 @@ pub struct ChatSessionUpsertInput {title: String,created_at: i64,updated_at: i64,- remote_id: Option<String>,- needs_sync: bool,- deleted_at: Option<i64>,}#[derive(Deserialize)]@@ -309,11 +224,25 @@ pub struct ChatMessageUpsertInput {sender: String,text: String,created_at: i64,- remote_id: Option<String>,- deleted_at: Option<i64>,attachments: Option<Vec<ChatAttachmentInput>>,}+#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ChatDbImportV1Input {+ key_b64: String,+ v1_key_b64: String,+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ChatDbImportV1Result {+ did_migrate: bool,+ migrated_sessions: i64,+ migrated_messages: i64,+ migrated_attachments: i64,+}+#[tauri::command]pub async fn chat_db_list_sessions(state: State<'_, ChatDbState>,@@ -360,23 +289,6 @@ pub async fn chat_db_get_session(.await}-#[tauri::command]-pub async fn chat_db_get_message(- state: State<'_, ChatDbState>,- app: AppHandle,- key_b64: String,- message_uuid: String,-) -> Result<Option<ChatMessageDto>, ApiError> {- let uuid = parse_uuid(&message_uuid)?;- with_chat_db_async(&state, app, key_b64, move |db| {- let message = db.get_message(uuid)?;- message- .map(|message| build_message_dto(db, message))- .transpose()- })- .await-}-#[tauri::command]pub async fn chat_db_create_session(state: State<'_, ChatDbState>,@@ -385,8 +297,7 @@ pub async fn chat_db_create_session(title: String,) -> Result<ChatSessionDto, ApiError> {with_chat_db_async(&state, app, key_b64, move |db| {- let session = db.create_session(&title)?;- Ok(ChatSessionDto::from(session))+ Ok(ChatSessionDto::from(db.create_session(&title)?))}).await}@@ -401,8 +312,7 @@ pub async fn chat_db_update_session_title() -> Result<(), ApiError> {let uuid = parse_uuid(&session_uuid)?;with_chat_db_async(&state, app, key_b64, move |db| {- db.update_session_title(uuid, &title)?;- Ok(())+ db.update_session_title(uuid, &title)}).await}@@ -415,11 +325,7 @@ pub async fn chat_db_delete_session(session_uuid: String,) -> Result<(), ApiError> {let uuid = parse_uuid(&session_uuid)?;- with_chat_db_async(&state, app, key_b64, move |db| {- db.delete_session(uuid)?;- Ok(())- })- .await+ with_chat_db_async(&state, app, key_b64, move |db| db.delete_session(uuid)).await}#[tauri::command]@@ -431,11 +337,11 @@ pub async fn chat_db_get_messages() -> Result<Vec<ChatMessageDto>, ApiError> {let uuid = parse_uuid(&session_uuid)?;with_chat_db_async(&state, app, key_b64, move |db| {- let messages = db.get_messages(uuid)?;- messages+ Ok(db+ .get_messages(uuid)?.into_iter()- .map(|message| build_message_dto(db, message))- .collect()+ .map(ChatMessageDto::from)+ .collect())}).await}@@ -448,25 +354,17 @@ pub async fn chat_db_insert_message(input: ChatMessageInsertInput,) -> Result<ChatMessageDto, ApiError> {let session_uuid = parse_uuid(&input.session_uuid)?;- let parent = input- .parent_message_uuid- .as_deref()- .map(parse_uuid)- .transpose()?;+ let parent = optional_uuid(&input.parent_message_uuid)?;let sender = normalize_sender(&input.sender)?;- let text = input.text;- let attachments = input- .attachments- .unwrap_or_default()- .into_iter()- .map(db::Attachment::try_from)- .collect::<Result<Vec<_>, ApiError>>()?;-+ let attachments = convert_attachments(input.attachments)?;with_chat_db_async(&state, app, key_b64, move |db| {- let attachment_metas: Vec<db::AttachmentMeta> =- attachments.into_iter().map(Into::into).collect();- let message = db.insert_message(session_uuid, sender, &text, parent, attachment_metas)?;- build_message_dto(db, message)+ Ok(ChatMessageDto::from(db.insert_message(+ session_uuid,+ sender,+ &input.text,+ parent,+ attachments,+ )?))}).await}@@ -481,8 +379,7 @@ pub async fn chat_db_update_message_text() -> Result<(), ApiError> {let uuid = parse_uuid(&message_uuid)?;with_chat_db_async(&state, app, key_b64, move |db| {- db.update_message_text(uuid, &text)?;- Ok(())+ db.update_message_text(uuid, &text)}).await}@@ -496,16 +393,12 @@ pub async fn chat_db_upsert_session() -> Result<ChatSessionDto, ApiError> {let uuid = parse_uuid(&input.session_uuid)?;with_chat_db_async(&state, app, key_b64, move |db| {- let session = db.upsert_session(+ Ok(ChatSessionDto::from(db.upsert_session(uuid,&input.title,input.created_at,input.updated_at,- input.remote_id.clone(),- input.needs_sync,- input.deleted_at,- )?;- Ok(ChatSessionDto::from(session))+ )?))}).await}@@ -519,67 +412,56 @@ pub async fn chat_db_insert_message_with_uuid() -> Result<ChatMessageDto, ApiError> {let message_uuid = parse_uuid(&input.message_uuid)?;let session_uuid = parse_uuid(&input.session_uuid)?;- let parent = input- .parent_message_uuid- .as_deref()- .map(parse_uuid)- .transpose()?;+ let parent = optional_uuid(&input.parent_message_uuid)?;let sender = normalize_sender(&input.sender)?;- let attachments = input- .attachments- .unwrap_or_default()- .into_iter()- .map(db::Attachment::try_from)- .collect::<Result<Vec<_>, ApiError>>()?;-+ let attachments = convert_attachments(input.attachments)?;with_chat_db_async(&state, app, key_b64, move |db| {- let attachment_metas = attachments- .iter()- .cloned()- .map(db::AttachmentMeta::from)- .collect::<Vec<_>>();- let message = if let Some(remote_id) = input.remote_id.as_deref() {- let message = db.upsert_message_from_remote(- message_uuid,- session_uuid,- remote_id,- sender,- &input.text,- parent,- attachment_metas,- input.created_at,- )?;- if let Some(deleted_at) = input.deleted_at {- db.apply_message_tombstone(message_uuid, deleted_at)?;- }- message- } else {- db.insert_message_with_uuid(- message_uuid,- session_uuid,- sender,- &input.text,- parent,- attachments,- input.created_at,- input.deleted_at,- )?- };- build_message_dto(db, message)+ Ok(ChatMessageDto::from(db.insert_message_with_uuid(+ message_uuid,+ session_uuid,+ sender,+ &input.text,+ parent,+ attachments,+ input.created_at,+ )?))}).await}#[tauri::command]-pub async fn chat_db_migrate_legacy(+pub async fn chat_db_import_v1(app: AppHandle,- input: ChatDbMigrateLegacyInput,-) -> Result<ChatDbMigrateLegacyResult, ApiError> {- async_runtime::spawn_blocking(move || migrate_legacy_chat_db(&app, &input))+ input: ChatDbImportV1Input,+) -> Result<ChatDbImportV1Result, ApiError> {+ async_runtime::spawn_blocking(move || import_v1_chat_db(&app, &input)).await.map_err(|_| chat_db_thread_error())?}+#[tauri::command]+pub async fn chat_db_compress_attachment_image_file(path: String) -> Result<Vec<u8>, ApiError> {+ async_runtime::spawn_blocking(move || {+ let data = fs::read(&path).map_err(|error| {+ ApiError::new("io", format!("failed to read image file '{path}': {error}"))+ })?;+ ente_ensu::image::compress_attachment_image(&data)+ .map_err(|error| ApiError::new("image", error.to_string()))+ })+ .await+ .map_err(|_| image_thread_error())?+}++fn convert_attachments(+ attachments: Option<Vec<ChatAttachmentInput>>,+) -> Result<Vec<db::AttachmentMeta>, ApiError> {+ attachments+ .unwrap_or_default()+ .into_iter()+ .map(db::AttachmentMeta::try_from)+ .collect()+}+fn normalize_sender(sender: &str) -> Result<&'static str, ApiError> {match sender {"self" => Ok("self"),@@ -592,137 +474,116 @@ fn normalize_sender(sender: &str) -> Result<&'static str, ApiError> {}fn parse_uuid(value: &str) -> Result<Uuid, ApiError> {- Uuid::parse_str(value).map_err(|err| ApiError::new("uuid", err.to_string()))+ Uuid::parse_str(value).map_err(|error| ApiError::new("uuid", error.to_string()))}-#[tauri::command]-pub async fn chat_db_compress_attachment_image_file(path: String) -> Result<Vec<u8>, ApiError> {- async_runtime::spawn_blocking(move || {- let data = fs::read(&path).map_err(|err| {- ApiError::new("io", format!("failed to read image file '{path}': {err}"))- })?;- ente_ensu::image::compress_attachment_image(&data)- .map_err(|err| ApiError::new("image", err.to_string()))- })- .await- .map_err(|_| image_thread_error())?+fn optional_uuid(value: &Option<String>) -> Result<Option<Uuid>, ApiError> {+ value.as_deref().map(parse_uuid).transpose()}fn chat_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {- Ok(app_data_dir(app)?.join(CHAT_DB_FILE_NAME_V2))-}--fn attachments_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {- Ok(app_data_dir(app)?.join(ATTACHMENTS_DB_FILE_NAME_V2))+ Ok(app_data_dir(app)?.join(CHAT_DB_FILE_NAME))}fn attachments_dir_path(app: &AppHandle) -> Result<PathBuf, ApiError> {- 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)+ let path = app_data_dir(app)?.join(ATTACHMENTS_DIR_NAME);+ fs::create_dir_all(&path).map_err(|error| ApiError::new("io", error.to_string()))?;+ Ok(path)}-fn legacy_chat_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {- Ok(app_data_dir(app)?.join(LEGACY_CHAT_DB_FILE_NAME))+fn v1_chat_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {+ Ok(app_data_dir(app)?.join(V1_CHAT_DB_FILE_NAME))}-fn legacy_attachments_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {- Ok(app_data_dir(app)?.join(LEGACY_ATTACHMENTS_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 legacy_attachments_dir_path(app: &AppHandle) -> Result<PathBuf, ApiError> {- Ok(app_data_dir(app)?.join(LEGACY_ATTACHMENTS_DIR_NAME))+fn v1_attachments_dir_path(app: &AppHandle) -> Result<PathBuf, ApiError> {+ Ok(app_data_dir(app)?.join(V1_ATTACHMENTS_DIR_NAME))}-fn cleanup_legacy_chat_artifacts(app: &AppHandle) -> Result<(), ApiError> {- let legacy_db_path = legacy_chat_db_path(app)?;- let legacy_attachments_db_path = legacy_attachments_db_path(app)?;- let legacy_attachments_dir = legacy_attachments_dir_path(app)?;-+fn remove_sqlite_files(path: &Path) -> Result<(), ApiError> {for candidate in [- legacy_db_path.clone(),- PathBuf::from(format!("{}-wal", legacy_db_path.display())),- PathBuf::from(format!("{}-shm", legacy_db_path.display())),- legacy_attachments_db_path.clone(),- PathBuf::from(format!("{}-wal", legacy_attachments_db_path.display())),- PathBuf::from(format!("{}-shm", legacy_attachments_db_path.display())),+ path.to_path_buf(),+ PathBuf::from(format!("{}-wal", path.display())),+ PathBuf::from(format!("{}-shm", path.display())),] {if candidate.exists() {- fs::remove_file(&candidate).map_err(|err| ApiError::new("io", err.to_string()))?;+ fs::remove_file(candidate).map_err(|error| ApiError::new("io", error.to_string()))?;}}+ Ok(())+}- if legacy_attachments_dir.exists() {- fs::remove_dir_all(&legacy_attachments_dir)- .map_err(|err| ApiError::new("io", err.to_string()))?;+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.exists() {+ fs::remove_dir_all(attachments_dir)+ .map_err(|error| ApiError::new("io", error.to_string()))?;}-Ok(())}fn verify_migrated_chat_db(- target_db: &Db<SqliteBackend>,- source_session_ids: &[Uuid],- source_message_ids_by_session: &HashMap<Uuid, Vec<Uuid>>,- target_attachments_dir: &Path,- expected_attachment_ids: &[String],+ target: &ChatDb<SqliteBackend>,+ session_ids: &[Uuid],+ message_ids: &HashMap<Uuid, Vec<Uuid>>,+ attachments_dir: &Path,+ attachment_ids: &[String],) -> Result<(), ApiError> {- let target_session_ids = target_db- .list_all_sessions()+ let target_sessions = target+ .list_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) {+ .collect::<HashSet<_>>();+ for uuid in session_ids {+ if !target_sessions.contains(uuid) {return Err(ApiError::new("db_migration_verification",- format!("Missing migrated session {session_uuid}"),+ format!("Missing migrated 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)+ for (session_uuid, expected) in message_ids {+ let actual = target+ .get_messages(*session_uuid).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) {+ .collect::<HashSet<_>>();+ for uuid in expected {+ if !actual.contains(uuid) {return Err(ApiError::new("db_migration_verification",- format!("Missing migrated message {message_uuid}"),+ format!("Missing migrated message {uuid}"),));}}}- for attachment_id in expected_attachment_ids {- let target_path = target_attachments_dir.join(attachment_id);- if !target_path.exists() {+ for id in attachment_ids {+ if !attachments_dir.join(id).exists() {return Err(ApiError::new("db_migration_verification",- format!("Missing migrated attachment {attachment_id}"),+ format!("Missing migrated attachment {id}"),));}}-Ok(())}-fn migrate_legacy_chat_db(+fn import_v1_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 {+ input: &ChatDbImportV1Input,+) -> Result<ChatDbImportV1Result, ApiError> {+ let v1_db_path = v1_chat_db_path(app)?;+ if !v1_db_path.exists() {+ return Ok(ChatDbImportV1Result {did_migrate: false,migrated_sessions: 0,migrated_messages: 0,@@ -730,145 +591,77 @@ fn migrate_legacy_chat_db(});}- let legacy_attachments_db_path = legacy_attachments_db_path(app)?;- let legacy_attachments_dir = legacy_attachments_dir_path(app)?;- let target_db_path = chat_db_path(app)?;- let target_attachments_db_path = attachments_db_path(app)?;+ let v1_attachments_dir = v1_attachments_dir_path(app)?;let target_attachments_dir = attachments_dir_path(app)?;-- let legacy_key = crypto::decode_b64(&input.legacy_key_b64).map_err(ApiError::from)?;+ let v1_key = crypto::decode_b64(&input.v1_key_b64).map_err(ApiError::from)?;let key = crypto::decode_b64(&input.key_b64).map_err(ApiError::from)?;-- let legacy_db =- Db::open_sqlite_with_defaults(&legacy_db_path, &legacy_attachments_db_path, legacy_key)- .map_err(ApiError::from)?;- let target_db =- Db::open_sqlite_with_defaults(&target_db_path, &target_attachments_db_path, key)- .map_err(ApiError::from)?;-- let mut migrated_sessions = 0_i64;- let mut migrated_messages = 0_i64;- let mut migrated_attachments = 0_i64;- let mut source_session_ids = Vec::new();- let mut source_message_ids_by_session = HashMap::new();- let mut expected_attachment_ids = Vec::new();- let legacy_sessions = legacy_db.list_all_sessions().map_err(ApiError::from)?;-- for session in legacy_sessions {- source_session_ids.push(session.uuid);- target_db+ let v1_db = ChatDb::open_sqlite_with_defaults(&v1_db_path, v1_key).map_err(ApiError::from)?;+ let target =+ ChatDb::open_sqlite_with_defaults(chat_db_path(app)?, key).map_err(ApiError::from)?;++ let mut migrated_sessions = 0;+ let mut migrated_messages = 0;+ let mut migrated_attachments = 0;+ let mut session_ids = Vec::new();+ let mut message_ids = HashMap::new();+ let mut attachment_ids = Vec::new();++ for session in v1_db.list_sessions().map_err(ApiError::from)? {+ session_ids.push(session.uuid);+ target.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)?;migrated_sessions += 1;- for message in legacy_db- .get_messages_for_sync(session.uuid, true)- .map_err(ApiError::from)?- {- source_message_ids_by_session+ for message in v1_db.get_messages(session.uuid).map_err(ApiError::from)? {+ message_ids.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);- 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(+ target+ .insert_message_with_uuid(message.uuid,message.session_uuid,message.sender.as_str(),&message.text,message.parent_message_uuid,- attachments.clone(),+ message.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)?;- }- 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()))?;+ for attachment in message.attachments {+ let source = v1_attachments_dir.join(&attachment.id);+ let destination = target_attachments_dir.join(&attachment.id);+ if source.exists() && !destination.exists() {+ fs::copy(&source, &destination)+ .map_err(|error| ApiError::new("io", error.to_string()))?;migrated_attachments += 1;}- if source_path.exists() {- expected_attachment_ids.push(attachment.id.clone());+ if source.exists() {+ attachment_ids.push(attachment.id);}}-migrated_messages += 1;}}verify_migrated_chat_db(- &target_db,- &source_session_ids,- &source_message_ids_by_session,+ &target,+ &session_ids,+ &message_ids,&target_attachments_dir,- &expected_attachment_ids,+ &attachment_ids,)?;+ drop(v1_db);+ cleanup_v1_chat_artifacts(app)?;- drop(legacy_db);-- cleanup_legacy_chat_artifacts(app)?;-- Ok(ChatDbMigrateLegacyResult {+ Ok(ChatDbImportV1Result {did_migrate: true,migrated_sessions,migrated_messages,@@ -880,16 +673,15 @@ fn with_chat_db<T, F>(inner: &Arc<Mutex<Option<ChatDbHolder>>>,app: &AppHandle,key_b64: &str,- f: F,+ operation: F,) -> Result<T, ApiError>where- F: FnOnce(&Db<SqliteBackend>) -> Result<T, DbError>,+ F: 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)@@ -898,20 +690,11 @@ whereif needs_open {let key = crypto::decode_b64(key_b64).map_err(ApiError::from)?;let path = chat_db_path(app)?;- let attachments_db_path = attachments_db_path(app)?;- logging::log(- "ChatDb",- format!(- "opening chat DB db={} attachments={}",- path.display(),- attachments_db_path.display()- ),- );- let db =- Db::open_sqlite_with_defaults(path, attachments_db_path, key).map_err(|err| {- logging::log("ChatDb", format!("failed to open chat DB error={err}"));- ApiError::from(err)- })?;+ 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),@@ -926,28 +709,28 @@ where.clone()};- f(db.as_ref()).map_err(ApiError::from)+ operation(db.as_ref()).map_err(ApiError::from)}async fn with_chat_db_async<T, F>(state: &ChatDbState,app: AppHandle,key_b64: String,- f: F,+ operation: F,) -> Result<T, ApiError>whereT: Send + 'static,- F: FnOnce(&Db<SqliteBackend>) -> Result<T, DbError> + 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, f))+ async_runtime::spawn_blocking(move || with_chat_db(&inner, &app, &key_b64, operation)).await.map_err(|_| chat_db_thread_error())?}pub(crate) fn clear_for_exit(app: &AppHandle) {- if let Some(chat_db_state) = app.try_state::<ChatDbState>() {- match chat_db_state.inner.lock() {+ if let Some(state) = app.try_state::<ChatDbState>() {+ match state.inner.lock() {Ok(mut guard) => {*guard = None;logging::log("App", "cleared chat DB state");diff --git a/rust/apps/ensu/src-tauri/src/main.rs b/rust/apps/ensu/src-tauri/src/main.rsindex cada2c3f50..d97566c0f6 100644--- a/rust/apps/ensu/src-tauri/src/main.rs+++ b/rust/apps/ensu/src-tauri/src/main.rs@@ -43,7 +43,6 @@ fn main() {commands::chat_db::chat_db_list_sessions,commands::chat_db::chat_db_list_sessions_with_preview,commands::chat_db::chat_db_get_session,- commands::chat_db::chat_db_get_message,commands::chat_db::chat_db_create_session,commands::chat_db::chat_db_update_session_title,commands::chat_db::chat_db_delete_session,@@ -53,7 +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_migrate_legacy,+ commands::chat_db::chat_db_import_v1,commands::llm::llm_init_backend,commands::llm::llm_load_model,commands::llm::llm_create_context,diff --git a/rust/bindings/uniffi/ensu/src/db.rs b/rust/bindings/uniffi/ensu/src/db.rsindex 0de01c5cf5..5a2a63abc2 100644--- a/rust/bindings/uniffi/ensu/src/db.rs+++ b/rust/bindings/uniffi/ensu/src/db.rs@@ -95,9 +95,6 @@ pub struct DbSession {pub title: String,pub created_at_us: i64,pub updated_at_us: i64,- pub remote_id: Option<String>,- pub needs_sync: bool,- pub deleted_at_us: Option<i64>,}#[derive(Debug, Clone, uniffi::Enum)]@@ -178,12 +175,11 @@ pub struct DbMessage {pub text: String,pub attachments: Vec<DbAttachmentMeta>,pub created_at_us: i64,- pub deleted_at_us: Option<i64>,}#[derive(uniffi::Object)]pub struct EnsuDb {- inner: db::Db<db::SqliteBackend>,+ inner: db::ChatDb<db::SqliteBackend>,}fn to_session(session: db::Session) -> DbSession {@@ -192,9 +188,6 @@ fn to_session(session: db::Session) -> DbSession {title: session.title,created_at_us: session.created_at,updated_at_us: session.updated_at,- remote_id: session.remote_id,- needs_sync: session.needs_sync,- deleted_at_us: session.deleted_at,}}@@ -210,19 +203,14 @@ fn to_message(message: db::Message) -> DbMessage {text: message.text,attachments: message.attachments.into_iter().map(Into::into).collect(),created_at_us: message.created_at,- deleted_at_us: message.deleted_at,}}#[uniffi::export]impl EnsuDb {#[uniffi::constructor]- pub fn open(- main_db_path: String,- attachments_db_path: String,- key: Vec<u8>,- ) -> Result<Self, DbError> {- let inner = db::Db::open_sqlite_with_defaults(main_db_path, attachments_db_path, key)?;+ pub fn open(main_db_path: String, key: Vec<u8>) -> Result<Self, DbError> {+ let inner = db::ChatDb::open_sqlite_with_defaults(main_db_path, key)?;Ok(Self { inner })}diff --git a/rust/crates/ensu/src/db/attachments/migrations.rs b/rust/crates/ensu/src/db/attachments/migrations.rsdeleted file mode 100644index dc7f2f247f..0000000000--- a/rust/crates/ensu/src/db/attachments/migrations.rs+++ /dev/null@@ -1,72 +0,0 @@-use crate::db::backend::RowExt;-use crate::db::{Backend, Error, Result};--use super::schema;--pub const LATEST_VERSION: i64 = 2;--pub fn migrate<B: Backend>(backend: &B) -> Result<()> {- let version = user_version(backend)?;- match version {- 0 => {- backend.execute_batch(schema::CREATE_ALL)?;- backend.execute("PRAGMA user_version = 2;", &[])?;- Ok(())- }- 1 => {- backend.execute("ALTER TABLE attachments ADD COLUMN remote_id TEXT;", &[])?;- backend.execute("PRAGMA user_version = 2;", &[])?;- Ok(())- }- LATEST_VERSION => Ok(()),- other => Err(Error::Migration(format!(- "unsupported attachments schema version {other}"- ))),- }-}--fn user_version<B: Backend>(backend: &B) -> Result<i64> {- let row = backend- .query_row("PRAGMA user_version;", &[])?- .ok_or_else(|| Error::Migration("missing user_version pragma".to_string()))?;- row.get_i64(0)-}--#[cfg(all(test, feature = "sqlite"))]-mod tests {- use super::*;- use crate::db::backend::sqlite::SqliteBackend;- use crate::db::backend::{BackendTx, RowExt, Value};-- #[test]- fn creates_schema_and_indexes() {- let backend = SqliteBackend::open_in_memory().unwrap();- migrate(&backend).unwrap();-- let row = backend- .query_row(- "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",- &[Value::Text("attachments".to_string())],- )- .unwrap();- assert!(row.is_some(), "missing attachments table");-- for index in [- "idx_attachments_session",- "idx_attachments_message",- "idx_attachments_state",- ] {- let row = backend- .query_row(- "SELECT name FROM sqlite_master WHERE type = 'index' AND name = ?",- &[Value::Text(index.to_string())],- )- .unwrap();- assert!(row.is_some(), "missing index {index}");- }-- let row = backend.query_row("PRAGMA user_version;", &[]).unwrap();- let version = row.unwrap().get_i64(0).unwrap();- assert_eq!(version, LATEST_VERSION);- }-}diff --git a/rust/crates/ensu/src/db/attachments/mod.rs b/rust/crates/ensu/src/db/attachments/mod.rsdeleted file mode 100644index 093b5c71ce..0000000000--- a/rust/crates/ensu/src/db/attachments/mod.rs+++ /dev/null@@ -1,380 +0,0 @@-pub mod migrations;-pub mod schema;--use std::sync::Arc;--use uuid::Uuid;--use crate::db::Result;-use crate::db::backend::{Backend, RowExt, Value};-use crate::db::traits::{Clock, SystemClock};--#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum UploadState {- Pending,- Uploading,- Uploaded,- Failed,-}--impl UploadState {- pub fn as_str(&self) -> &'static str {- match self {- UploadState::Pending => "pending",- UploadState::Uploading => "uploading",- UploadState::Uploaded => "uploaded",- UploadState::Failed => "failed",- }- }-}--impl std::str::FromStr for UploadState {- type Err = crate::db::Error;-- fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {- match value {- "pending" => Ok(UploadState::Pending),- "uploading" => Ok(UploadState::Uploading),- "uploaded" => Ok(UploadState::Uploaded),- "failed" => Ok(UploadState::Failed),- _ => Err(crate::db::Error::Row(format!(- "invalid upload_state value {value}"- ))),- }- }-}--#[derive(Debug, Clone, PartialEq, Eq)]-pub struct AttachmentUploadRow {- pub attachment_id: String,- pub session_uuid: Uuid,- pub message_uuid: Uuid,- pub size: i64,- pub remote_id: Option<String>,- pub upload_state: UploadState,- pub uploaded_at: Option<i64>,- pub updated_at: i64,-}--pub struct AttachmentsDb<B: Backend> {- backend: B,- clock: Arc<dyn Clock>,-}--impl<B: Backend> AttachmentsDb<B> {- pub fn new(backend: B, clock: Arc<dyn Clock>) -> Result<Self> {- migrations::migrate(&backend)?;- Ok(Self { backend, clock })- }-- pub fn new_with_defaults(backend: B) -> Result<Self> {- Self::new(backend, Arc::new(SystemClock))- }-- pub fn upsert_pending_attachment(- &self,- attachment_id: &str,- session_uuid: Uuid,- message_uuid: Uuid,- size: i64,- ) -> Result<()> {- let now = self.clock.now_us();- // If row exists, do not overwrite an existing terminal state.- // Only ensure it's present and updated.- self.backend.execute(- "INSERT INTO attachments (attachment_id, session_uuid, message_uuid, size, remote_id, upload_state, uploaded_at, updated_at) \- VALUES (?, ?, ?, ?, NULL, 'pending', NULL, ?) \- ON CONFLICT(attachment_id) DO UPDATE SET \- session_uuid = excluded.session_uuid, \- message_uuid = excluded.message_uuid, \- size = excluded.size, \- remote_id = attachments.remote_id, \- updated_at = excluded.updated_at",- &[- Value::Text(attachment_id.to_string()),- Value::Text(session_uuid.to_string()),- Value::Text(message_uuid.to_string()),- Value::Integer(size),- Value::Integer(now),- ],- )?;- Ok(())- }-- pub fn set_attachment_upload_state(- &self,- attachment_id: &str,- state: UploadState,- ) -> Result<()> {- let now = self.clock.now_us();- self.backend.execute(- "UPDATE attachments SET upload_state = ?, updated_at = ? WHERE attachment_id = ?",- &[- Value::Text(state.as_str().to_string()),- Value::Integer(now),- Value::Text(attachment_id.to_string()),- ],- )?;- Ok(())- }-- pub fn set_attachment_remote_id(- &self,- attachment_id: &str,- remote_id: Option<&str>,- ) -> Result<()> {- let now = self.clock.now_us();- let value = remote_id- .map(|id| Value::Text(id.to_string()))- .unwrap_or(Value::Null);- self.backend.execute(- "UPDATE attachments SET remote_id = ?, updated_at = ? WHERE attachment_id = ?",- &[- value,- Value::Integer(now),- Value::Text(attachment_id.to_string()),- ],- )?;- Ok(())- }-- pub fn get_attachment_remote_id(&self, attachment_id: &str) -> Result<Option<String>> {- let row = self.backend.query_row(- "SELECT remote_id FROM attachments WHERE attachment_id = ?",- &[Value::Text(attachment_id.to_string())],- )?;- match row {- Some(row) => Ok(row.get_optional_string(0)?),- None => Ok(None),- }- }-- pub fn mark_attachment_uploaded(&self, attachment_id: &str) -> Result<()> {- let now = self.clock.now_us();- self.backend.execute(- "UPDATE attachments SET upload_state = 'uploaded', uploaded_at = ?, updated_at = ? WHERE attachment_id = ?",- &[- Value::Integer(now),- Value::Integer(now),- Value::Text(attachment_id.to_string()),- ],- )?;- Ok(())- }-- pub fn reset_all_upload_state(&self) -> Result<()> {- let now = self.clock.now_us();- self.backend.execute(- "UPDATE attachments SET upload_state = 'pending', remote_id = NULL, uploaded_at = NULL, updated_at = ?",- &[Value::Integer(now)],- )?;- Ok(())- }-- pub fn get_upload_state(&self, attachment_id: &str) -> Result<Option<UploadState>> {- let row = self.backend.query_row(- "SELECT upload_state FROM attachments WHERE attachment_id = ?",- &[Value::Text(attachment_id.to_string())],- )?;- match row {- Some(row) => {- let state: UploadState = row.get_string(0)?.parse()?;- Ok(Some(state))- }- None => Ok(None),- }- }-- pub fn upsert_attachment_with_state(- &self,- attachment_id: &str,- session_uuid: Uuid,- message_uuid: Uuid,- size: i64,- remote_id: Option<&str>,- state: UploadState,- ) -> Result<()> {- let now = self.clock.now_us();- let uploaded_at = if state == UploadState::Uploaded {- Value::Integer(now)- } else {- Value::Null- };- let remote_value = remote_id- .map(|value| Value::Text(value.to_string()))- .unwrap_or(Value::Null);- self.backend.execute(- "INSERT INTO attachments (attachment_id, session_uuid, message_uuid, size, remote_id, upload_state, uploaded_at, updated_at) \- VALUES (?, ?, ?, ?, ?, ?, ?, ?) \- ON CONFLICT(attachment_id) DO UPDATE SET \- session_uuid = excluded.session_uuid, \- message_uuid = excluded.message_uuid, \- size = excluded.size, \- remote_id = COALESCE(excluded.remote_id, attachments.remote_id), \- upload_state = excluded.upload_state, \- uploaded_at = excluded.uploaded_at, \- updated_at = excluded.updated_at",- &[- Value::Text(attachment_id.to_string()),- Value::Text(session_uuid.to_string()),- Value::Text(message_uuid.to_string()),- Value::Integer(size),- remote_value,- Value::Text(state.as_str().to_string()),- uploaded_at,- Value::Integer(now),- ],- )?;- Ok(())- }-- pub fn get_pending_uploads_for_session(- &self,- session_uuid: Uuid,- ) -> Result<Vec<AttachmentUploadRow>> {- let rows = self.backend.query(- "SELECT attachment_id, session_uuid, message_uuid, size, remote_id, upload_state, uploaded_at, updated_at \- FROM attachments \- WHERE session_uuid = ? AND upload_state IN ('pending','uploading','failed') \- ORDER BY updated_at ASC",- &[Value::Text(session_uuid.to_string())],- )?;-- rows.iter().map(Self::row_from_row).collect()- }-- pub fn get_uploads_for_message(&self, message_uuid: Uuid) -> Result<Vec<AttachmentUploadRow>> {- let rows = self.backend.query(- "SELECT attachment_id, session_uuid, message_uuid, size, remote_id, upload_state, uploaded_at, updated_at \- FROM attachments \- WHERE message_uuid = ? \- ORDER BY updated_at ASC",- &[Value::Text(message_uuid.to_string())],- )?;-- rows.iter().map(Self::row_from_row).collect()- }-- pub fn get_pending_uploads_for_message(- &self,- message_uuid: Uuid,- ) -> Result<Vec<AttachmentUploadRow>> {- let rows = self.backend.query(- "SELECT attachment_id, session_uuid, message_uuid, size, remote_id, upload_state, uploaded_at, updated_at \- FROM attachments \- WHERE message_uuid = ? AND upload_state IN ('pending','uploading','failed') \- ORDER BY updated_at ASC",- &[Value::Text(message_uuid.to_string())],- )?;-- rows.iter().map(Self::row_from_row).collect()- }-- pub fn delete_attachment_tracking_for_message(&self, message_uuid: Uuid) -> Result<()> {- self.backend.execute(- "DELETE FROM attachments WHERE message_uuid = ?",- &[Value::Text(message_uuid.to_string())],- )?;- Ok(())- }-- pub fn delete_attachment_tracking_for_session(&self, session_uuid: Uuid) -> Result<()> {- self.backend.execute(- "DELETE FROM attachments WHERE session_uuid = ?",- &[Value::Text(session_uuid.to_string())],- )?;- Ok(())- }-- fn row_from_row(row: &crate::db::backend::Row) -> Result<AttachmentUploadRow> {- let attachment_id = row.get_string(0)?;- let session_uuid = Uuid::parse_str(&row.get_string(1)?)?;- let message_uuid = Uuid::parse_str(&row.get_string(2)?)?;- let size = row.get_i64(3)?;- let remote_id = row.get_optional_string(4)?;- let upload_state: UploadState = row.get_string(5)?.parse()?;- let uploaded_at = row.get_optional_i64(6)?;- let updated_at = row.get_i64(7)?;- Ok(AttachmentUploadRow {- attachment_id,- session_uuid,- message_uuid,- size,- remote_id,- upload_state,- uploaded_at,- updated_at,- })- }-}--#[cfg(feature = "sqlite")]-impl AttachmentsDb<crate::db::backend::sqlite::SqliteBackend> {- pub fn open_sqlite(path: impl AsRef<std::path::Path>, clock: Arc<dyn Clock>) -> Result<Self> {- let backend = crate::db::backend::sqlite::SqliteBackend::open(path)?;- Self::new(backend, clock)- }-- pub fn open_sqlite_with_defaults(path: impl AsRef<std::path::Path>) -> Result<Self> {- let backend = crate::db::backend::sqlite::SqliteBackend::open(path)?;- Self::new_with_defaults(backend)- }-- pub fn open_in_memory(clock: Arc<dyn Clock>) -> Result<Self> {- let backend = crate::db::backend::sqlite::SqliteBackend::open_in_memory()?;- Self::new(backend, clock)- }-}--#[cfg(all(test, feature = "sqlite"))]-mod tests {- use std::sync::atomic::{AtomicI64, Ordering};-- use super::*;- use crate::db::backend::sqlite::SqliteBackend;-- #[derive(Debug)]- struct StepClock {- current: AtomicI64,- }-- impl StepClock {- fn new(start: i64) -> Self {- Self {- current: AtomicI64::new(start),- }- }- }-- impl Clock for StepClock {- fn now_us(&self) -> i64 {- self.current.fetch_add(1, Ordering::SeqCst)- }- }-- #[test]- fn pending_and_mark_uploaded() {- let clock = Arc::new(StepClock::new(100));- let backend = SqliteBackend::open_in_memory().unwrap();- let db = AttachmentsDb::new(backend, clock.clone()).unwrap();-- let session = Uuid::from_u128(1);- let message = Uuid::from_u128(2);-- db.upsert_pending_attachment("att-1", session, message, 123)- .unwrap();-- let pending = db.get_pending_uploads_for_session(session).unwrap();- assert_eq!(pending.len(), 1);- assert_eq!(pending[0].upload_state, UploadState::Pending);-- db.set_attachment_upload_state("att-1", UploadState::Uploading)- .unwrap();- let pending = db.get_pending_uploads_for_message(message).unwrap();- assert_eq!(pending[0].upload_state, UploadState::Uploading);-- db.mark_attachment_uploaded("att-1").unwrap();- let pending_after = db.get_pending_uploads_for_session(session).unwrap();- assert!(pending_after.is_empty());- }-}diff --git a/rust/crates/ensu/src/db/attachments/schema.rs b/rust/crates/ensu/src/db/attachments/schema.rsdeleted file mode 100644index aedfa2a6b8..0000000000--- a/rust/crates/ensu/src/db/attachments/schema.rs+++ /dev/null@@ -1,35 +0,0 @@-pub const CREATE_ATTACHMENTS: &str = "-CREATE TABLE IF NOT EXISTS attachments (- attachment_id TEXT PRIMARY KEY NOT NULL,- session_uuid TEXT NOT NULL,- message_uuid TEXT NOT NULL,- size INTEGER NOT NULL,- remote_id TEXT,- upload_state TEXT NOT NULL CHECK(upload_state IN ('pending','uploading','uploaded','failed')),- uploaded_at INTEGER,- updated_at INTEGER NOT NULL-);-";--pub const CREATE_INDEXES: &str = "-CREATE INDEX IF NOT EXISTS idx_attachments_session ON attachments(session_uuid);-CREATE INDEX IF NOT EXISTS idx_attachments_message ON attachments(message_uuid);-CREATE INDEX IF NOT EXISTS idx_attachments_state ON attachments(upload_state);-";--pub const CREATE_ALL: &str = "-CREATE TABLE IF NOT EXISTS attachments (- attachment_id TEXT PRIMARY KEY NOT NULL,- session_uuid TEXT NOT NULL,- message_uuid TEXT NOT NULL,- size INTEGER NOT NULL,- remote_id TEXT,- upload_state TEXT NOT NULL CHECK(upload_state IN ('pending','uploading','uploaded','failed')),- uploaded_at INTEGER,- updated_at INTEGER NOT NULL-);--CREATE INDEX IF NOT EXISTS idx_attachments_session ON attachments(session_uuid);-CREATE INDEX IF NOT EXISTS idx_attachments_message ON attachments(message_uuid);-CREATE INDEX IF NOT EXISTS idx_attachments_state ON attachments(upload_state);-";diff --git a/rust/crates/ensu/src/db/chat/migrations.rs b/rust/crates/ensu/src/db/chat/migrations.rsindex a0c1f8089a..4d465b6f11 100644--- a/rust/crates/ensu/src/db/chat/migrations.rs+++ b/rust/crates/ensu/src/db/chat/migrations.rs@@ -1,56 +1,69 @@-use crate::db::backend::RowExt;+use crate::db::backend::{BackendTx, RowExt};use crate::db::{Backend, Error, Result};use super::schema;-pub const LATEST_VERSION: i64 = 4;+pub const LATEST_VERSION: i64 = 5;pub fn migrate<B: Backend>(backend: &B) -> Result<()> {- let mut version = user_version(backend)?;-- while version < LATEST_VERSION {- match version {- 0 => {- backend.execute_batch(schema::CREATE_ALL)?;- version = LATEST_VERSION;- }- 1 => {- backend.execute(- "ALTER TABLE messages ADD COLUMN needs_sync INTEGER NOT NULL DEFAULT 1 CHECK(needs_sync IN (0,1));",- &[],- )?;- backend.execute(- "UPDATE messages SET needs_sync = 0 WHERE session_uuid IN (SELECT session_uuid FROM sessions WHERE needs_sync = 0);",- &[],- )?;- version = 2;- }- 2 => {- backend.execute(- "ALTER TABLE sessions ADD COLUMN server_updated_at INTEGER;",- &[],- )?;- backend.execute(- "ALTER TABLE messages ADD COLUMN server_updated_at INTEGER;",- &[],- )?;- version = 3;- }- 3 => {- backend.execute("ALTER TABLE messages ADD COLUMN remote_id TEXT;", &[])?;- version = 4;- }- other => {- return Err(Error::Migration(format!(- "unsupported schema version {other}"- )));- }+ match user_version(backend)? {+ 0 => {+ backend.execute_batch(schema::CREATE_ALL)?;+ backend.execute(&format!("PRAGMA user_version = {LATEST_VERSION};"), &[])?;+ Ok(())}-- backend.execute(&format!("PRAGMA user_version = {version};"), &[])?;+ 1..=4 => migrate_to_local_schema(backend),+ LATEST_VERSION => Ok(()),+ other => Err(Error::Migration(format!(+ "unsupported schema version {other}"+ ))),}+}- Ok(())+fn migrate_to_local_schema<B: Backend>(backend: &B) -> Result<()> {+ backend.execute_batch("PRAGMA foreign_keys = OFF;")?;+ let result = backend.transaction(|tx| {+ tx.execute_batch(+ "CREATE TABLE sessions_v5 (+ session_uuid TEXT PRIMARY KEY NOT NULL,+ title BLOB NOT NULL,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE TABLE messages_v5 (+ message_uuid TEXT PRIMARY KEY NOT NULL,+ session_uuid TEXT NOT NULL,+ parent_message_uuid TEXT,+ sender TEXT NOT NULL CHECK(sender IN ('self','other')),+ text BLOB NOT NULL,+ attachments TEXT,+ created_at INTEGER NOT NULL,+ FOREIGN KEY (session_uuid) REFERENCES sessions(session_uuid) ON DELETE CASCADE+ );+ INSERT INTO sessions_v5 (session_uuid, title, created_at, updated_at)+ SELECT session_uuid, title, created_at, updated_at+ FROM sessions+ WHERE deleted_at IS NULL;+ INSERT INTO messages_v5 (+ message_uuid, session_uuid, parent_message_uuid, sender, text, attachments, created_at+ )+ SELECT m.message_uuid, m.session_uuid, m.parent_message_uuid, m.sender,+ m.text, m.attachments, m.created_at+ FROM messages m+ JOIN sessions s ON s.session_uuid = m.session_uuid+ WHERE m.deleted_at IS NULL AND s.deleted_at IS NULL;+ DROP TABLE messages;+ DROP TABLE sessions;+ ALTER TABLE sessions_v5 RENAME TO sessions;+ ALTER TABLE messages_v5 RENAME TO messages;",+ )?;+ tx.execute_batch(schema::CREATE_INDEXES)?;+ tx.execute(&format!("PRAGMA user_version = {LATEST_VERSION};"), &[])?;+ Ok(())+ });+ let enable_result = backend.execute_batch("PRAGMA foreign_keys = ON;");+ result?;+ enable_result}fn user_version<B: Backend>(backend: &B) -> Result<i64> {@@ -95,4 +108,117 @@ mod tests {let version = row.unwrap().get_i64(0).unwrap();assert_eq!(version, LATEST_VERSION);}++ #[test]+ fn v1_migrates_directly_to_local_schema() {+ let backend = SqliteBackend::open_in_memory().unwrap();+ backend+ .execute_batch(+ "CREATE TABLE sessions (+ session_uuid TEXT PRIMARY KEY NOT NULL,+ title BLOB NOT NULL,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ remote_id TEXT UNIQUE,+ needs_sync INTEGER NOT NULL DEFAULT 1,+ deleted_at INTEGER+ );+ CREATE TABLE messages (+ message_uuid TEXT PRIMARY KEY NOT NULL,+ session_uuid TEXT NOT NULL,+ parent_message_uuid TEXT,+ sender TEXT NOT NULL,+ text BLOB NOT NULL,+ attachments TEXT,+ created_at INTEGER NOT NULL,+ deleted_at INTEGER+ );+ INSERT INTO sessions VALUES ('session', X'01', 1, 2, NULL, 1, NULL);+ INSERT INTO messages VALUES ('message', 'session', NULL, 'self', X'02', NULL, 3, NULL);+ PRAGMA user_version = 1;",+ )+ .unwrap();++ migrate(&backend).unwrap();++ assert!(+ backend+ .query_row("SELECT session_uuid FROM sessions", &[])+ .unwrap()+ .is_some()+ );+ assert!(+ backend+ .query_row("SELECT message_uuid FROM messages", &[])+ .unwrap()+ .is_some()+ );+ }++ #[test]+ fn v4_migration_keeps_only_visible_local_data() {+ let backend = SqliteBackend::open_in_memory().unwrap();+ backend.execute_batch(+ "CREATE TABLE sessions (+ session_uuid TEXT PRIMARY KEY NOT NULL,+ title BLOB NOT NULL,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ server_updated_at INTEGER,+ remote_id TEXT UNIQUE,+ needs_sync INTEGER NOT NULL DEFAULT 1,+ deleted_at INTEGER+ );+ CREATE TABLE messages (+ message_uuid TEXT PRIMARY KEY NOT NULL,+ session_uuid TEXT NOT NULL,+ parent_message_uuid TEXT,+ sender TEXT NOT NULL,+ text BLOB NOT NULL,+ attachments TEXT,+ created_at INTEGER NOT NULL,+ remote_id TEXT,+ server_updated_at INTEGER,+ needs_sync INTEGER NOT NULL DEFAULT 1,+ deleted_at INTEGER+ );+ INSERT INTO sessions VALUES ('active', X'01', 1, 2, 3, 'remote-1', 0, NULL);+ INSERT INTO sessions VALUES ('deleted', X'02', 1, 2, NULL, NULL, 1, 4);+ INSERT INTO messages VALUES ('visible', 'active', NULL, 'self', X'03', NULL, 5, NULL, NULL, 1, NULL);+ INSERT INTO messages VALUES ('deleted-message', 'active', NULL, 'other', X'04', NULL, 6, NULL, NULL, 1, 7);+ INSERT INTO messages VALUES ('deleted-session-message', 'deleted', NULL, 'other', X'05', NULL, 8, NULL, NULL, 1, NULL);+ PRAGMA user_version = 4;",+ ).unwrap();++ migrate(&backend).unwrap();++ let sessions = backend+ .query("SELECT session_uuid FROM sessions", &[])+ .unwrap();+ assert_eq!(sessions, vec![vec![Value::Text("active".to_string())]]);+ let messages = backend+ .query("SELECT message_uuid FROM messages", &[])+ .unwrap();+ assert_eq!(messages, vec![vec![Value::Text("visible".to_string())]]);+ assert!(+ backend+ .query_row("SELECT remote_id FROM sessions", &[])+ .is_err()+ );+ assert!(+ backend+ .query("PRAGMA foreign_key_check", &[])+ .unwrap()+ .is_empty()+ );+ backend+ .execute("DELETE FROM sessions WHERE session_uuid = 'active'", &[])+ .unwrap();+ assert!(+ backend+ .query("SELECT * FROM messages", &[])+ .unwrap()+ .is_empty()+ );+ }}diff --git a/rust/crates/ensu/src/db/chat/mod.rs b/rust/crates/ensu/src/db/chat/mod.rsindex b5c7c372e8..ca61ee7f94 100644--- a/rust/crates/ensu/src/db/chat/mod.rs+++ b/rust/crates/ensu/src/db/chat/mod.rs@@ -14,14 +14,6 @@ use crate::db::models::{use crate::db::traits::{Clock, RandomUuidGen, SystemClock, UuidGen};use crate::db::{Error, Result};-const SESSION_NEEDS_SYNC_PREDICATE: &str = "deleted_at IS NULL \- AND (needs_sync = 1 OR EXISTS (\- SELECT 1 FROM messages \- WHERE messages.session_uuid = sessions.session_uuid \- AND messages.needs_sync = 1 \- AND messages.deleted_at IS NULL\- ))";-pub struct ChatDb<B: Backend> {backend: B,key: Zeroizing<Vec<u8>>,@@ -52,99 +44,66 @@ impl<B: Backend> ChatDb<B> {pub fn create_session(&self, title: &str) -> Result<Session> {let now = self.clock.now_us();- let session_uuid = self.uuid_gen.new_uuid();- let encrypted_title = crypto::encrypt_string(title, &self.key)?;-+ let uuid = self.uuid_gen.new_uuid();let affected = self.backend.execute(- "INSERT INTO sessions (session_uuid, title, created_at, updated_at, remote_id, needs_sync, deleted_at) \- VALUES (?, ?, ?, ?, NULL, 1, NULL)",+ "INSERT INTO sessions (session_uuid, title, created_at, updated_at) VALUES (?, ?, ?, ?)",&[- Value::Text(session_uuid.to_string()),- Value::Blob(encrypted_title),+ Value::Text(uuid.to_string()),+ Value::Blob(crypto::encrypt_string(title, &self.key)?),Value::Integer(now),Value::Integer(now),],)?;-- if affected != 1 {- return Err(Error::NotFound {- entity: EntityType::Session,- id: session_uuid,- });- }-+ ensure_row_updated(affected, EntityType::Session, uuid)?;Ok(Session {- uuid: session_uuid,+ uuid,title: title.to_string(),created_at: now,updated_at: now,- server_updated_at: None,- remote_id: None,- needs_sync: true,- deleted_at: None,})}pub fn get_session(&self, uuid: Uuid) -> Result<Option<Session>> {let row = self.backend.query_row(- "SELECT session_uuid, title, created_at, updated_at, server_updated_at, remote_id, needs_sync, deleted_at \- FROM sessions WHERE session_uuid = ? AND deleted_at IS NULL",+ "SELECT session_uuid, title, created_at, updated_at FROM sessions WHERE session_uuid = ?",&[Value::Text(uuid.to_string())],)?;-row.map(|row| self.session_from_row(&row)).transpose()}pub fn list_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 WHERE deleted_at IS NULL ORDER BY updated_at DESC",- &[],- )?;- 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",+ "SELECT session_uuid, title, created_at, updated_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());-- for session in sessions {- let messages = self.get_messages(session.uuid)?;- let last_message_preview = messages.last().map(|message| message.text.clone());- with_preview.push(SessionWithPreview {- uuid: session.uuid,- title: session.title,- created_at: session.created_at,- updated_at: session.updated_at,- server_updated_at: session.server_updated_at,- remote_id: session.remote_id,- needs_sync: session.needs_sync,- deleted_at: session.deleted_at,- last_message_preview,- });- }-- Ok(with_preview)+ self.list_sessions()?+ .into_iter()+ .map(|session| {+ let last_message_preview = self+ .get_messages(session.uuid)?+ .last()+ .map(|message| message.text.clone());+ Ok(SessionWithPreview {+ uuid: session.uuid,+ title: session.title,+ created_at: session.created_at,+ updated_at: session.updated_at,+ last_message_preview,+ })+ })+ .collect()}pub fn update_session_title(&self, uuid: Uuid, title: &str) -> Result<()> {- let now = self.clock.now_us();- let encrypted_title = crypto::encrypt_string(title, &self.key)?;let affected = self.backend.execute(- "UPDATE sessions SET title = ?, updated_at = ?, needs_sync = 1, server_updated_at = NULL \- WHERE session_uuid = ? AND deleted_at IS NULL",+ "UPDATE sessions SET title = ?, updated_at = ? WHERE session_uuid = ?",&[- Value::Blob(encrypted_title),- Value::Integer(now),+ Value::Blob(crypto::encrypt_string(title, &self.key)?),+ Value::Integer(self.clock.now_us()),Value::Text(uuid.to_string()),],)?;@@ -152,104 +111,41 @@ impl<B: Backend> ChatDb<B> {}pub fn delete_session(&self, uuid: Uuid) -> Result<()> {- let now = self.clock.now_us();- self.backend.transaction(|tx| {- tx.execute(- "UPDATE messages SET deleted_at = ?, server_updated_at = NULL WHERE session_uuid = ? AND deleted_at IS NULL",- &[Value::Integer(now), Value::Text(uuid.to_string())],- )?;- let affected = tx.execute(- "UPDATE sessions SET deleted_at = ?, server_updated_at = NULL WHERE session_uuid = ? AND deleted_at IS NULL",- &[Value::Integer(now), Value::Text(uuid.to_string())],- )?;- ensure_row_updated(affected, EntityType::Session, uuid)- })+ let affected = self.backend.execute(+ "DELETE FROM sessions WHERE session_uuid = ?",+ &[Value::Text(uuid.to_string())],+ )?;+ ensure_row_updated(affected, EntityType::Session, uuid)}- #[allow(clippy::too_many_arguments)]pub fn upsert_session(&self,- session_uuid: Uuid,+ uuid: Uuid,title: &str,created_at: i64,updated_at: i64,- remote_id: Option<String>,- needs_sync: bool,- deleted_at: Option<i64>,) -> Result<Session> {- let encrypted_title = crypto::encrypt_string(title, &self.key)?;- let needs_sync_value = if needs_sync { 1 } else { 0 };- let remote_value = remote_id.map(Value::Text).unwrap_or(Value::Null);- let deleted_value = deleted_at.map(Value::Integer).unwrap_or(Value::Null);-self.backend.execute(- "INSERT INTO sessions (session_uuid, title, created_at, updated_at, remote_id, needs_sync, deleted_at) \- VALUES (?, ?, ?, ?, ?, ?, ?) \- ON CONFLICT(session_uuid) DO UPDATE SET \- title = excluded.title, \- created_at = excluded.created_at, \- updated_at = excluded.updated_at, \- remote_id = COALESCE(excluded.remote_id, sessions.remote_id), \- needs_sync = excluded.needs_sync, \- deleted_at = excluded.deleted_at",+ "INSERT INTO sessions (session_uuid, title, created_at, updated_at)+ VALUES (?, ?, ?, ?)+ ON CONFLICT(session_uuid) DO UPDATE SET+ title = CASE+ WHEN excluded.updated_at >= sessions.updated_at THEN excluded.title+ ELSE sessions.title+ END,+ created_at = MIN(sessions.created_at, excluded.created_at),+ updated_at = MAX(sessions.updated_at, excluded.updated_at)",&[- Value::Text(session_uuid.to_string()),- Value::Blob(encrypted_title),+ Value::Text(uuid.to_string()),+ Value::Blob(crypto::encrypt_string(title, &self.key)?),Value::Integer(created_at),Value::Integer(updated_at),- remote_value,- Value::Integer(needs_sync_value),- deleted_value,],)?;-- let row = self.backend.query_row(- "SELECT session_uuid, title, created_at, updated_at, server_updated_at, remote_id, needs_sync, deleted_at \- FROM sessions WHERE session_uuid = ?",- &[Value::Text(session_uuid.to_string())],- )?;- let row = row.ok_or(Error::NotFound {+ self.get_session(uuid)?.ok_or(Error::NotFound {entity: EntityType::Session,- id: session_uuid,- })?;- self.session_from_row(&row)- }-- pub fn get_sessions_needing_sync(&self) -> Result<Vec<Session>> {- let query = format!(- "SELECT session_uuid, title, created_at, updated_at, server_updated_at, remote_id, needs_sync, deleted_at \- FROM sessions \- WHERE {SESSION_NEEDS_SYNC_PREDICATE} \- ORDER BY updated_at DESC"- );- let rows = self.backend.query(&query, &[])?;- rows.iter().map(|row| self.session_from_row(row)).collect()- }-- pub fn count_needing_sync(&self) -> Result<i64> {- let query = format!("SELECT COUNT(*) FROM sessions WHERE {SESSION_NEEDS_SYNC_PREDICATE}");- let row = self.backend.query_row(&query, &[])?;- Ok(row.map(|row| row.get_i64(0)).transpose()?.unwrap_or(0))- }-- pub fn get_sessions_needing_sync_batch(- &self,- limit: i64,- order_desc: bool,- ) -> Result<Vec<Session>> {- if limit <= 0 {- return Ok(Vec::new());- }- let order_clause = if order_desc { "DESC" } else { "ASC" };- let query = format!(- "SELECT session_uuid, title, created_at, updated_at, server_updated_at, remote_id, needs_sync, deleted_at \- FROM sessions \- WHERE {SESSION_NEEDS_SYNC_PREDICATE} \- ORDER BY updated_at {order_clause} \- LIMIT ?"- );- let rows = self.backend.query(&query, &[Value::Integer(limit)])?;- rows.iter().map(|row| self.session_from_row(row)).collect()+ id: uuid,+ })}pub fn insert_message(@@ -261,621 +157,156 @@ impl<B: Backend> ChatDb<B> {attachments: Vec<AttachmentMeta>,) -> Result<Message> {let sender: Sender = sender.parse()?;- let now = self.clock.now_us();- let message_uuid = self.uuid_gen.new_uuid();+ let created_at = self.clock.now_us();+ let uuid = self.uuid_gen.new_uuid();let encrypted_text = crypto::encrypt_string(text, &self.key)?;let attachments_json = self.serialize_attachments(&attachments)?;self.backend.transaction(|tx| {tx.execute(- "INSERT INTO messages (message_uuid, session_uuid, parent_message_uuid, sender, text, attachments, created_at, needs_sync, deleted_at) \- VALUES (?, ?, ?, ?, ?, ?, ?, 1, NULL)",+ "INSERT INTO messages (+ message_uuid, session_uuid, parent_message_uuid, sender,+ text, attachments, created_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?)",&[- Value::Text(message_uuid.to_string()),+ Value::Text(uuid.to_string()),Value::Text(session_uuid.to_string()),- parent- .map(|value| Value::Text(value.to_string()))- .unwrap_or(Value::Null),+ optional_uuid(parent),Value::Text(sender.as_str().to_string()),Value::Blob(encrypted_text),- attachments_json- .map(Value::Text)- .unwrap_or(Value::Null),- Value::Integer(now),+ attachments_json.map(Value::Text).unwrap_or(Value::Null),+ Value::Integer(created_at),],)?;-- self.touch_session(tx, session_uuid, now)?;- Ok(())+ self.touch_session(tx, session_uuid, created_at)})?;Ok(Message {- uuid: message_uuid,+ uuid,session_uuid,parent_message_uuid: parent,sender,text: text.to_string(),attachments,- created_at: now,- remote_id: None,- server_updated_at: None,- needs_sync: true,- deleted_at: None,+ created_at,})}#[allow(clippy::too_many_arguments)]- pub fn insert_message_with_uuid_and_state(+ pub fn insert_message_with_uuid(&self,- message_uuid: Uuid,+ uuid: Uuid,session_uuid: Uuid,sender: &str,text: &str,parent: Option<Uuid>,attachments: Vec<AttachmentMeta>,created_at: i64,- deleted_at: Option<i64>,- needs_sync: bool,) -> Result<Message> {let sender: Sender = sender.parse()?;let encrypted_text = crypto::encrypt_string(text, &self.key)?;let attachments_json = self.serialize_attachments(&attachments)?;- let deleted_value = deleted_at.map(Value::Integer).unwrap_or(Value::Null);- let needs_sync_value = if needs_sync { 1 } else { 0 };- self.backend.execute(- "INSERT INTO messages (message_uuid, session_uuid, parent_message_uuid, sender, text, attachments, created_at, remote_id, server_updated_at, needs_sync, deleted_at) \- VALUES (?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?) \- ON CONFLICT(message_uuid) DO NOTHING",- &[- Value::Text(message_uuid.to_string()),- Value::Text(session_uuid.to_string()),- parent- .map(|value| Value::Text(value.to_string()))- .unwrap_or(Value::Null),- Value::Text(sender.as_str().to_string()),- Value::Blob(encrypted_text),- attachments_json- .map(Value::Text)- .unwrap_or(Value::Null),- Value::Integer(created_at),- Value::Integer(needs_sync_value),- deleted_value,- ],- )?;-- let _ = self.touch_session_remote(session_uuid, created_at);+ self.backend.transaction(|tx| {+ let inserted = tx.execute(+ "INSERT INTO messages (+ message_uuid, session_uuid, parent_message_uuid, sender,+ text, attachments, created_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(message_uuid) DO NOTHING",+ &[+ Value::Text(uuid.to_string()),+ Value::Text(session_uuid.to_string()),+ optional_uuid(parent),+ Value::Text(sender.as_str().to_string()),+ Value::Blob(encrypted_text),+ attachments_json.map(Value::Text).unwrap_or(Value::Null),+ Value::Integer(created_at),+ ],+ )?;+ if inserted == 1 {+ self.touch_session_at_least(tx, session_uuid, created_at)?;+ }+ Ok(())+ })?;- self.get_message(message_uuid)?.ok_or(Error::NotFound {+ self.get_message(uuid)?.ok_or(Error::NotFound {entity: EntityType::Message,- id: message_uuid,+ id: uuid,})}- #[allow(clippy::too_many_arguments)]- pub fn insert_message_with_uuid(- &self,- message_uuid: Uuid,- session_uuid: Uuid,- sender: &str,- text: &str,- parent: Option<Uuid>,- attachments: Vec<AttachmentMeta>,- created_at: i64,- deleted_at: Option<i64>,- ) -> Result<Message> {- self.insert_message_with_uuid_and_state(- message_uuid,- session_uuid,- sender,- text,- parent,- attachments,- created_at,- deleted_at,- false,- )- }-pub fn get_message(&self, uuid: Uuid) -> Result<Option<Message>> {let row = self.backend.query_row(- "SELECT message_uuid, session_uuid, parent_message_uuid, sender, text, attachments, created_at, remote_id, server_updated_at, needs_sync, deleted_at \+ "SELECT message_uuid, session_uuid, parent_message_uuid, sender,+ text, attachments, created_atFROM messages WHERE message_uuid = ?",&[Value::Text(uuid.to_string())],)?;-row.map(|row| self.message_from_row(&row)).transpose()}- pub fn get_messages_for_sync(- &self,- session_uuid: Uuid,- include_deleted: bool,- ) -> Result<Vec<Message>> {- if !include_deleted {- return self.get_messages_needing_sync(session_uuid);- }-- let rows = self.backend.query(- "SELECT message_uuid, session_uuid, parent_message_uuid, sender, text, attachments, created_at, remote_id, server_updated_at, needs_sync, deleted_at \- FROM messages WHERE session_uuid = ? ORDER BY created_at ASC, message_uuid ASC",- &[Value::Text(session_uuid.to_string())],- )?;- rows.iter().map(|row| self.message_from_row(row)).collect()- }-pub fn get_messages(&self, session_uuid: Uuid) -> Result<Vec<Message>> {let rows = self.backend.query(- "SELECT message_uuid, session_uuid, parent_message_uuid, sender, text, attachments, created_at, remote_id, server_updated_at, needs_sync, deleted_at \- FROM messages WHERE session_uuid = ? AND deleted_at IS NULL ORDER BY created_at ASC, message_uuid ASC",- &[Value::Text(session_uuid.to_string())],- )?;- rows.iter().map(|row| self.message_from_row(row)).collect()- }-- pub fn get_messages_needing_sync(&self, session_uuid: Uuid) -> Result<Vec<Message>> {- let rows = self.backend.query(- "SELECT message_uuid, session_uuid, parent_message_uuid, sender, text, attachments, created_at, remote_id, server_updated_at, needs_sync, deleted_at \- FROM messages WHERE session_uuid = ? AND needs_sync = 1 AND deleted_at IS NULL ORDER BY created_at ASC, message_uuid ASC",+ "SELECT message_uuid, session_uuid, parent_message_uuid, sender,+ text, attachments, created_at+ FROM messages+ WHERE session_uuid = ?+ ORDER BY created_at ASC, message_uuid ASC",&[Value::Text(session_uuid.to_string())],)?;rows.iter().map(|row| self.message_from_row(row)).collect()}pub fn update_message_text(&self, uuid: Uuid, text: &str) -> Result<()> {- let now = self.clock.now_us();+ let updated_at = self.clock.now_us();let encrypted_text = crypto::encrypt_string(text, &self.key)?;self.backend.transaction(|tx| {- let row = tx.query_row(- "SELECT session_uuid FROM messages WHERE message_uuid = ? AND deleted_at IS NULL",- &[Value::Text(uuid.to_string())],- )?;- let row = row.ok_or(Error::NotFound {- entity: EntityType::Message,- id: uuid,- })?;- let session_uuid = Uuid::parse_str(&row.get_string(0)?)?;-+ let session_uuid = message_session_uuid(tx, uuid)?;let affected = tx.execute(- "UPDATE messages SET text = ?, needs_sync = 1, server_updated_at = NULL WHERE message_uuid = ? AND deleted_at IS NULL",+ "UPDATE messages SET text = ? WHERE message_uuid = ?",&[Value::Blob(encrypted_text), Value::Text(uuid.to_string())],)?;ensure_row_updated(affected, EntityType::Message, uuid)?;-- self.touch_session(tx, session_uuid, now)+ self.touch_session(tx, session_uuid, updated_at)})}pub fn delete_message(&self, uuid: Uuid) -> Result<()> {- let now = self.clock.now_us();+ let updated_at = self.clock.now_us();self.backend.transaction(|tx| {- let row = tx.query_row(- "SELECT session_uuid FROM messages WHERE message_uuid = ? AND deleted_at IS NULL",- &[Value::Text(uuid.to_string())],- )?;- let row = row.ok_or(Error::NotFound {- entity: EntityType::Message,- id: uuid,- })?;- let session_uuid = Uuid::parse_str(&row.get_string(0)?)?;-+ let session_uuid = message_session_uuid(tx, uuid)?;let affected = tx.execute(- "UPDATE messages SET deleted_at = ?, server_updated_at = NULL WHERE message_uuid = ? AND deleted_at IS NULL",- &[Value::Integer(now), Value::Text(uuid.to_string())],+ "DELETE FROM messages WHERE message_uuid = ?",+ &[Value::Text(uuid.to_string())],)?;ensure_row_updated(affected, EntityType::Message, uuid)?;-- self.touch_session(tx, session_uuid, now)- })- }-- pub fn mark_session_synced(&self, uuid: Uuid, remote_id: &str) -> Result<()> {- let affected = self.backend.execute(- "UPDATE sessions SET remote_id = ?, needs_sync = 0 WHERE session_uuid = ?",- &[- Value::Text(remote_id.to_string()),- Value::Text(uuid.to_string()),- ],- )?;- ensure_row_updated(affected, EntityType::Session, uuid)- }-- pub fn get_session_remote_id(&self, uuid: Uuid) -> Result<Option<String>> {- let row = self.backend.query_row(- "SELECT remote_id FROM sessions WHERE session_uuid = ?",- &[Value::Text(uuid.to_string())],- )?;- let remote_id = match row {- Some(row) => row.get_optional_string(0)?,- None => None,- };- Ok(remote_id)- }-- pub fn set_session_remote_id(&self, uuid: Uuid, remote_id: &str) -> Result<()> {- let affected = self.backend.execute(- "UPDATE sessions SET remote_id = ? WHERE session_uuid = ?",- &[- Value::Text(remote_id.to_string()),- Value::Text(uuid.to_string()),- ],- )?;- ensure_row_updated(affected, EntityType::Session, uuid)- }-- pub fn get_session_uuid_by_remote_id(&self, remote_id: &str) -> Result<Option<Uuid>> {- let row = self.backend.query_row(- "SELECT session_uuid FROM sessions WHERE remote_id = ?",- &[Value::Text(remote_id.to_string())],- )?;- let uuid = match row {- Some(row) => {- let value = row.get_string(0)?;- Some(Uuid::parse_str(&value)?)- }- None => None,- };- Ok(uuid)- }-- pub fn set_session_server_updated_at(&self, uuid: Uuid, updated_at: i64) -> Result<()> {- let affected = self.backend.execute(- "UPDATE sessions SET server_updated_at = ? WHERE session_uuid = ?",- &[Value::Integer(updated_at), Value::Text(uuid.to_string())],- )?;- ensure_row_updated(affected, EntityType::Session, uuid)- }-- pub fn set_message_server_updated_at(&self, uuid: Uuid, updated_at: i64) -> Result<()> {- let affected = self.backend.execute(- "UPDATE messages SET server_updated_at = ? WHERE message_uuid = ?",- &[Value::Integer(updated_at), Value::Text(uuid.to_string())],- )?;- ensure_row_updated(affected, EntityType::Message, uuid)- }-- pub fn set_message_remote_id(&self, uuid: Uuid, remote_id: &str) -> Result<()> {- let affected = self.backend.execute(- "UPDATE messages SET remote_id = ? WHERE message_uuid = ?",- &[- Value::Text(remote_id.to_string()),- Value::Text(uuid.to_string()),- ],- )?;- ensure_row_updated(affected, EntityType::Message, uuid)- }-- pub fn get_message_remote_id(&self, uuid: Uuid) -> Result<Option<String>> {- let row = self.backend.query_row(- "SELECT remote_id FROM messages WHERE message_uuid = ?",- &[Value::Text(uuid.to_string())],- )?;- let remote_id = match row {- Some(row) => row.get_optional_string(0)?,- None => None,- };- Ok(remote_id)- }-- pub fn get_message_uuid_by_remote_id(&self, remote_id: &str) -> Result<Option<Uuid>> {- let row = self.backend.query_row(- "SELECT message_uuid FROM messages WHERE remote_id = ?",- &[Value::Text(remote_id.to_string())],- )?;- let uuid = match row {- Some(row) => {- let value = row.get_string(0)?;- Some(Uuid::parse_str(&value)?)- }- None => None,- };- Ok(uuid)- }-- pub fn mark_all_needs_sync(&self) -> Result<()> {- self.backend.execute(- "UPDATE sessions SET needs_sync = 1 WHERE deleted_at IS NULL",- &[],- )?;- self.backend.execute(- "UPDATE messages SET needs_sync = 1 WHERE deleted_at IS NULL",- &[],- )?;- Ok(())- }-- pub fn clear_all_server_timestamps(&self) -> Result<()> {- self.backend- .execute("UPDATE sessions SET server_updated_at = NULL", &[])?;- self.backend- .execute("UPDATE messages SET server_updated_at = NULL", &[])?;- Ok(())- }-- pub fn reset_sync_state(&self) -> Result<()> {- self.backend.execute(- "UPDATE sessions SET remote_id = NULL, server_updated_at = NULL, \- needs_sync = CASE WHEN deleted_at IS NULL THEN 1 ELSE needs_sync END",- &[],- )?;- self.backend.execute(- "UPDATE messages SET remote_id = NULL, server_updated_at = NULL, \- needs_sync = CASE WHEN deleted_at IS NULL THEN 1 ELSE needs_sync END",- &[],- )?;- Ok(())- }-- pub fn mark_message_synced(&self, uuid: Uuid) -> Result<()> {- let affected = self.backend.execute(- "UPDATE messages SET needs_sync = 0 WHERE message_uuid = ? AND deleted_at IS NULL",- &[Value::Text(uuid.to_string())],- )?;- ensure_row_updated(affected, EntityType::Message, uuid)- }-- pub fn upsert_session_from_remote(- &self,- session_uuid: Uuid,- remote_id: &str,- title: &str,- created_at: i64,- updated_at: i64,- ) -> Result<Session> {- let encrypted_title = crypto::encrypt_string(title, &self.key)?;- self.backend.execute(- "INSERT INTO sessions (session_uuid, title, created_at, updated_at, remote_id, needs_sync, deleted_at) \- VALUES (?, ?, ?, ?, ?, 0, NULL) \- ON CONFLICT(session_uuid) DO UPDATE SET \- title = CASE WHEN sessions.needs_sync = 1 THEN sessions.title ELSE excluded.title END, \- created_at = MIN(sessions.created_at, excluded.created_at), \- updated_at = MAX(sessions.updated_at, excluded.updated_at), \- remote_id = COALESCE(sessions.remote_id, excluded.remote_id), \- needs_sync = CASE WHEN sessions.needs_sync = 1 THEN 1 ELSE excluded.needs_sync END, \- deleted_at = NULL",- &[- Value::Text(session_uuid.to_string()),- Value::Blob(encrypted_title),- Value::Integer(created_at),- Value::Integer(updated_at),- Value::Text(remote_id.to_string()),- ],- )?;-- let session = self.get_session(session_uuid)?.ok_or(Error::NotFound {- entity: EntityType::Session,- id: session_uuid,- })?;- Ok(session)- }-- pub fn apply_session_tombstone(&self, session_uuid: Uuid, deleted_at: i64) -> Result<()> {- self.backend.transaction(|tx| {- tx.execute(- "UPDATE messages SET deleted_at = ? WHERE session_uuid = ? AND deleted_at IS NULL",- &[- Value::Integer(deleted_at),- Value::Text(session_uuid.to_string()),- ],- )?;- tx.execute(- "UPDATE sessions SET deleted_at = ?, needs_sync = 0 WHERE session_uuid = ?",- &[- Value::Integer(deleted_at),- Value::Text(session_uuid.to_string()),- ],- )?;- Ok(())+ self.touch_session(tx, session_uuid, updated_at)})}- #[allow(clippy::too_many_arguments)]- pub fn upsert_message_from_remote(- &self,- message_uuid: Uuid,- session_uuid: Uuid,- remote_id: &str,- sender: &str,- text: &str,- parent: Option<Uuid>,- attachments: Vec<AttachmentMeta>,- created_at: i64,- ) -> Result<Message> {- let sender: Sender = sender.parse()?;- let encrypted_text = crypto::encrypt_string(text, &self.key)?;- let attachments_json = self.serialize_attachments(&attachments)?;-- self.backend.execute(- "INSERT INTO messages (message_uuid, session_uuid, parent_message_uuid, sender, text, attachments, created_at, remote_id, needs_sync, deleted_at) \- VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, NULL) \- ON CONFLICT(message_uuid) DO UPDATE SET \- session_uuid = excluded.session_uuid, \- parent_message_uuid = excluded.parent_message_uuid, \- sender = excluded.sender, \- text = excluded.text, \- attachments = excluded.attachments, \- created_at = MIN(messages.created_at, excluded.created_at), \- remote_id = COALESCE(messages.remote_id, excluded.remote_id), \- needs_sync = CASE WHEN messages.needs_sync = 1 THEN 1 ELSE excluded.needs_sync END, \- deleted_at = NULL",- &[- Value::Text(message_uuid.to_string()),- Value::Text(session_uuid.to_string()),- parent- .map(|value| Value::Text(value.to_string()))- .unwrap_or(Value::Null),- Value::Text(sender.as_str().to_string()),- Value::Blob(encrypted_text),- attachments_json- .map(Value::Text)- .unwrap_or(Value::Null),- Value::Integer(created_at),- Value::Text(remote_id.to_string()),- ],- )?;-- let _ = self.touch_session_remote(session_uuid, created_at);-- Ok(Message {- uuid: message_uuid,- session_uuid,- parent_message_uuid: parent,- sender,- text: text.to_string(),- attachments,- created_at,- remote_id: Some(remote_id.to_string()),- server_updated_at: None,- needs_sync: false,- deleted_at: None,- })- }-- pub fn apply_message_tombstone(&self, message_uuid: Uuid, deleted_at: i64) -> Result<()> {- self.backend.execute(- "UPDATE messages SET deleted_at = ? WHERE message_uuid = ?",- &[- Value::Integer(deleted_at),- Value::Text(message_uuid.to_string()),- ],- )?;- Ok(())- }-- pub fn get_pending_deletions(&self) -> Result<Vec<(EntityType, Uuid)>> {- let session_rows = self.backend.query(- "SELECT session_uuid FROM sessions WHERE remote_id IS NOT NULL AND deleted_at IS NOT NULL ORDER BY deleted_at ASC",- &[],- )?;-- let mut deletions = Vec::new();- for row in session_rows {- let uuid = Uuid::parse_str(&row.get_string(0)?)?;- deletions.push((EntityType::Session, uuid));- }-- let message_rows = self.backend.query(- "SELECT messages.message_uuid \- FROM messages \- JOIN sessions ON messages.session_uuid = sessions.session_uuid \- WHERE messages.deleted_at IS NOT NULL \- AND sessions.remote_id IS NOT NULL \- AND sessions.deleted_at IS NULL \- ORDER BY messages.deleted_at ASC",- &[],- )?;-- for row in message_rows {- let uuid = Uuid::parse_str(&row.get_string(0)?)?;- deletions.push((EntityType::Message, uuid));- }-- Ok(deletions)- }-- pub fn get_deleted_sessions(&self) -> Result<Vec<(Uuid, i64)>> {- let rows = self.backend.query(- "SELECT session_uuid, deleted_at FROM sessions WHERE deleted_at IS NOT NULL ORDER BY deleted_at ASC",- &[],- )?;- rows.iter()- .map(|row| {- let uuid = Uuid::parse_str(&row.get_string(0)?)?;- let deleted_at = row.get_i64(1)?;- Ok((uuid, deleted_at))- })- .collect()- }-- pub fn get_deleted_messages(&self) -> Result<Vec<(Uuid, i64)>> {- let rows = self.backend.query(- "SELECT messages.message_uuid, messages.deleted_at \- FROM messages \- JOIN sessions ON messages.session_uuid = sessions.session_uuid \- WHERE messages.deleted_at IS NOT NULL \- AND sessions.deleted_at IS NULL \- ORDER BY messages.deleted_at ASC",- &[],- )?;- rows.iter()- .map(|row| {- let uuid = Uuid::parse_str(&row.get_string(0)?)?;- let deleted_at = row.get_i64(1)?;- Ok((uuid, deleted_at))- })- .collect()- }-- pub fn hard_delete(&self, entity_type: EntityType, uuid: Uuid) -> Result<()> {- match entity_type {- EntityType::Session => {- self.backend.execute(- "DELETE FROM sessions WHERE session_uuid = ?",- &[Value::Text(uuid.to_string())],- )?;- }- EntityType::Message => {- self.backend.execute(- "DELETE FROM messages WHERE message_uuid = ?",- &[Value::Text(uuid.to_string())],- )?;- }- }- Ok(())- }-fn session_from_row(&self, row: &crate::db::backend::Row) -> Result<Session> {- let uuid = Uuid::parse_str(&row.get_string(0)?)?;- let title_blob = row.get_blob(1)?;- let title = crypto::decrypt_string(&title_blob, &self.key)?;- let created_at = row.get_i64(2)?;- let updated_at = row.get_i64(3)?;- let server_updated_at = row.get_optional_i64(4)?;- let remote_id = row.get_optional_string(5)?;- let needs_sync = bool_from_i64(row.get_i64(6)?)?;- let deleted_at = row.get_optional_i64(7)?;Ok(Session {- uuid,- title,- created_at,- updated_at,- server_updated_at,- remote_id,- needs_sync,- deleted_at,+ uuid: Uuid::parse_str(&row.get_string(0)?)?,+ title: crypto::decrypt_string(&row.get_blob(1)?, &self.key)?,+ created_at: row.get_i64(2)?,+ updated_at: row.get_i64(3)?,})}fn message_from_row(&self, row: &crate::db::backend::Row) -> Result<Message> {- let uuid = Uuid::parse_str(&row.get_string(0)?)?;- let session_uuid = Uuid::parse_str(&row.get_string(1)?)?;let parent_message_uuid = row.get_optional_string(2)?.map(|value| Uuid::parse_str(&value)).transpose()?;- let sender: Sender = row.get_string(3)?.parse()?;- let text_blob = row.get_blob(4)?;- let text = crypto::decrypt_string(&text_blob, &self.key)?;- let attachments_json = row.get_optional_string(5)?;- let attachments = self.deserialize_attachments(attachments_json)?;- let created_at = row.get_i64(6)?;- let remote_id = row.get_optional_string(7)?;- let server_updated_at = row.get_optional_i64(8)?;- let needs_sync = bool_from_i64(row.get_i64(9)?)?;- let deleted_at = row.get_optional_i64(10)?;-Ok(Message {- uuid,- session_uuid,+ uuid: Uuid::parse_str(&row.get_string(0)?)?,+ session_uuid: Uuid::parse_str(&row.get_string(1)?)?,parent_message_uuid,- sender,- text,- attachments,- created_at,- remote_id,- server_updated_at,- needs_sync,- deleted_at,+ sender: row.get_string(3)?.parse()?,+ text: crypto::decrypt_string(&row.get_blob(4)?, &self.key)?,+ attachments: self.deserialize_attachments(row.get_optional_string(5)?)?,+ created_at: row.get_i64(6)?,})}@@ -883,39 +314,34 @@ impl<B: Backend> ChatDb<B> {if attachments.is_empty() {return Ok(None);}- let mut stored = Vec::with_capacity(attachments.len());- for attachment in attachments {- stored.push(self.attachment_to_stored(attachment)?);- }+ let stored = attachments+ .iter()+ .map(|attachment| {+ Ok(StoredAttachment {+ id: attachment.id.clone(),+ kind: attachment.kind,+ size: attachment.size,+ encrypted_name: crypto::encrypt_json_field(&attachment.name, &self.key)?,+ })+ })+ .collect::<Result<Vec<_>>>()?;Ok(Some(serde_json::to_string(&stored)?))}fn deserialize_attachments(&self, raw: Option<String>) -> Result<Vec<AttachmentMeta>> {- let stored = parse_stored_attachments(raw)?;- stored+ parse_stored_attachments(raw)?.into_iter()- .map(|attachment| self.stored_to_attachment(attachment))+ .map(|attachment| {+ Ok(AttachmentMeta {+ id: attachment.id,+ kind: attachment.kind,+ size: attachment.size,+ name: crypto::decrypt_json_field(&attachment.encrypted_name, &self.key)?,+ })+ }).collect()}- fn attachment_to_stored(&self, attachment: &AttachmentMeta) -> Result<StoredAttachment> {- Ok(StoredAttachment {- id: attachment.id.clone(),- kind: attachment.kind,- size: attachment.size,- encrypted_name: crypto::encrypt_json_field(&attachment.name, &self.key)?,- })- }-- fn stored_to_attachment(&self, attachment: StoredAttachment) -> Result<AttachmentMeta> {- Ok(AttachmentMeta {- id: attachment.id,- kind: attachment.kind,- size: attachment.size,- name: crypto::decrypt_json_field(&attachment.encrypted_name, &self.key)?,- })- }-fn touch_session<T: BackendTx>(&self,backend: &T,@@ -923,16 +349,27 @@ impl<B: Backend> ChatDb<B> {updated_at: i64,) -> Result<()> {let affected = backend.execute(- "UPDATE sessions SET updated_at = ?, needs_sync = 1, server_updated_at = NULL WHERE session_uuid = ? AND deleted_at IS NULL",- &[Value::Integer(updated_at), Value::Text(session_uuid.to_string())],+ "UPDATE sessions SET updated_at = ? WHERE session_uuid = ?",+ &[+ Value::Integer(updated_at),+ Value::Text(session_uuid.to_string()),+ ],)?;ensure_row_updated(affected, EntityType::Session, session_uuid)}- fn touch_session_remote(&self, session_uuid: Uuid, updated_at: i64) -> Result<()> {- let affected = self.backend.execute(- "UPDATE sessions SET updated_at = MAX(updated_at, ?) WHERE session_uuid = ? AND deleted_at IS NULL",- &[Value::Integer(updated_at), Value::Text(session_uuid.to_string())],+ fn touch_session_at_least<T: BackendTx>(+ &self,+ backend: &T,+ session_uuid: Uuid,+ updated_at: i64,+ ) -> Result<()> {+ let affected = backend.execute(+ "UPDATE sessions SET updated_at = MAX(updated_at, ?) WHERE session_uuid = ?",+ &[+ Value::Integer(updated_at),+ Value::Text(session_uuid.to_string()),+ ],)?;ensure_row_updated(affected, EntityType::Session, session_uuid)}@@ -974,29 +411,36 @@ fn validate_key(key: Vec<u8>) -> Result<Zeroizing<Vec<u8>>> {Ok(Zeroizing::new(key))}-fn bool_from_i64(value: i64) -> Result<bool> {- match value {- 0 => Ok(false),- 1 => Ok(true),- other => Err(Error::Row(format!("invalid bool value {other}"))),- }+fn optional_uuid(value: Option<Uuid>) -> Value {+ value+ .map(|uuid| Value::Text(uuid.to_string()))+ .unwrap_or(Value::Null)}-fn ensure_row_updated(affected: usize, entity: EntityType, uuid: Uuid) -> Result<()> {+fn message_session_uuid<T: BackendTx>(backend: &T, uuid: Uuid) -> Result<Uuid> {+ let row = backend.query_row(+ "SELECT session_uuid FROM messages WHERE message_uuid = ?",+ &[Value::Text(uuid.to_string())],+ )?;+ let row = row.ok_or(Error::NotFound {+ entity: EntityType::Message,+ id: uuid,+ })?;+ Ok(Uuid::parse_str(&row.get_string(0)?)?)+}++fn ensure_row_updated(affected: usize, entity: EntityType, id: Uuid) -> Result<()> {if affected == 0 {- return Err(Error::NotFound { entity, id: uuid });+ return Err(Error::NotFound { entity, id });}Ok(())}fn parse_stored_attachments(raw: Option<String>) -> Result<Vec<StoredAttachment>> {- let Some(raw) = raw else {- return Ok(Vec::new());- };- if raw.trim().is_empty() {- return Ok(Vec::new());+ match raw {+ Some(raw) if !raw.trim().is_empty() => Ok(serde_json::from_str(&raw)?),+ _ => Ok(Vec::new()),}- Ok(serde_json::from_str(&raw)?)}#[cfg(all(test, feature = "sqlite"))]@@ -1005,8 +449,6 @@ mod tests {use std::sync::atomic::{AtomicI64, Ordering};use std::sync::{Arc, Mutex};- use uuid::Uuid;-use super::*;use crate::db::backend::sqlite::SqliteBackend;use crate::db::backend::{BackendTx, RowExt, Value};@@ -1058,9 +500,8 @@ mod tests {}fn make_db(uuids: Vec<Uuid>, clock: Arc<dyn Clock>) -> ChatDb<SqliteBackend> {- let backend = SqliteBackend::open_in_memory().unwrap();ChatDb::new(- backend,+ SqliteBackend::open_in_memory().unwrap(),vec![1u8; KEY_BYTES],clock,Arc::new(TestUuidGen::new(uuids)),@@ -1071,16 +512,12 @@ mod tests {#[test]fn create_and_get_session_encrypts_title() {let session_id = Uuid::from_u128(1);- let clock = Arc::new(StepClock::new(100, 1));- let db = make_db(vec![session_id], clock);+ let db = make_db(vec![session_id], Arc::new(StepClock::new(100, 1)));let session = db.create_session("hello").unwrap();assert_eq!(session.uuid, session_id);assert_eq!(session.title, "hello");- assert!(session.needs_sync);-- let fetched = db.get_session(session_id).unwrap().unwrap();- assert_eq!(fetched.title, "hello");+ assert_eq!(db.get_session(session_id).unwrap().unwrap().title, "hello");let row = db.backend@@ -1099,76 +536,61 @@ mod tests {fn message_updates_touch_session() {let session_id = Uuid::from_u128(2);let message_id = Uuid::from_u128(3);- let clock = Arc::new(StepClock::new(10, 1));- let db = make_db(vec![session_id, message_id], clock.clone());+ let db = make_db(+ vec![session_id, message_id],+ Arc::new(StepClock::new(10, 1)),+ );db.create_session("title").unwrap();let after_create = db.get_session(session_id).unwrap().unwrap().updated_at;-let message = db.insert_message(session_id, "self", "hello", None, Vec::new()).unwrap();assert_eq!(message.uuid, message_id);-let after_insert = db.get_session(session_id).unwrap().unwrap().updated_at;assert!(after_insert > after_create);db.update_message_text(message_id, "updated").unwrap();- let after_update = db.get_session(session_id).unwrap().unwrap().updated_at;- assert!(after_update > after_insert);+ assert!(db.get_session(session_id).unwrap().unwrap().updated_at > after_insert);}#[test]- fn delete_session_soft_deletes_messages() {+ fn delete_session_cascades_messages() {let session_id = Uuid::from_u128(4);let message_id = Uuid::from_u128(5);- let clock = Arc::new(StepClock::new(1, 1));- let db = make_db(vec![session_id, message_id], clock);+ 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();- assert!(db.get_session(session_id).unwrap().is_none());- let row = db- .backend- .query_row(- "SELECT deleted_at FROM messages WHERE message_uuid = ?",- &[Value::Text(message_id.to_string())],- )- .unwrap()- .unwrap();- assert!(row.get_optional_i64(0).unwrap().is_some());+ assert!(db.get_session(session_id).unwrap().is_none());+ assert!(db.get_message(message_id).unwrap().is_none());}#[test]fn attachment_metadata_is_encrypted_in_json() {let session_id = Uuid::from_u128(6);let message_id = Uuid::from_u128(7);- let clock = Arc::new(StepClock::new(50, 1));- let db = make_db(vec![session_id, message_id], clock.clone());-+ let db = make_db(+ vec![session_id, message_id],+ Arc::new(StepClock::new(50, 1)),+ );db.create_session("title").unwrap();-- let attachments = vec![- AttachmentMeta {+ db.insert_message(+ session_id,+ "self",+ "hello",+ None,+ vec![AttachmentMeta {id: "att-1".to_string(),kind: AttachmentKind::Image,size: 123,name: "photo.jpg".to_string(),- },- AttachmentMeta {- id: "att-2".to_string(),- kind: AttachmentKind::Document,- size: 456,- name: "doc.pdf".to_string(),- },- ];-- db.insert_message(session_id, "self", "hello", None, attachments)- .unwrap();+ }],+ )+ .unwrap();let row = db.backend@@ -1178,9 +600,8 @@ mod tests {).unwrap().unwrap();- let json = row.get_optional_string(0).unwrap().unwrap();- let stored: Vec<StoredAttachment> = serde_json::from_str(&json).unwrap();- assert_eq!(stored.len(), 2);+ let stored: Vec<StoredAttachment> =+ serde_json::from_str(&row.get_optional_string(0).unwrap().unwrap()).unwrap();assert!(stored[0].encrypted_name.starts_with("enc:v1:"));assert!(!stored[0].encrypted_name.contains("photo.jpg"));}@@ -1189,17 +610,11 @@ mod tests {fn invalid_sender_is_rejected() {let session_id = Uuid::from_u128(8);let message_id = Uuid::from_u128(9);- let clock = Arc::new(StepClock::new(1, 1));- let db = make_db(vec![session_id, message_id], clock);-+ let db = make_db(vec![session_id, message_id], Arc::new(StepClock::new(1, 1)));db.create_session("title").unwrap();- let err = db- .insert_message(session_id, "invalid", "hello", None, Vec::new())- .unwrap_err();-- match err {- Error::InvalidSender(_) => {}- other => panic!("unexpected error: {other:?}"),- }+ assert!(matches!(+ db.insert_message(session_id, "invalid", "hello", None, Vec::new()),+ Err(Error::InvalidSender(_))+ ));}}diff --git a/rust/crates/ensu/src/db/chat/schema.rs b/rust/crates/ensu/src/db/chat/schema.rsindex 3a9580f317..ed9c23d940 100644--- a/rust/crates/ensu/src/db/chat/schema.rs+++ b/rust/crates/ensu/src/db/chat/schema.rs@@ -1,35 +1,3 @@-pub const PRAGMA_FOREIGN_KEYS: &str = "PRAGMA foreign_keys = ON;";--pub const CREATE_SESSIONS: &str = "-CREATE TABLE IF NOT EXISTS sessions (- session_uuid TEXT PRIMARY KEY NOT NULL,- title BLOB NOT NULL,- created_at INTEGER NOT NULL,- updated_at INTEGER NOT NULL,- server_updated_at INTEGER,- remote_id TEXT UNIQUE,- needs_sync INTEGER NOT NULL DEFAULT 1 CHECK(needs_sync IN (0,1)),- deleted_at INTEGER-);-";--pub const CREATE_MESSAGES: &str = "-CREATE TABLE IF NOT EXISTS messages (- message_uuid TEXT PRIMARY KEY NOT NULL,- session_uuid TEXT NOT NULL,- parent_message_uuid TEXT,- sender TEXT NOT NULL CHECK(sender IN ('self','other')),- text BLOB NOT NULL,- attachments TEXT,- created_at INTEGER NOT NULL,- remote_id TEXT,- server_updated_at INTEGER,- needs_sync INTEGER NOT NULL DEFAULT 1 CHECK(needs_sync IN (0,1)),- deleted_at INTEGER,- FOREIGN KEY (session_uuid) REFERENCES sessions(session_uuid) ON DELETE CASCADE-);-";-pub const CREATE_INDEXES: &str = "CREATE INDEX IF NOT EXISTS idx_messages_order ON messages(session_uuid, created_at, message_uuid);CREATE INDEX IF NOT EXISTS idx_sessions_updated ON sessions(updated_at);@@ -39,14 +7,10 @@ pub const CREATE_ALL: &str = "PRAGMA foreign_keys = ON;CREATE TABLE IF NOT EXISTS sessions (- session_uuid TEXT PRIMARY KEY NOT NULL,- title BLOB NOT NULL,- created_at INTEGER NOT NULL,- updated_at INTEGER NOT NULL,- server_updated_at INTEGER,- remote_id TEXT UNIQUE,- needs_sync INTEGER NOT NULL DEFAULT 1 CHECK(needs_sync IN (0,1)),- deleted_at INTEGER+ session_uuid TEXT PRIMARY KEY NOT NULL,+ title BLOB NOT NULL,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS messages (@@ -57,10 +21,6 @@ CREATE TABLE IF NOT EXISTS messages (text BLOB NOT NULL,attachments TEXT,created_at INTEGER NOT NULL,- remote_id TEXT,- server_updated_at INTEGER,- needs_sync INTEGER NOT NULL DEFAULT 1 CHECK(needs_sync IN (0,1)),- deleted_at INTEGER,FOREIGN KEY (session_uuid) REFERENCES sessions(session_uuid) ON DELETE CASCADE);diff --git a/rust/crates/ensu/src/db/database.rs b/rust/crates/ensu/src/db/database.rsdeleted file mode 100644index 5a09103862..0000000000--- a/rust/crates/ensu/src/db/database.rs+++ /dev/null@@ -1,355 +0,0 @@-#[cfg(feature = "sqlite")]-use std::sync::Arc;--use uuid::Uuid;--use crate::db::Result;-use crate::db::attachments::{AttachmentUploadRow, AttachmentsDb, UploadState};-use crate::db::chat::ChatDb;-use crate::db::models::{Attachment, AttachmentMeta, Message, Session, SessionWithPreview};-#[cfg(feature = "sqlite")]-use crate::db::traits::{Clock, UuidGen};--/// High-level DB that ties together the main chat DB and the attachments upload-state DB.-pub struct Db<B: crate::db::Backend> {- pub chat: ChatDb<B>,- pub attachments: AttachmentsDb<B>,-}--impl<B: crate::db::Backend> Db<B> {- pub fn new(chat: ChatDb<B>, attachments: AttachmentsDb<B>) -> Self {- Self { chat, attachments }- }-- pub fn create_session(&self, title: &str) -> Result<Session> {- self.chat.create_session(title)- }-- pub fn get_session(&self, uuid: Uuid) -> Result<Option<Session>> {- self.chat.get_session(uuid)- }-- pub fn list_sessions(&self) -> Result<Vec<Session>> {- 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()- }-- pub fn update_session_title(&self, uuid: Uuid, title: &str) -> Result<()> {- self.chat.update_session_title(uuid, title)- }-- pub fn delete_session(&self, uuid: Uuid) -> Result<()> {- // Best-effort cleanup in attachments DB. If this fails, still delete session.- let _ = self- .attachments- .delete_attachment_tracking_for_session(uuid);- self.chat.delete_session(uuid)- }-- #[allow(clippy::too_many_arguments)]- pub fn upsert_session(- &self,- session_uuid: Uuid,- title: &str,- created_at: i64,- updated_at: i64,- remote_id: Option<String>,- needs_sync: bool,- deleted_at: Option<i64>,- ) -> Result<Session> {- self.chat.upsert_session(- session_uuid,- title,- created_at,- updated_at,- remote_id,- needs_sync,- deleted_at,- )- }-- pub fn insert_message(- &self,- session_uuid: Uuid,- sender: &str,- text: &str,- parent: Option<Uuid>,- attachments: Vec<AttachmentMeta>,- ) -> Result<Message> {- let message =- self.chat- .insert_message(session_uuid, sender, text, parent, attachments.clone())?;-- for attachment in attachments {- self.attachments.upsert_pending_attachment(- &attachment.id,- session_uuid,- message.uuid,- attachment.size,- )?;- }-- Ok(message)- }-- #[allow(clippy::too_many_arguments)]- pub fn insert_message_with_uuid_and_state(- &self,- message_uuid: Uuid,- session_uuid: Uuid,- sender: &str,- text: &str,- parent: Option<Uuid>,- attachments: Vec<Attachment>,- created_at: i64,- deleted_at: Option<i64>,- needs_sync: bool,- ) -> Result<Message> {- let attachment_metas: Vec<AttachmentMeta> = attachments- .iter()- .cloned()- .map(AttachmentMeta::from)- .collect();- let message = self.chat.insert_message_with_uuid_and_state(- message_uuid,- session_uuid,- sender,- text,- parent,- attachment_metas,- created_at,- deleted_at,- needs_sync,- )?;-- for attachment in attachments {- if attachment.uploaded_at.is_some() {- self.attachments.upsert_attachment_with_state(- &attachment.id,- session_uuid,- message_uuid,- attachment.size,- None,- UploadState::Uploaded,- )?;- } else {- self.attachments.upsert_pending_attachment(- &attachment.id,- session_uuid,- message_uuid,- attachment.size,- )?;- }- }-- Ok(message)- }-- #[allow(clippy::too_many_arguments)]- pub fn insert_message_with_uuid(- &self,- message_uuid: Uuid,- session_uuid: Uuid,- sender: &str,- text: &str,- parent: Option<Uuid>,- attachments: Vec<Attachment>,- created_at: i64,- deleted_at: Option<i64>,- ) -> Result<Message> {- self.insert_message_with_uuid_and_state(- message_uuid,- session_uuid,- sender,- text,- parent,- attachments,- created_at,- deleted_at,- false,- )- }-- pub fn get_message(&self, uuid: Uuid) -> Result<Option<Message>> {- self.chat.get_message(uuid)- }-- pub fn get_messages(&self, session_uuid: Uuid) -> Result<Vec<Message>> {- self.chat.get_messages(session_uuid)- }-- pub fn get_messages_for_sync(- &self,- session_uuid: Uuid,- include_deleted: bool,- ) -> Result<Vec<Message>> {- self.chat- .get_messages_for_sync(session_uuid, include_deleted)- }-- pub fn get_messages_needing_sync(&self, session_uuid: Uuid) -> Result<Vec<Message>> {- self.chat.get_messages_needing_sync(session_uuid)- }-- pub fn update_message_text(&self, uuid: Uuid, text: &str) -> Result<()> {- self.chat.update_message_text(uuid, text)- }-- pub fn delete_message(&self, uuid: Uuid) -> Result<()> {- let _ = self- .attachments- .delete_attachment_tracking_for_message(uuid);- self.chat.delete_message(uuid)- }-- // Attachments DB APIs- pub fn upsert_pending_attachment(- &self,- attachment_id: &str,- session_uuid: Uuid,- message_uuid: Uuid,- size: i64,- ) -> Result<()> {- self.attachments- .upsert_pending_attachment(attachment_id, session_uuid, message_uuid, size)- }-- pub fn set_attachment_upload_state(- &self,- attachment_id: &str,- state: UploadState,- ) -> Result<()> {- self.attachments- .set_attachment_upload_state(attachment_id, state)- }-- pub fn get_pending_uploads_for_session(- &self,- session_uuid: Uuid,- ) -> Result<Vec<AttachmentUploadRow>> {- self.attachments- .get_pending_uploads_for_session(session_uuid)- }-- pub fn get_pending_uploads_for_message(- &self,- message_uuid: Uuid,- ) -> Result<Vec<AttachmentUploadRow>> {- self.attachments- .get_pending_uploads_for_message(message_uuid)- }-- pub fn get_uploads_for_message(&self, message_uuid: Uuid) -> Result<Vec<AttachmentUploadRow>> {- self.attachments.get_uploads_for_message(message_uuid)- }-- pub fn delete_attachment_tracking_for_message(&self, message_uuid: Uuid) -> Result<()> {- self.attachments- .delete_attachment_tracking_for_message(message_uuid)- }-- pub fn delete_attachment_tracking_for_session(&self, session_uuid: Uuid) -> Result<()> {- self.attachments- .delete_attachment_tracking_for_session(session_uuid)- }-- pub fn set_message_remote_id(&self, uuid: Uuid, remote_id: &str) -> Result<()> {- self.chat.set_message_remote_id(uuid, remote_id)- }-- #[allow(clippy::too_many_arguments)]- pub fn upsert_message_from_remote(- &self,- message_uuid: Uuid,- session_uuid: Uuid,- remote_id: &str,- sender: &str,- text: &str,- parent: Option<Uuid>,- attachments: Vec<AttachmentMeta>,- created_at: i64,- ) -> Result<Message> {- self.chat.upsert_message_from_remote(- message_uuid,- session_uuid,- remote_id,- sender,- text,- parent,- attachments,- created_at,- )- }-- pub fn apply_message_tombstone(&self, message_uuid: Uuid, deleted_at: i64) -> Result<()> {- self.chat.apply_message_tombstone(message_uuid, deleted_at)- }-- pub fn upsert_attachment_with_state(- &self,- attachment_id: &str,- session_uuid: Uuid,- message_uuid: Uuid,- size: i64,- remote_id: Option<&str>,- state: UploadState,- ) -> Result<()> {- self.attachments.upsert_attachment_with_state(- attachment_id,- session_uuid,- message_uuid,- size,- remote_id,- state,- )- }-- pub fn set_attachment_remote_id(- &self,- attachment_id: &str,- remote_id: Option<&str>,- ) -> Result<()> {- self.attachments- .set_attachment_remote_id(attachment_id, remote_id)- }-- pub fn get_attachment_remote_id(&self, attachment_id: &str) -> Result<Option<String>> {- self.attachments.get_attachment_remote_id(attachment_id)- }-- pub fn get_attachment_upload_state(&self, attachment_id: &str) -> Result<Option<UploadState>> {- self.attachments.get_upload_state(attachment_id)- }-}--#[cfg(feature = "sqlite")]-impl Db<crate::db::backend::sqlite::SqliteBackend> {- pub fn open_sqlite(- main_path: impl AsRef<std::path::Path>,- attachments_path: impl AsRef<std::path::Path>,- key: Vec<u8>,- clock: Arc<dyn Clock>,- uuid_gen: Arc<dyn UuidGen>,- ) -> Result<Self> {- let chat = ChatDb::open_sqlite(main_path, key, clock.clone(), uuid_gen)?;- let attachments = AttachmentsDb::open_sqlite(attachments_path, clock)?;- Ok(Self { chat, attachments })- }-- pub fn open_sqlite_with_defaults(- main_path: impl AsRef<std::path::Path>,- attachments_path: impl AsRef<std::path::Path>,- key: Vec<u8>,- ) -> Result<Self> {- let chat = ChatDb::open_sqlite_with_defaults(main_path, key)?;- let attachments = AttachmentsDb::open_sqlite_with_defaults(attachments_path)?;- Ok(Self { chat, attachments })- }-}diff --git a/rust/crates/ensu/src/db/mod.rs b/rust/crates/ensu/src/db/mod.rsindex 01341ebe6f..51b4d2fbdd 100644--- a/rust/crates/ensu/src/db/mod.rs+++ b/rust/crates/ensu/src/db/mod.rs@@ -1,27 +1,19 @@#![forbid(unsafe_code)]-pub mod attachments;pub mod backend;pub mod chat;pub mod crypto;-pub mod database;pub mod error;pub mod models;pub mod traits;-pub use crate::db::attachments::{AttachmentUploadRow, AttachmentsDb, UploadState};pub use crate::db::backend::{Backend, BackendTx, Row, Value};pub use crate::db::chat::ChatDb;-pub use crate::db::database::Db;pub use crate::db::error::{Error, Result};pub use crate::db::models::{- Attachment, AttachmentKind, AttachmentMeta, EntityType, Message, Sender, Session,- SessionWithPreview,-};-pub use crate::db::traits::{- AttachmentStore, Clock, FileMetaStore, FsAttachmentStore, MetaStore, RandomUuidGen,- SystemClock, UuidGen,+ AttachmentKind, AttachmentMeta, EntityType, Message, Sender, Session, SessionWithPreview,};+pub use crate::db::traits::{Clock, RandomUuidGen, SystemClock, UuidGen};#[cfg(feature = "sqlite")]pub use crate::db::backend::sqlite::SqliteBackend;diff --git a/rust/crates/ensu/src/db/models.rs b/rust/crates/ensu/src/db/models.rsindex d6540fef12..849d5424b2 100644--- a/rust/crates/ensu/src/db/models.rs+++ b/rust/crates/ensu/src/db/models.rs@@ -7,10 +7,6 @@ pub struct Session {pub title: String,pub created_at: i64,pub updated_at: i64,- pub server_updated_at: Option<i64>,- pub remote_id: Option<String>,- pub needs_sync: bool,- pub deleted_at: Option<i64>,}#[derive(Debug, Clone, PartialEq, Eq)]@@ -19,10 +15,6 @@ pub struct SessionWithPreview {pub title: String,pub created_at: i64,pub updated_at: i64,- pub server_updated_at: Option<i64>,- pub remote_id: Option<String>,- pub needs_sync: bool,- pub deleted_at: Option<i64>,pub last_message_preview: Option<String>,}@@ -35,10 +27,6 @@ pub struct Message {pub text: String,pub attachments: Vec<AttachmentMeta>,pub created_at: i64,- pub remote_id: Option<String>,- pub server_updated_at: Option<i64>,- pub needs_sync: bool,- pub deleted_at: Option<i64>,}#[derive(Debug, Clone, PartialEq, Eq)]@@ -49,38 +37,6 @@ pub struct AttachmentMeta {pub name: String,}-#[derive(Debug, Clone, PartialEq, Eq)]-pub struct Attachment {- pub id: String,- pub kind: AttachmentKind,- pub size: i64,- pub name: String,- pub uploaded_at: Option<i64>,-}--impl From<AttachmentMeta> for Attachment {- fn from(meta: AttachmentMeta) -> Self {- Self {- id: meta.id,- kind: meta.kind,- size: meta.size,- name: meta.name,- uploaded_at: None,- }- }-}--impl From<Attachment> for AttachmentMeta {- fn from(attachment: Attachment) -> Self {- Self {- id: attachment.id,- kind: attachment.kind,- size: attachment.size,- name: attachment.name,- }- }-}-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum AttachmentKind {diff --git a/rust/crates/ensu/src/db/traits.rs b/rust/crates/ensu/src/db/traits.rsindex 6f4fc72424..de5c3ce048 100644--- a/rust/crates/ensu/src/db/traits.rs+++ b/rust/crates/ensu/src/db/traits.rs@@ -1,26 +1,7 @@-use std::{- fs,- path::{Path, PathBuf},- time::{SystemTime, UNIX_EPOCH},-};+use std::time::{SystemTime, UNIX_EPOCH};use uuid::Uuid;-use crate::db::Result;--pub trait MetaStore: Send + Sync {- fn get(&self, key: &str) -> Result<Option<Vec<u8>>>;- fn set(&self, key: &str, value: &[u8]) -> Result<()>;- fn delete(&self, key: &str) -> Result<()>;-}--pub trait AttachmentStore: Send + Sync {- fn write(&self, id: &str, data: &[u8]) -> Result<()>;- fn read(&self, id: &str) -> Result<Vec<u8>>;- fn delete(&self, id: &str) -> Result<()>;- fn exists(&self, id: &str) -> Result<bool>;-}-pub trait Clock: Send + Sync {fn now_us(&self) -> i64;}@@ -51,117 +32,3 @@ impl UuidGen for RandomUuidGen {Uuid::new_v4()}}--#[derive(Debug, Clone)]-pub struct FileMetaStore {- root: PathBuf,-}--impl FileMetaStore {- pub fn new(root: impl Into<PathBuf>) -> Self {- Self { root: root.into() }- }-- fn key_path(&self, key: &str) -> PathBuf {- let encoded = ente_core::crypto::encode_b64_url_safe(key.as_bytes());- self.root.join(encoded)- }-- fn ensure_root(&self) -> Result<()> {- fs::create_dir_all(&self.root)?;- Ok(())- }-}--impl MetaStore for FileMetaStore {- fn get(&self, key: &str) -> Result<Option<Vec<u8>>> {- let path = self.key_path(key);- match fs::read(&path) {- Ok(bytes) => Ok(Some(bytes)),- Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),- Err(err) => Err(err.into()),- }- }-- fn set(&self, key: &str, value: &[u8]) -> Result<()> {- self.ensure_root()?;- let path = self.key_path(key);- fs::write(path, value)?;- Ok(())- }-- fn delete(&self, key: &str) -> Result<()> {- let path = self.key_path(key);- match fs::remove_file(path) {- Ok(()) => Ok(()),- Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),- Err(err) => Err(err.into()),- }- }-}--#[derive(Debug, Clone)]-pub struct FsAttachmentStore {- root: PathBuf,-}--impl FsAttachmentStore {- pub fn new(root: impl Into<PathBuf>) -> Self {- Self { root: root.into() }- }-- pub fn size(&self, id: &str) -> Result<u64> {- let path = self.attachment_path(id);- Ok(fs::metadata(path)?.len())- }-- pub fn clear_all(&self) -> Result<()> {- if self.root.exists() {- fs::remove_dir_all(&self.root)?;- }- fs::create_dir_all(&self.root)?;- Ok(())- }-- fn attachment_path(&self, id: &str) -> PathBuf {- self.root.join(id)- }-- fn ensure_root(&self) -> Result<()> {- fs::create_dir_all(&self.root)?;- Ok(())- }-}--impl AttachmentStore for FsAttachmentStore {- fn write(&self, id: &str, data: &[u8]) -> Result<()> {- self.ensure_root()?;- let path = self.attachment_path(id);- fs::write(path, data)?;- Ok(())- }-- fn read(&self, id: &str) -> Result<Vec<u8>> {- let path = self.attachment_path(id);- Ok(fs::read(path)?)- }-- fn delete(&self, id: &str) -> Result<()> {- let path = self.attachment_path(id);- match fs::remove_file(path) {- Ok(()) => Ok(()),- Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),- Err(err) => Err(err.into()),- }- }-- fn exists(&self, id: &str) -> Result<bool> {- let path = self.attachment_path(id);- Ok(path.exists())- }-}--pub fn ensure_directory(path: impl AsRef<Path>) -> Result<()> {- fs::create_dir_all(path)?;- Ok(())-}diff --git a/web/apps/ensu/src/services/chat/chatKey.ts b/web/apps/ensu/src/services/chat/chatKey.tsindex b3c8d81492..351fc03eaa 100644--- a/web/apps/ensu/src/services/chat/chatKey.ts+++ b/web/apps/ensu/src/services/chat/chatKey.ts@@ -10,16 +10,15 @@ import { ensureCryptoInit, enteWasm } from "../wasm";const LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY = "ensu.chatKey.local";const CHAT_KEY_FILE_NAME = "chat-keys.json";const LOCAL_CHAT_KEY_SECURE_STORAGE_KEY = "localChatKey.v2";-const LEGACY_ATTACHMENT_KEY_SECURE_STORAGE_KEY = "legacyAttachmentKey.v2";-const LEGACY_LOCAL_CHAT_KEY_SECURE_STORAGE_KEY = "localChatKey";+const V1_ATTACHMENT_KEY_SECURE_STORAGE_KEY = "legacyAttachmentKey.v2";+const V1_LOCAL_CHAT_KEY_SECURE_STORAGE_KEY = "localChatKey";type NativeChatKeys = { localChatKey?: string };let _localChatKey: string | undefined;-let _legacyLocalChatKey: string | undefined;-let _legacyAttachmentChatKey: string | undefined;-/** All distinct keys discovered during init, before any cleanup. */-let _allDiscoveredLocalChatKeys: string[] = [];+let _v1LocalChatKey: string | undefined;+let _v1AttachmentChatKey: string | undefined;+let _v1ChatKeyCandidates: string[] = [];let _chatKeyStoreInitPromise: Promise<void> | undefined;const readLocalStorageKey = (key: string) => {@@ -88,7 +87,7 @@ const persistNativeChatKeysSoon = () => {});};-const cleanupLegacyChatKeyCopies = async () => {+const cleanupV1ChatKeyCopies = async () => {removeLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);try {@@ -96,7 +95,7 @@ const cleanupLegacyChatKeyCopies = async () => {const path = await nativeChatKeyPath();await remove(path);} catch {- // ignore missing legacy file+ // The v1 key file may not exist.}};@@ -108,40 +107,37 @@ export const initChatKeyStore = async () => {_chatKeyStoreInitPromise = (async () => {const [secureLocalChatKey,- secureLegacyAttachmentKey,- legacySecureLocalChatKey,+ secureV1AttachmentKey,+ secureV1LocalChatKey,nativeKeys,] = await Promise.all([secureStorageGet(LOCAL_CHAT_KEY_SECURE_STORAGE_KEY).catch(() => undefined,),- secureStorageGet(LEGACY_ATTACHMENT_KEY_SECURE_STORAGE_KEY).catch(+ secureStorageGet(V1_ATTACHMENT_KEY_SECURE_STORAGE_KEY).catch(() => undefined,),- secureStorageGet(LEGACY_LOCAL_CHAT_KEY_SECURE_STORAGE_KEY).catch(+ secureStorageGet(V1_LOCAL_CHAT_KEY_SECURE_STORAGE_KEY).catch(() => undefined,),readNativeChatKeys(),]);- // Prefer localStorage over legacy secure storage for the local key.+ // Prefer localStorage over v1 secure storage for the local key.// Pre-v0.1.12 builds only used localStorage, so when both exist the- // localStorage value is the key that actually encrypted the legacy DB.+ // localStorage value is the key that actually encrypted the v1 DB.// Stale OS keyring entries from a previous v0.1.12 install can shadow// the correct localStorage key if secure storage is checked first.- const legacyLocalChatKey =+ const v1LocalChatKey =readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY) ??- legacySecureLocalChatKey ??+ secureV1LocalChatKey ??nativeKeys.localChatKey;- const localChatKey = secureLocalChatKey ?? legacyLocalChatKey;+ const localChatKey = secureLocalChatKey ?? v1LocalChatKey;_localChatKey = localChatKey;- _legacyLocalChatKey = legacyLocalChatKey;- _legacyAttachmentChatKey = secureLegacyAttachmentKey;+ _v1LocalChatKey = v1LocalChatKey;+ _v1AttachmentChatKey = secureV1AttachmentKey;- // Capture every distinct local chat key found across all sources- // *before* cleanup deletes legacy copies. The migration needs all- // of these because the ?? chains above can shadow the correct key- // when stale entries exist in the OS keyring.+ // Capture v1 candidates before cleanup removes their old copies.{const rawLocalStorage = readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY,@@ -150,7 +146,7 @@ export const initChatKeyStore = async () => {const all: string[] = [];for (const k of [secureLocalChatKey,- legacySecureLocalChatKey,+ secureV1LocalChatKey,nativeKeys.localChatKey,rawLocalStorage,]) {@@ -159,7 +155,7 @@ export const initChatKeyStore = async () => {all.push(k);}}- _allDiscoveredLocalChatKeys = all;+ _v1ChatKeyCandidates = all;}if (secureLocalChatKey !== localChatKey) {@@ -175,9 +171,9 @@ export const initChatKeyStore = async () => {}try {- await cleanupLegacyChatKeyCopies();+ await cleanupV1ChatKeyCopies();} catch (error) {- log.warn("Failed to clean up legacy chat key copies", error);+ log.warn("Failed to clean up v1 chat key copies", error);}})().catch((error: unknown) => {_chatKeyStoreInitPromise = undefined;@@ -208,23 +204,18 @@ export const cachedLocalChatKey = (): string | undefined => {return readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);};-export const legacyLocalChatKey = (): string | undefined => {+export const v1LocalChatKey = (): string | undefined => {if (isTauriRuntime()) {- return _legacyLocalChatKey;+ return _v1LocalChatKey;}return readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);};/**- * Return all distinct legacy key candidates that might decrypt a legacy DB.- *- * Unlike {@link legacyLocalChatKey}, this returns every key found across all- * legacy storage locations so the migration can try each one. This is needed- * because stale keys in the OS keyring can shadow the correct key in- * localStorage.+ * Return every key candidate that might decrypt the v1 DB.*/-export const allLegacyKeyCandidates = (): string[] => {+export const v1ChatKeyCandidates = (): string[] => {const seen = new Set<string>();const keys: string[] = [];const add = (k: string | undefined) => {@@ -233,28 +224,22 @@ export const allLegacyKeyCandidates = (): string[] => {keys.push(k);}};- add(_legacyLocalChatKey);+ add(_v1LocalChatKey);add(_localChatKey);- // Include every local chat key discovered during init (before cleanup- // deleted legacy copies). This ensures we try the raw localStorage key- // even when stale OS keyring entries shadowed it in the ?? chains.- for (const k of _allDiscoveredLocalChatKeys) add(k);+ for (const k of _v1ChatKeyCandidates) add(k);return keys;};-export const legacyAttachmentChatKey = (): string | undefined =>- _legacyAttachmentChatKey;+export const v1AttachmentChatKey = (): string | undefined =>+ _v1AttachmentChatKey;-export const setLegacyAttachmentChatKey = async (chatKey?: string) => {- _legacyAttachmentChatKey = chatKey;+export const setV1AttachmentChatKey = async (chatKey?: string) => {+ _v1AttachmentChatKey = chatKey;if (!isTauriRuntime()) return;if (chatKey) {- await secureStorageSet(- LEGACY_ATTACHMENT_KEY_SECURE_STORAGE_KEY,- chatKey,- );+ await secureStorageSet(V1_ATTACHMENT_KEY_SECURE_STORAGE_KEY, chatKey);} else {- await secureStorageDelete(LEGACY_ATTACHMENT_KEY_SECURE_STORAGE_KEY);+ await secureStorageDelete(V1_ATTACHMENT_KEY_SECURE_STORAGE_KEY);}};diff --git a/web/apps/ensu/src/services/chat/store.ts b/web/apps/ensu/src/services/chat/store.tsindex 96c03f0c20..017a1f4eb8 100644--- a/web/apps/ensu/src/services/chat/store.ts+++ b/web/apps/ensu/src/services/chat/store.ts@@ -5,11 +5,11 @@ import log from "ente-base/log";import { deleteDB, openDB, type DBSchema, type IDBPDatabase } from "idb";import { decryptAttachmentBytes, encryptAttachmentBytes } from "./attachments";import {- allLegacyKeyCandidates,cachedLocalChatKey,- legacyAttachmentChatKey,- legacyLocalChatKey,- setLegacyAttachmentChatKey,+ setV1AttachmentChatKey,+ v1AttachmentChatKey,+ v1ChatKeyCandidates,+ v1LocalChatKey,} from "./chatKey";import {decryptChatField,@@ -19,9 +19,10 @@ import {} from "./crypto";const STORAGE_KEY = "ensu.chat.store.v1";-const NATIVE_MIGRATION_KEY = "ensu.chat.nativeMigration.v2";+const NATIVE_V1_IMPORT_KEY = "ensu.chat.nativeMigration.v2";+const LOCAL_SCHEMA_MIGRATION_KEY = "ensu.chat.localMigration.v2";const CHAT_DB_NAME = "ensu-chat";-const LEGACY_WEB_CHAT_DB_NAME = "ensu.chat.db";+const V1_WEB_CHAT_DB_NAME = "ensu.chat.db";export type AttachmentKind = "image" | "document";@@ -31,7 +32,6 @@ export interface ChatAttachment {name: string;size: number;encryptedName?: string;- uploadedAt?: number;}interface StoredAttachment {@@ -39,7 +39,6 @@ interface StoredAttachment {kind: AttachmentKind;size: number;encryptedName: string;- uploadedAt?: number | null;}interface StoredSession {@@ -48,10 +47,6 @@ interface StoredSession {updatedAt: number;encryptedData: string;header: string;- remoteId?: string | null;- needsSync?: boolean;- deletedAt?: number | null;- isDeleted?: boolean;}interface StoredMessage {@@ -63,10 +58,20 @@ interface StoredMessage {encryptedData: string;header: string;attachments?: StoredAttachment[];- remoteId?: string | null;+}++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;@@ -84,8 +89,8 @@ type ChatStoreName = keyof ChatDbSchema;type PersistedAttachmentBytes = { id: string; data: string };type PersistedChatStore = {- sessions: StoredSession[];- messages: StoredMessage[];+ sessions: OldStoredSession[];+ messages: OldStoredMessage[];attachmentBytes: PersistedAttachmentBytes[];};@@ -153,9 +158,6 @@ interface NativeSession {title: string;createdAt: number;updatedAt: number;- remoteId?: string | null;- needsSync?: boolean;- deletedAt?: number | null;lastMessagePreview?: string | null;}@@ -164,7 +166,6 @@ interface NativeAttachment {kind: AttachmentKind;name: string;size: number;- uploadedAt?: number | null;}interface NativeMessage {@@ -175,11 +176,9 @@ interface NativeMessage {text: string;createdAt: number;attachments?: NativeAttachment[];- remoteId?: string | null;- deletedAt?: number | null;}-interface NativeLegacyMigrationResult {+interface NativeV1ImportResult {didMigrate: boolean;migratedSessions: number;migratedMessages: number;@@ -219,23 +218,20 @@ const loadChatStoreState = (): ChatStoreState => {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: (parsed.sessions ?? []).map((session) => ({- ...session,- remoteId: session.remoteId ?? null,- needsSync: session.needsSync ?? true,- deletedAt:- session.deletedAt ??- (session.isDeleted ? session.updatedAt : null),- })),- messages: (parsed.messages ?? []).map((message) => ({- ...message,- attachments: message.attachments ?? [],- remoteId: message.remoteId ?? null,- deletedAt:- message.deletedAt ??- (message.isDeleted ? message.createdAt : null),- })),+ sessions,+ messages: (parsed.messages ?? [])+ .map(normalizeOldMessage)+ .filter(+ (message): message is StoredMessage =>+ !!message && sessionIDs.has(message.sessionUuid),+ ),attachmentBytes: (parsed.attachmentBytes ?? []).map((attachment) => ({id: attachment.id,@@ -275,37 +271,38 @@ let _chatDb: Promise<ChatDbLike> | undefined;let _chatPersistenceInitPromise: Promise<void> | undefined;let _chatPersistenceInitKey: string | undefined;-const normalizeStoredSession = (session: StoredSession): StoredSession => ({- ...session,- remoteId: session.remoteId ?? null,- needsSync: session.needsSync ?? true,- deletedAt:- session.deletedAt ?? (session.isDeleted ? session.updatedAt : null),-});--const normalizeStoredMessage = (message: StoredMessage): StoredMessage => ({- ...message,- attachments: message.attachments ?? [],- remoteId: message.remoteId ?? null,- deletedAt:- message.deletedAt ?? (message.isDeleted ? message.createdAt : null),-});+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 normalizeStoreEntry = <K extends ChatStoreName>(- name: K,- value: ChatDbSchema[K],-): ChatDbSchema[K] => {- if (name === "sessions") {- return normalizeStoredSession(- value as StoredSession,- ) as ChatDbSchema[K];- }- if (name === "messages") {- return normalizeStoredMessage(- value as StoredMessage,- ) as ChatDbSchema[K];- }- return value;+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 = (@@ -316,13 +313,11 @@ const createIndexedDbChatDb = (| ChatDbSchema[typeof name]| undefined;if (!entry) return undefined;- return cloneStoreEntry(name, normalizeStoreEntry(name, entry));+ return cloneStoreEntry(name, entry);},getAll: async (name) => {const entries = (await db.getAll(name)) as ChatDbSchema[typeof name][];- return entries.map((entry) =>- cloneStoreEntry(name, normalizeStoreEntry(name, entry)),- );+ return entries.map((entry) => cloneStoreEntry(name, entry));},put: async (name, value) => {await db.put(name, cloneStoreEntry(name, value));@@ -338,18 +333,13 @@ const createIndexedDbChatDb = (| ChatDbSchema[K]| undefined;if (!entry) return undefined;- return cloneStoreEntry(- name,- normalizeStoreEntry(name, entry),- );+ return cloneStoreEntry(name, entry);},getAll: async () => {const entries = (await tx.objectStore(name).getAll()) as ChatDbSchema[K][];- return entries.map((entry) =>- cloneStoreEntry(name, normalizeStoreEntry(name, entry)),- );+ return entries.map((entry) => cloneStoreEntry(name, entry));},put: async (value: ChatDbSchema[K]) => {await tx@@ -366,6 +356,46 @@ 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) {@@ -381,6 +411,7 @@ const openChatDb = async () => {},});+ await migrateIndexedDbToLocalOnly(db);return createIndexedDbChatDb(db);};@@ -445,7 +476,6 @@ const serializeAttachments = async (encryptedName:attachment.encryptedName ??(await encryptChatField(attachment.name, chatKey)),- uploadedAt: attachment.uploadedAt ?? null,})),);};@@ -456,7 +486,7 @@ const deserializeAttachments = async (): Promise<ChatAttachment[]> => {if (!attachments?.length || !isTauriRuntime()) return [];- const localKey = cachedLocalChatKey() ?? legacyLocalChatKey();+ const localKey = cachedLocalChatKey() ?? v1LocalChatKey();return Promise.all(attachments.map(async (attachment) => {@@ -471,7 +501,6 @@ const deserializeAttachments = async (size: attachment.size,name,encryptedName: attachment.encryptedName,- uploadedAt: attachment.uploadedAt ?? undefined,} satisfies ChatAttachment;} catch (error) {if (localKey && localKey !== chatKey) {@@ -486,7 +515,6 @@ const deserializeAttachments = async (size: attachment.size,name,encryptedName: undefined,- uploadedAt: attachment.uploadedAt ?? undefined,} satisfies ChatAttachment;} catch (innerError) {log.error(@@ -503,14 +531,13 @@ const deserializeAttachments = async (size: attachment.size,name: "Attachment",encryptedName: attachment.encryptedName,- uploadedAt: attachment.uploadedAt ?? undefined,} satisfies ChatAttachment;}}),);};-const hasLegacyChatStore = () =>+const hasLocalStorageChatStore = () =>typeof localStorage !== "undefined" && !!localStorage.getItem(STORAGE_KEY);const hasIndexedDbDatabase = async (name: string) => {@@ -548,32 +575,32 @@ const hasIndexedDbDatabase = async (name: string) => {});};-const isNativeMigrationDone = () =>+const isNativeV1ImportDone = () =>typeof localStorage !== "undefined" &&- localStorage.getItem(NATIVE_MIGRATION_KEY) === "1";+ localStorage.getItem(NATIVE_V1_IMPORT_KEY) === "1";-const markNativeMigrationDone = () => {+const markNativeV1ImportDone = () => {if (typeof localStorage === "undefined") return;- localStorage.setItem(NATIVE_MIGRATION_KEY, "1");+ localStorage.setItem(NATIVE_V1_IMPORT_KEY, "1");};-const migrateLegacyLocalChatStoreToIndexedDb = async () => {+const importLocalStorageChatStoreToIndexedDb = async () => {if (typeof localStorage === "undefined") return;- const legacy = loadChatStoreState();+ const localStorageStore = loadChatStoreState();if (- !legacy.sessions.length &&- !legacy.messages.length &&- !legacy.attachmentBytes.length+ !localStorageStore.sessions.length &&+ !localStorageStore.messages.length &&+ !localStorageStore.attachmentBytes.length) {localStorage.removeItem(STORAGE_KEY);return;}- log.info("Migrating legacy local chat store to IndexedDB", {- sessions: legacy.sessions.length,- messages: legacy.messages.length,- attachmentBytes: legacy.attachmentBytes.length,+ log.info("Migrating localStorage chat store to IndexedDB", {+ sessions: localStorageStore.sessions.length,+ messages: localStorageStore.messages.length,+ attachmentBytes: localStorageStore.attachmentBytes.length,});const db = await chatDb();@@ -582,15 +609,15 @@ const migrateLegacyLocalChatStoreToIndexedDb = async () => {"readwrite",);- for (const session of legacy.sessions) {- await tx.objectStore("sessions").put(normalizeStoredSession(session));+ for (const session of localStorageStore.sessions) {+ await tx.objectStore("sessions").put(session);}- for (const message of legacy.messages) {- await tx.objectStore("messages").put(normalizeStoredMessage(message));+ for (const message of localStorageStore.messages) {+ await tx.objectStore("messages").put(message);}- for (const attachment of legacy.attachmentBytes) {+ for (const attachment of localStorageStore.attachmentBytes) {await tx.objectStore("attachmentBytes").put({ id: attachment.id, data: new Uint8Array(attachment.data) });@@ -598,30 +625,42 @@ const migrateLegacyLocalChatStoreToIndexedDb = async () => {await tx.done;localStorage.removeItem(STORAGE_KEY);- log.info("Finished migrating legacy local chat store to IndexedDB");+ log.info("Finished migrating localStorage chat store to IndexedDB");};-const migrateLegacyIndexedDbChatStore = async () => {+const importV1IndexedDbChatStore = async () => {if (typeof indexedDB === "undefined") return;- if (!(await hasIndexedDbDatabase(LEGACY_WEB_CHAT_DB_NAME))) return;+ if (!(await hasIndexedDbDatabase(V1_WEB_CHAT_DB_NAME))) return;- log.info("Migrating legacy IndexedDB chat store", {- from: LEGACY_WEB_CHAT_DB_NAME,+ log.info("Migrating v1 IndexedDB chat store", {+ from: V1_WEB_CHAT_DB_NAME,to: CHAT_DB_NAME,});- const [legacyDb, db] = await Promise.all([- openDB<IndexedChatDBSchema>(LEGACY_WEB_CHAT_DB_NAME),+ const [v1Db, db] = await Promise.all([+ openDB<IndexedChatDBSchema>(V1_WEB_CHAT_DB_NAME),chatDb(),]);let migratedAnyEntries: boolean;try {- const [sessions, messages, attachmentBytes] = await Promise.all([- legacyDb.getAll("sessions"),- legacyDb.getAll("messages"),- legacyDb.getAll("attachmentBytes"),+ 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 ||@@ -633,15 +672,11 @@ const migrateLegacyIndexedDbChatStore = async () => {);for (const session of sessions) {- await tx- .objectStore("sessions")- .put(normalizeStoredSession(session));+ await tx.objectStore("sessions").put(session);}for (const message of messages) {- await tx- .objectStore("messages")- .put(normalizeStoredMessage(message));+ await tx.objectStore("messages").put(message);}for (const attachment of attachmentBytes) {@@ -655,44 +690,42 @@ const migrateLegacyIndexedDbChatStore = async () => {await tx.done;} finally {- legacyDb.close();+ v1Db.close();}- await deleteDB(LEGACY_WEB_CHAT_DB_NAME, {+ await deleteDB(V1_WEB_CHAT_DB_NAME, {blocked() {- log.warn(- "Waiting for an existing client to close the legacy chat DB",- );+ log.warn("Waiting for an existing client to close the v1 chat DB");},});log.info(migratedAnyEntries- ? "Finished migrating legacy IndexedDB chat store"- : "Removed empty legacy IndexedDB chat store",+ ? "Finished migrating v1 IndexedDB chat store"+ : "Removed empty v1 IndexedDB chat store",);};-const migrateLegacyChatStoreToNative = async (chatKey: string) => {+const importLocalStorageChatStoreToNative = async (chatKey: string) => {if (!isTauriRuntime() || typeof localStorage === "undefined") return;- const legacy = loadChatStoreState();+ const localStorageStore = loadChatStoreState();if (- !legacy.sessions.length &&- !legacy.messages.length &&- !legacy.attachmentBytes.length+ !localStorageStore.sessions.length &&+ !localStorageStore.messages.length &&+ !localStorageStore.attachmentBytes.length) {localStorage.removeItem(STORAGE_KEY);return;}- log.info("Migrating legacy local chat store to native DB", {- sessions: legacy.sessions.length,- messages: legacy.messages.length,- attachmentBytes: legacy.attachmentBytes.length,+ log.info("Migrating localStorage chat store to native DB", {+ sessions: localStorageStore.sessions.length,+ messages: localStorageStore.messages.length,+ attachmentBytes: localStorageStore.attachmentBytes.length,});- const sessions = [...legacy.sessions].sort(+ const sessions = [...localStorageStore.sessions].sort((left, right) => left.createdAt - right.createdAt,);for (const session of sessions) {@@ -704,14 +737,11 @@ const migrateLegacyChatStoreToNative = async (chatKey: string) => {title,createdAt: session.createdAt,updatedAt: session.updatedAt,- remoteId: session.remoteId ?? null,- needsSync: session.needsSync ?? false,- deletedAt: session.deletedAt ?? null,},});}- const messages = [...legacy.messages].sort(+ const messages = [...localStorageStore.messages].sort((left, right) => left.createdAt - right.createdAt,);for (const message of messages) {@@ -720,16 +750,6 @@ const migrateLegacyChatStoreToNative = async (chatKey: string) => {chatKey,);- if (!message.remoteId) {- const existing = await invokeChat<NativeMessage | null>(- "chat_db_get_message",- { keyB64: chatKey, messageUuid: message.messageUuid },- );- if (existing) {- continue;- }- }-await invokeChat("chat_db_insert_message_with_uuid", {keyB64: chatKey,input: {@@ -739,53 +759,47 @@ const migrateLegacyChatStoreToNative = async (chatKey: string) => {sender: message.sender,text: await decryptMessageText(message, chatKey),createdAt: message.createdAt,- remoteId: message.remoteId ?? null,- deletedAt: message.deletedAt ?? null,attachments: attachments.map((attachment) => ({id: attachment.id,kind: attachment.kind,name: attachment.name,size: attachment.size,- uploadedAt: attachment.uploadedAt ?? null,})),},});}- for (const attachment of legacy.attachmentBytes) {+ for (const attachment of localStorageStore.attachmentBytes) {await writeAttachmentBytes(attachment.id, attachment.data);}localStorage.removeItem(STORAGE_KEY);- log.info("Finished migrating legacy local chat store to native DB");+ log.info("Finished migrating localStorage chat store to native DB");};-const migrateLegacyNativeChatStoreToV2 = async (- chatKey: string,-): Promise<boolean> => {+const importNativeV1ChatStore = async (chatKey: string): Promise<boolean> => {if (!isTauriRuntime()) return true;- // Collect all known key candidates. allLegacyKeyCandidates returns every- // key found across secure storage, native file, AND localStorage. This is- // important because stale OS keyring entries from a previous install can- // shadow the correct localStorage key in the normal prioritized lookup.- const candidateKeys = allLegacyKeyCandidates();+ const candidateKeys = v1ChatKeyCandidates();+ const previousAttachmentKey = v1AttachmentChatKey();const seen = new Set<string>(candidateKeys);if (chatKey && !seen.has(chatKey)) {candidateKeys.push(chatKey);}for (const candidateKey of candidateKeys) {+ await setV1AttachmentChatKey(+ candidateKey === chatKey ? undefined : candidateKey,+ );try {- const result = await invokeChat<NativeLegacyMigrationResult>(- "chat_db_migrate_legacy",- { input: { keyB64: chatKey, legacyKeyB64: candidateKey } },+ const result = await invokeChat<NativeV1ImportResult>(+ "chat_db_import_v1",+ { input: { keyB64: chatKey, v1KeyB64: candidateKey } },);if (result.didMigrate) {- await setLegacyAttachmentChatKey(- candidateKey === chatKey ? undefined : candidateKey,- );- log.info("Migrated legacy native chat store to v2 DB", result);+ log.info("Migrated v1 native chat store", result);+ } else {+ await setV1AttachmentChatKey(previousAttachmentKey);}return true;} catch (error) {@@ -795,6 +809,7 @@ const migrateLegacyNativeChatStoreToV2 = async (code === "db_invalid_blob_length" ||code === "db_invalid_encrypted_field") {+ await setV1AttachmentChatKey(previousAttachmentKey);continue;}throw error;@@ -802,7 +817,7 @@ const migrateLegacyNativeChatStoreToV2 = async (}log.warn(- "Skipping legacy native chat migration because the available legacy keys could not decrypt the legacy DB",+ "Skipping v1 native chat migration because no v1 key could decrypt the DB",);return false;};@@ -815,20 +830,20 @@ export const initializeChatStorePersistence = async (chatKey: string) => {_chatPersistenceInitKey = chatKey;const initPromise = (async () => {if (isTauriRuntime()) {- if (!isNativeMigrationDone()) {- const didResolveNativeMigration =- await migrateLegacyNativeChatStoreToV2(chatKey);- if (hasLegacyChatStore()) {- await migrateLegacyChatStoreToNative(chatKey);+ if (!isNativeV1ImportDone()) {+ const didResolveNativeV1Import =+ await importNativeV1ChatStore(chatKey);+ if (hasLocalStorageChatStore()) {+ await importLocalStorageChatStoreToNative(chatKey);}- if (didResolveNativeMigration) {- markNativeMigrationDone();+ if (didResolveNativeV1Import) {+ markNativeV1ImportDone();}}- } else if (hasLegacyChatStore()) {- await migrateLegacyLocalChatStoreToIndexedDb();+ } else if (hasLocalStorageChatStore()) {+ await importLocalStorageChatStoreToIndexedDb();} else {- await migrateLegacyIndexedDbChatStore();+ await importV1IndexedDbChatStore();}})().catch((error: unknown) => {if (_chatPersistenceInitPromise === initPromise) {@@ -866,9 +881,7 @@ const listSessionsNative = async (chatKey: string): Promise<ChatSession[]> => {{ keyB64: chatKey },);- const activeSessions = sessions.filter((session) => !session.deletedAt);-- return activeSessions.map((session) => ({+ return sessions.map((session) => ({sessionUuid: session.sessionUuid,rootSessionUuid: session.sessionUuid,branchFromMessageUuid: undefined,@@ -888,23 +901,20 @@ const listMessagesNative = async (sessionUuid,});- return messages- .filter((message) => !message.deletedAt)- .map((message) => ({- messageUuid: message.messageUuid,- sessionUuid: message.sessionUuid,- parentMessageUuid: message.parentMessageUuid ?? undefined,- sender: message.sender,- text: message.text,- createdAt: message.createdAt,- attachments: message.attachments?.map((attachment) => ({- id: attachment.id,- kind: attachment.kind,- name: attachment.name,- size: attachment.size,- uploadedAt: attachment.uploadedAt ?? undefined,- })),- }));+ return messages.map((message) => ({+ messageUuid: message.messageUuid,+ sessionUuid: message.sessionUuid,+ parentMessageUuid: message.parentMessageUuid ?? undefined,+ sender: message.sender,+ text: message.text,+ createdAt: message.createdAt,+ attachments: message.attachments?.map((attachment) => ({+ id: attachment.id,+ kind: attachment.kind,+ name: attachment.name,+ size: attachment.size,+ })),+ }));};const createSessionNative = async (chatKey: string) => {@@ -947,7 +957,6 @@ const addMessageNative = async (kind: attachment.kind,name: attachment.name,size: attachment.size,- uploadedAt: attachment.uploadedAt ?? null,})),},});@@ -982,7 +991,6 @@ const addMessageNative = async (kind: attachment.kind,name: attachment.name,size: attachment.size,- uploadedAt: attachment.uploadedAt ?? undefined,})),};};@@ -1021,13 +1029,12 @@ export const listSessions = async (chatKey: string): Promise<ChatSession[]> => {try {const { sessions, messages } = await fetchStore();- const activeSessions = sessions- .filter((session) => !session.deletedAt && !session.isDeleted)- .sort((a, b) => b.updatedAt - a.updatedAt);+ const activeSessions = sessions.sort(+ (a, b) => b.updatedAt - a.updatedAt,+ );const bySession = new Map<string, StoredMessage[]>();for (const message of messages) {- if (message.deletedAt || message.isDeleted) continue;const list = bySession.get(message.sessionUuid) ?? [];list.push(message);bySession.set(message.sessionUuid, list);@@ -1080,12 +1087,7 @@ export const listMessages = async (try {const { messages } = await fetchStore();const sessionMessages = messages- .filter(- (message) =>- message.sessionUuid === sessionUuid &&- !message.deletedAt &&- !message.isDeleted,- )+ .filter((message) => message.sessionUuid === sessionUuid).sort((a, b) => a.createdAt - b.createdAt);return Promise.all(@@ -1125,9 +1127,6 @@ export const createSession = async (chatKey: string) => {updatedAt: now,encryptedData: encrypted.encryptedData,header: encrypted.header,- remoteId: null,- needsSync: true,- deletedAt: null,};await db.put("sessions", session);@@ -1169,8 +1168,6 @@ export const addMessage = async (encryptedData: encrypted.encryptedData,header: encrypted.header,attachments: storedAttachments,- remoteId: null,- deletedAt: null,};const tx = db.transaction(["sessions", "messages"], "readwrite");@@ -1180,7 +1177,6 @@ export const addMessage = async (const session = await sessionStore.get(sessionUuid);if (session) {session.updatedAt = now;- session.needsSync = true;const currentTitle = await decryptSessionTitle(session, chatKey);if (sender === "self" && currentTitle.toLowerCase() === "new chat") {@@ -1224,7 +1220,6 @@ export const updateSessionTitle = async (session.encryptedData = updated.encryptedData;session.header = updated.header;session.updatedAt = nowMicros();- session.needsSync = true;await db.put("sessions", session);};@@ -1256,7 +1251,6 @@ export const updateMessage = async (const session = await sessionStore.get(message.sessionUuid);if (session) {session.updatedAt = nowMicros();- session.needsSync = true;await sessionStore.put(session);}@@ -1299,27 +1293,16 @@ export const deleteSession = async (sessionUuid: string, chatKey: string) => {}const db = await chatDb();- const now = nowMicros();+ const messages = await db.getAll("messages");const tx = db.transaction(["sessions", "messages"], "readwrite");-const sessionStore = tx.objectStore("sessions");- const session = await sessionStore.get(sessionUuid);- if (session) {- session.deletedAt = now;- session.needsSync = true;- await sessionStore.put(session);- }-const messageStore = tx.objectStore("messages");- const messages = await messageStore.getAll();- await Promise.all(- messages+ await Promise.all([+ sessionStore.delete(sessionUuid),+ ...messages.filter((message) => message.sessionUuid === sessionUuid)- .map((message) => {- message.deletedAt = now;- return messageStore.put(message);- }),- );+ .map((message) => messageStore.delete(message.messageUuid)),+ ]);await tx.done;await deleteBranchSelections(sessionUuid);@@ -1404,9 +1387,9 @@ export const readDecryptedAttachmentBytes = async (return await decryptAttachmentBytes(encrypted, chatKey, sessionUuid);} catch (error) {for (const fallbackKey of [- legacyAttachmentChatKey(),+ v1AttachmentChatKey(),cachedLocalChatKey(),- legacyLocalChatKey(),+ v1LocalChatKey(),]) {if (!fallbackKey || fallbackKey === chatKey) continue;try {@@ -1416,7 +1399,7 @@ export const readDecryptedAttachmentBytes = async (sessionUuid,);} catch {- // Try the next known legacy key.+ // Try the next v1 key.}}throw error;