Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

update common packages

Prateek Sunalaf15ebfcb779
diff --git a/rust/llmchat-db/src/attachments_db.rs b/rust/llmchat-db/src/attachments_db.rs
new file mode 100644
index 0000000000..f67303c987
--- /dev/null
+++ b/rust/llmchat-db/src/attachments_db.rs
@@ -0,0 +1,318 @@
+use std::sync::Arc;
+
+use uuid::Uuid;
+
+use crate::backend::{Backend, RowExt, Value};
+use crate::traits::{Clock, SystemClock};
+use crate::{Result};
+
+#[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::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::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 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> {
+ crate::attachments_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, upload_state, uploaded_at, updated_at) \
+ VALUES (?, ?, ?, ?, 'pending', NULL, ?) \
+ ON CONFLICT(attachment_id) DO UPDATE SET \
+ session_uuid = excluded.session_uuid, \
+ message_uuid = excluded.message_uuid, \
+ size = excluded.size, \
+ 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 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 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,
+ state: UploadState,
+ ) -> Result<()> {
+ let now = self.clock.now_us();
+ let uploaded_at = if state == UploadState::Uploaded {
+ Value::Integer(now)
+ } else {
+ Value::Null
+ };
+ self.backend.execute(
+ "INSERT INTO attachments (attachment_id, session_uuid, message_uuid, size, 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, \
+ 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),
+ 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, 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_pending_uploads_for_message(
+ &self,
+ message_uuid: Uuid,
+ ) -> Result<Vec<AttachmentUploadRow>> {
+ let rows = self.backend.query(
+ "SELECT attachment_id, session_uuid, message_uuid, size, 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::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 upload_state: UploadState = row.get_string(4)?.parse()?;
+ let uploaded_at = row.get_optional_i64(5)?;
+ let updated_at = row.get_i64(6)?;
+ Ok(AttachmentUploadRow {
+ attachment_id,
+ session_uuid,
+ message_uuid,
+ size,
+ upload_state,
+ uploaded_at,
+ updated_at,
+ })
+ }
+}
+
+#[cfg(feature = "sqlite")]
+impl AttachmentsDb<crate::backend::sqlite::SqliteBackend> {
+ pub fn open_sqlite(
+ path: impl AsRef<std::path::Path>,
+ clock: Arc<dyn Clock>,
+ ) -> Result<Self> {
+ let backend = crate::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::backend::sqlite::SqliteBackend::open(path)?;
+ Self::new_with_defaults(backend)
+ }
+
+ pub fn open_in_memory(clock: Arc<dyn Clock>) -> Result<Self> {
+ let backend = crate::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::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/llmchat-db/src/attachments_migrations.rs b/rust/llmchat-db/src/attachments_migrations.rs
new file mode 100644
index 0000000000..ae6d3e0b0c
--- /dev/null
+++ b/rust/llmchat-db/src/attachments_migrations.rs
@@ -0,0 +1,66 @@
+use crate::{Backend, Error, Result};
+use crate::backend::RowExt;
+use crate::attachments_schema;
+
+pub const LATEST_VERSION: i64 = 1;
+
+pub fn migrate<B: Backend>(backend: &B) -> Result<()> {
+ let version = user_version(backend)?;
+ match version {
+ 0 => {
+ backend.execute_batch(attachments_schema::CREATE_ALL)?;
+ backend.execute("PRAGMA user_version = 1;", &[])?;
+ 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::backend::{BackendTx, RowExt, Value};
+ use crate::backend::sqlite::SqliteBackend;
+
+ #[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/llmchat-db/src/attachments_schema.rs b/rust/llmchat-db/src/attachments_schema.rs
new file mode 100644
index 0000000000..f4a255c7c2
--- /dev/null
+++ b/rust/llmchat-db/src/attachments_schema.rs
@@ -0,0 +1,33 @@
+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,
+ 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,
+ 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/llmchat-db/src/db.rs b/rust/llmchat-db/src/db.rs
index c182ad37cf..4e63a20bbb 100644
--- a/rust/llmchat-db/src/db.rs
+++ b/rust/llmchat-db/src/db.rs
@@ -6,7 +6,7 @@ use zeroize::Zeroizing;
use crate::backend::{Backend, BackendTx, RowExt, Value};
use crate::crypto;
use crate::migrations;
-use crate::models::{Attachment, EntityType, Message, Sender, Session, StoredAttachment};
+use crate::models::{AttachmentMeta, EntityType, Message, Sender, Session, StoredAttachment};
use crate::traits::{Clock, RandomUuidGen, SystemClock, UuidGen};
use crate::{Error, Result};
@@ -141,7 +141,7 @@ impl<B: Backend> ChatDb<B> {
sender: &str,
text: &str,
parent: Option<Uuid>,
- attachments: Vec<Attachment>,
+ attachments: Vec<AttachmentMeta>,
) -> Result<Message> {
let sender: Sender = sender.parse()?;
let now = self.clock.now_us();
@@ -240,78 +240,125 @@ impl<B: Backend> ChatDb<B> {
})
}
- pub fn mark_attachment_uploaded(&self, message_uuid: Uuid, attachment_id: &str) -> Result<()> {
- let now = self.clock.now_us();
- let row = self.backend.query_row(
- "SELECT attachments FROM messages WHERE message_uuid = ? AND deleted_at IS NULL",
- &[Value::Text(message_uuid.to_string())],
+ 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()),
+ ],
)?;
- let row = row.ok_or(Error::NotFound {
- entity: EntityType::Message,
- id: message_uuid,
- })?;
-
- let attachments_json = row.get_optional_string(0)?;
- let mut stored = parse_stored_attachments(attachments_json)?;
- let mut found = false;
- for attachment in &mut stored {
- if attachment.id == attachment_id {
- if attachment.uploaded_at.is_none() {
- attachment.uploaded_at = Some(now);
- }
- found = true;
- break;
- }
- }
-
- if !found {
- return Err(Error::AttachmentNotFound(attachment_id.to_string()));
- }
-
- let updated_json = if stored.is_empty() {
- None
- } else {
- Some(serde_json::to_string(&stored)?)
- };
+ ensure_row_updated(affected, EntityType::Session, uuid)
+ }
+ pub fn upsert_session_from_remote(
+ &self,
+ session_uuid: Uuid,
+ title: &str,
+ created_at: i64,
+ updated_at: i64,
+ ) -> Result<Session> {
+ let encrypted_title = crypto::encrypt_string(title, &self.key)?;
self.backend.execute(
- "UPDATE messages SET attachments = ? WHERE message_uuid = ?",
+ "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 = excluded.title, \
+ 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",
&[
- updated_json.map(Value::Text).unwrap_or(Value::Null),
- Value::Text(message_uuid.to_string()),
+ Value::Text(session_uuid.to_string()),
+ Value::Blob(encrypted_title),
+ Value::Integer(created_at),
+ Value::Integer(updated_at),
+ Value::Text(session_uuid.to_string()),
],
)?;
- Ok(())
+ let session = self.get_session(session_uuid)?.ok_or(Error::NotFound {
+ entity: EntityType::Session,
+ id: session_uuid,
+ })?;
+ Ok(session)
}
- pub fn get_pending_uploads(&self, session_uuid: Uuid) -> Result<Vec<Attachment>> {
- let rows = self.backend.query(
- "SELECT attachments FROM messages WHERE session_uuid = ? AND deleted_at IS NULL",
- &[Value::Text(session_uuid.to_string())],
+ 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(())
+ })
+ }
+
+ pub fn upsert_message_from_remote(
+ &self,
+ message_uuid: Uuid,
+ session_uuid: Uuid,
+ 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, deleted_at) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, 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), \
+ 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),
+ ],
)?;
- let mut pending = Vec::new();
- for row in rows {
- let attachments_json = row.get_optional_string(0)?;
- let stored = parse_stored_attachments(attachments_json)?;
- for attachment in stored.into_iter().filter(|att| att.uploaded_at.is_none()) {
- pending.push(self.stored_to_attachment(attachment)?);
- }
- }
+ let _ = self.touch_session_remote(session_uuid, created_at);
- Ok(pending)
+ Ok(Message {
+ uuid: message_uuid,
+ session_uuid,
+ parent_message_uuid: parent,
+ sender,
+ text: text.to_string(),
+ attachments,
+ created_at,
+ deleted_at: None,
+ })
}
- 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()),
- ],
+ 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())],
)?;
- ensure_row_updated(affected, EntityType::Session, uuid)
+ Ok(())
}
pub fn get_pending_deletions(&self) -> Result<Vec<(EntityType, Uuid)>> {
@@ -410,7 +457,7 @@ impl<B: Backend> ChatDb<B> {
})
}
- fn serialize_attachments(&self, attachments: &[Attachment]) -> Result<Option<String>> {
+ fn serialize_attachments(&self, attachments: &[AttachmentMeta]) -> Result<Option<String>> {
if attachments.is_empty() {
return Ok(None);
}
@@ -421,7 +468,7 @@ impl<B: Backend> ChatDb<B> {
Ok(Some(serde_json::to_string(&stored)?))
}
- fn deserialize_attachments(&self, raw: Option<String>) -> Result<Vec<Attachment>> {
+ fn deserialize_attachments(&self, raw: Option<String>) -> Result<Vec<AttachmentMeta>> {
let stored = parse_stored_attachments(raw)?;
stored
.into_iter()
@@ -429,23 +476,21 @@ impl<B: Backend> ChatDb<B> {
.collect()
}
- fn attachment_to_stored(&self, attachment: &Attachment) -> Result<StoredAttachment> {
+ 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)?,
- uploaded_at: attachment.uploaded_at,
})
}
- fn stored_to_attachment(&self, attachment: StoredAttachment) -> Result<Attachment> {
- Ok(Attachment {
+ 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)?,
- uploaded_at: attachment.uploaded_at,
})
}
@@ -461,6 +506,14 @@ impl<B: Backend> ChatDb<B> {
)?;
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())],
+ )?;
+ ensure_row_updated(affected, EntityType::Session, session_uuid)
+ }
}
#[cfg(feature = "sqlite")]
@@ -536,7 +589,7 @@ mod tests {
use crate::backend::{BackendTx, RowExt, Value};
use crate::backend::sqlite::SqliteBackend;
use crate::crypto::KEY_BYTES;
- use crate::models::{Attachment, AttachmentKind};
+ use crate::models::{AttachmentMeta, AttachmentKind};
#[derive(Debug)]
struct StepClock {
@@ -669,7 +722,7 @@ mod tests {
}
#[test]
- fn attachment_upload_flow_does_not_touch_session() {
+ 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));
@@ -678,37 +731,23 @@ mod tests {
db.create_session("title").unwrap();
let attachments = vec![
- Attachment {
+ AttachmentMeta {
id: "att-1".to_string(),
kind: AttachmentKind::Image,
size: 123,
name: "photo.jpg".to_string(),
- uploaded_at: None,
},
- Attachment {
+ AttachmentMeta {
id: "att-2".to_string(),
kind: AttachmentKind::Document,
size: 456,
name: "doc.pdf".to_string(),
- uploaded_at: None,
},
];
db.insert_message(session_id, "self", "hello", None, attachments)
.unwrap();
- let updated_at_before = db.get_session(session_id).unwrap().unwrap().updated_at;
-
- let pending = db.get_pending_uploads(session_id).unwrap();
- assert_eq!(pending.len(), 2);
-
- db.mark_attachment_uploaded(message_id, "att-1").unwrap();
- let pending_after = db.get_pending_uploads(session_id).unwrap();
- assert_eq!(pending_after.len(), 1);
-
- let updated_at_after = db.get_session(session_id).unwrap().unwrap().updated_at;
- assert_eq!(updated_at_before, updated_at_after);
-
let row = db
.backend
.query_row(
@@ -719,6 +758,7 @@ mod tests {
.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);
assert!(stored[0].encrypted_name.starts_with("enc:v1:"));
assert!(!stored[0].encrypted_name.contains("photo.jpg"));
}
diff --git a/rust/llmchat-db/src/error.rs b/rust/llmchat-db/src/error.rs
index a7a5f94dee..15604244e6 100644
--- a/rust/llmchat-db/src/error.rs
+++ b/rust/llmchat-db/src/error.rs
@@ -27,8 +27,6 @@ pub enum Error {
#[error("{entity:?} not found: {id}")]
NotFound { entity: EntityType, id: uuid::Uuid },
- #[error("attachment not found: {0}")]
- AttachmentNotFound(String),
#[error(transparent)]
Crypto(#[from] ente_core::crypto::CryptoError),
diff --git a/rust/llmchat-db/src/lib.rs b/rust/llmchat-db/src/lib.rs
index c2661eabfd..d3cbb61ae3 100644
--- a/rust/llmchat-db/src/lib.rs
+++ b/rust/llmchat-db/src/lib.rs
@@ -3,17 +3,23 @@
pub mod backend;
pub mod crypto;
pub mod db;
+pub mod attachments_db;
+pub mod attachments_migrations;
+pub mod attachments_schema;
pub mod error;
pub mod migrations;
pub mod models;
pub mod schema;
pub mod traits;
+pub mod llmchat;
pub use crate::backend::{Backend, BackendTx, Row, Value};
pub use crate::db::ChatDb;
+pub use crate::attachments_db::{AttachmentsDb, AttachmentUploadRow, UploadState};
+pub use crate::llmchat::LlmChatDb;
pub use crate::error::{Error, Result};
pub use crate::models::{
- Attachment, AttachmentKind, EntityType, Message, Sender, Session,
+ AttachmentKind, AttachmentMeta, EntityType, Message, Sender, Session,
};
pub use crate::traits::{
AttachmentStore, Clock, FileMetaStore, FsAttachmentStore, MetaStore, RandomUuidGen,
diff --git a/rust/llmchat-db/src/llmchat.rs b/rust/llmchat-db/src/llmchat.rs
new file mode 100644
index 0000000000..b282014cc5
--- /dev/null
+++ b/rust/llmchat-db/src/llmchat.rs
@@ -0,0 +1,223 @@
+use std::sync::Arc;
+
+use uuid::Uuid;
+
+use crate::attachments_db::{AttachmentUploadRow, AttachmentsDb, UploadState};
+use crate::db::ChatDb;
+use crate::models::{AttachmentMeta, EntityType, Message, Session};
+use crate::traits::{Clock, UuidGen};
+use crate::Result;
+
+/// High-level DB that ties together the main chat DB and the attachments upload-state DB.
+pub struct LlmChatDb<B: crate::Backend> {
+ pub chat: ChatDb<B>,
+ pub attachments: AttachmentsDb<B>,
+}
+
+impl<B: crate::Backend> LlmChatDb<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 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)
+ }
+
+ 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)
+ }
+
+ pub fn get_messages(&self, session_uuid: Uuid) -> Result<Vec<Message>> {
+ self.chat.get_messages(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 mark_attachment_uploaded(&self, attachment_id: &str) -> Result<()> {
+ self.attachments.mark_attachment_uploaded(attachment_id)
+ }
+
+ 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 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)
+ }
+
+ // Sync helpers
+ pub fn mark_session_synced(&self, uuid: Uuid, remote_id: &str) -> Result<()> {
+ self.chat.mark_session_synced(uuid, remote_id)
+ }
+
+ pub fn get_sessions_needing_sync(&self) -> Result<Vec<Session>> {
+ self.chat.get_sessions_needing_sync()
+ }
+
+ pub fn get_pending_deletions(&self) -> Result<Vec<(EntityType, Uuid)>> {
+ self.chat.get_pending_deletions()
+ }
+
+ pub fn hard_delete(&self, entity_type: EntityType, uuid: Uuid) -> Result<()> {
+ self.chat.hard_delete(entity_type, uuid)
+ }
+
+ // Sync apply helpers
+ pub fn upsert_session_from_remote(
+ &self,
+ session_uuid: Uuid,
+ title: &str,
+ created_at: i64,
+ updated_at: i64,
+ ) -> Result<Session> {
+ self.chat
+ .upsert_session_from_remote(session_uuid, title, created_at, updated_at)
+ }
+
+ pub fn apply_session_tombstone(&self, session_uuid: Uuid, deleted_at: i64) -> Result<()> {
+ self.chat.apply_session_tombstone(session_uuid, deleted_at)
+ }
+
+ pub fn upsert_message_from_remote(
+ &self,
+ message_uuid: Uuid,
+ session_uuid: Uuid,
+ 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,
+ 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,
+ state: UploadState,
+ ) -> Result<()> {
+ self.attachments
+ .upsert_attachment_with_state(attachment_id, session_uuid, message_uuid, size, state)
+ }
+
+ pub fn get_attachment_upload_state(&self, attachment_id: &str) -> Result<Option<UploadState>> {
+ self.attachments.get_upload_state(attachment_id)
+ }
+}
+
+#[cfg(feature = "sqlite")]
+impl LlmChatDb<crate::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/llmchat-db/src/models.rs b/rust/llmchat-db/src/models.rs
index 7ab7962865..3842545a68 100644
--- a/rust/llmchat-db/src/models.rs
+++ b/rust/llmchat-db/src/models.rs
@@ -19,24 +19,17 @@ pub struct Message {
pub parent_message_uuid: Option<Uuid>,
pub sender: Sender,
pub text: String,
- pub attachments: Vec<Attachment>,
+ pub attachments: Vec<AttachmentMeta>,
pub created_at: i64,
pub deleted_at: Option<i64>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct Attachment {
+pub struct AttachmentMeta {
pub id: String,
pub kind: AttachmentKind,
pub size: i64,
pub name: String,
- pub uploaded_at: Option<i64>,
-}
-
-impl Attachment {
- pub fn needs_upload(&self) -> bool {
- self.uploaded_at.is_none()
- }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -85,6 +78,4 @@ pub(crate) struct StoredAttachment {
pub kind: AttachmentKind,
pub size: i64,
pub encrypted_name: String,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub uploaded_at: Option<i64>,
}
diff --git a/rust/llmchat-db/src/traits.rs b/rust/llmchat-db/src/traits.rs
index f716ae7357..31f62bdcbd 100644
--- a/rust/llmchat-db/src/traits.rs
+++ b/rust/llmchat-db/src/traits.rs
@@ -110,6 +110,11 @@ impl FsAttachmentStore {
Self { root: root.into() }
}
+ pub fn size(&self, id: &str) -> Result<u64> {
+ let path = self.attachment_path(id);
+ Ok(fs::metadata(path)?.len())
+ }
+
fn attachment_path(&self, id: &str) -> PathBuf {
self.root.join(id)
}
diff --git a/rust/llmchat-sync/Cargo.lock b/rust/llmchat-sync/Cargo.lock
new file mode 100644
index 0000000000..f436820728
--- /dev/null
+++ b/rust/llmchat-sync/Cargo.lock
@@ -0,0 +1,2160 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "aead"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
+dependencies = [
+ "crypto-common",
+ "generic-array",
+]
+
+[[package]]
+name = "argon2"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
+dependencies = [
+ "base64ct",
+ "blake2",
+ "cpufeatures",
+ "password-hash",
+]
+
+[[package]]
+name = "arrayref"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"
+
+[[package]]
+name = "arrayvec"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
+
+[[package]]
+name = "atomic-waker"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+
+[[package]]
+name = "base64"
+version = "0.22.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+
+[[package]]
+name = "base64ct"
+version = "1.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
+
+[[package]]
+name = "bitflags"
+version = "2.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"
+
+[[package]]
+name = "blake2"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
+dependencies = [
+ "digest",
+]
+
+[[package]]
+name = "blake2b_simd"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b79834656f71332577234b50bfc009996f7449e0c056884e6a02492ded0ca2f3"
+dependencies = [
+ "arrayref",
+ "arrayvec",
+ "constant_time_eq",
+]
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "block-padding"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "bumpalo"
+version = "3.19.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510"
+
+[[package]]
+name = "bytes"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b35204fbdc0b3f4446b89fc1ac2cf84a8a68971995d0bf2e925ec7cd960f9cb3"
+
+[[package]]
+name = "cc"
+version = "1.2.53"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "755d2fce177175ffca841e9a06afdb2c4ab0f593d53b4dee48147dfaade85932"
+dependencies = [
+ "find-msvc-tools",
+ "shlex",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "cfg_aliases"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
+
+[[package]]
+name = "chacha20"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
+dependencies = [
+ "cfg-if",
+ "cipher",
+ "cpufeatures",
+]
+
+[[package]]
+name = "cipher"
+version = "0.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
+dependencies = [
+ "crypto-common",
+ "inout",
+ "zeroize",
+]
+
+[[package]]
+name = "constant_time_eq"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
+
+[[package]]
+name = "core-foundation"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "core-foundation"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "core-foundation-sys"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "rand_core 0.6.4",
+ "typenum",
+]
+
+[[package]]
+name = "crypto_secretstream"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a6419214057ad50a13efccb3ad7714b86b848e3a5aa7b6cf5a3ff07edf387eb"
+dependencies = [
+ "aead",
+ "chacha20",
+ "getrandom 0.2.17",
+ "poly1305",
+ "rand_core 0.6.4",
+ "subtle",
+]
+
+[[package]]
+name = "curve25519-dalek"
+version = "4.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "curve25519-dalek-derive",
+ "fiat-crypto",
+ "rustc_version",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "curve25519-dalek-derive"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+ "subtle",
+]
+
+[[package]]
+name = "displaydoc"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "encoding_rs"
+version = "0.8.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "ente-core"
+version = "0.0.1"
+dependencies = [
+ "argon2",
+ "base64",
+ "blake2b_simd",
+ "crypto_secretstream",
+ "getrandom 0.2.17",
+ "hex",
+ "md-5",
+ "rand_core 0.6.4",
+ "reqwest",
+ "salsa20",
+ "serde",
+ "serde_json",
+ "subtle",
+ "thiserror",
+ "x25519-dalek",
+ "xsalsa20poly1305",
+ "zeroize",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "fallible-iterator"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
+
+[[package]]
+name = "fallible-streaming-iterator"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
+
+[[package]]
+name = "fastrand"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
+
+[[package]]
+name = "fiat-crypto"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8591b0bcc8a98a64310a2fae1bb3e9b8564dd10e381e6e28010fde8e8e8568db"
+
+[[package]]
+name = "fnv"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+
+[[package]]
+name = "foldhash"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+
+[[package]]
+name = "form_urlencoded"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
+dependencies = [
+ "percent-encoding",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"
+
+[[package]]
+name = "futures-io"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6"
+
+[[package]]
+name = "futures-sink"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7"
+
+[[package]]
+name = "futures-task"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988"
+
+[[package]]
+name = "futures-util"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"
+dependencies = [
+ "futures-core",
+ "futures-io",
+ "futures-sink",
+ "futures-task",
+ "memchr",
+ "pin-project-lite",
+ "pin-utils",
+ "slab",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "libc",
+ "wasi",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "libc",
+ "r-efi",
+ "wasip2",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "h2"
+version = "0.4.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "fnv",
+ "futures-core",
+ "futures-sink",
+ "http",
+ "indexmap",
+ "slab",
+ "tokio",
+ "tokio-util",
+ "tracing",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+dependencies = [
+ "foldhash",
+]
+
+[[package]]
+name = "hashlink"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea0b22561a9c04a7cb1a302c013e0259cd3b4bb619f145b32f72b8b4bcbed230"
+dependencies = [
+ "hashbrown",
+]
+
+[[package]]
+name = "hex"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+
+[[package]]
+name = "hkdf"
+version = "0.12.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
+dependencies = [
+ "hmac",
+]
+
+[[package]]
+name = "hmac"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
+dependencies = [
+ "digest",
+]
+
+[[package]]
+name = "http"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a"
+dependencies = [
+ "bytes",
+ "itoa",
+]
+
+[[package]]
+name = "http-body"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"
+dependencies = [
+ "bytes",
+ "http",
+]
+
+[[package]]
+name = "http-body-util"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "httparse"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+
+[[package]]
+name = "hyper"
+version = "1.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "h2",
+ "http",
+ "http-body",
+ "httparse",
+ "itoa",
+ "pin-project-lite",
+ "pin-utils",
+ "smallvec",
+ "tokio",
+ "want",
+]
+
+[[package]]
+name = "hyper-rustls"
+version = "0.27.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58"
+dependencies = [
+ "http",
+ "hyper",
+ "hyper-util",
+ "rustls",
+ "rustls-native-certs",
+ "rustls-pki-types",
+ "tokio",
+ "tokio-rustls",
+ "tower-service",
+]
+
+[[package]]
+name = "hyper-util"
+version = "0.1.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "727805d60e7938b76b826a6ef209eb70eaa1812794f9424d4a4e2d740662df5f"
+dependencies = [
+ "base64",
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "futures-util",
+ "http",
+ "http-body",
+ "hyper",
+ "ipnet",
+ "libc",
+ "percent-encoding",
+ "pin-project-lite",
+ "socket2",
+ "system-configuration",
+ "tokio",
+ "tower-service",
+ "tracing",
+ "windows-registry",
+]
+
+[[package]]
+name = "icu_collections"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43"
+dependencies = [
+ "displaydoc",
+ "potential_utf",
+ "yoke",
+ "zerofrom",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locale_core"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6"
+dependencies = [
+ "displaydoc",
+ "litemap",
+ "tinystr",
+ "writeable",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599"
+dependencies = [
+ "icu_collections",
+ "icu_normalizer_data",
+ "icu_properties",
+ "icu_provider",
+ "smallvec",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer_data"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a"
+
+[[package]]
+name = "icu_properties"
+version = "2.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec"
+dependencies = [
+ "icu_collections",
+ "icu_locale_core",
+ "icu_properties_data",
+ "icu_provider",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_properties_data"
+version = "2.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af"
+
+[[package]]
+name = "icu_provider"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614"
+dependencies = [
+ "displaydoc",
+ "icu_locale_core",
+ "writeable",
+ "yoke",
+ "zerofrom",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "idna"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
+dependencies = [
+ "idna_adapter",
+ "smallvec",
+ "utf8_iter",
+]
+
+[[package]]
+name = "idna_adapter"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344"
+dependencies = [
+ "icu_normalizer",
+ "icu_properties",
+]
+
+[[package]]
+name = "indexmap"
+version = "2.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"
+dependencies = [
+ "equivalent",
+ "hashbrown",
+]
+
+[[package]]
+name = "inout"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
+dependencies = [
+ "block-padding",
+ "generic-array",
+]
+
+[[package]]
+name = "ipnet"
+version = "2.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"
+
+[[package]]
+name = "iri-string"
+version = "0.7.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c91338f0783edbd6195decb37bae672fd3b165faffb89bf7b9e6942f8b1a731a"
+dependencies = [
+ "memchr",
+ "serde",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
+
+[[package]]
+name = "js-sys"
+version = "0.3.85"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8c942ebf8e95485ca0d52d97da7c5a2c387d0e7f0ba4c35e93bfcaee045955b3"
+dependencies = [
+ "once_cell",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.180"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bcc35a38544a891a5f7c865aca548a982ccb3b8650a5b06d0fd33a10283c56fc"
+
+[[package]]
+name = "libsqlite3-sys"
+version = "0.36.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95b4103cffefa72eb8428cb6b47d6627161e51c2739fc5e3b734584157bc642a"
+dependencies = [
+ "cc",
+ "pkg-config",
+ "vcpkg",
+]
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"
+
+[[package]]
+name = "litemap"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77"
+
+[[package]]
+name = "llmchat-db"
+version = "0.1.0"
+dependencies = [
+ "ente-core",
+ "rusqlite",
+ "serde",
+ "serde_json",
+ "thiserror",
+ "uuid",
+ "zeroize",
+]
+
+[[package]]
+name = "llmchat-sync"
+version = "0.1.0"
+dependencies = [
+ "ente-core",
+ "hkdf",
+ "llmchat-db",
+ "reqwest",
+ "serde",
+ "serde_json",
+ "sha2",
+ "tempfile",
+ "thiserror",
+ "uuid",
+]
+
+[[package]]
+name = "log"
+version = "0.4.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
+
+[[package]]
+name = "lru-slab"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
+
+[[package]]
+name = "md-5"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
+dependencies = [
+ "cfg-if",
+ "digest",
+]
+
+[[package]]
+name = "memchr"
+version = "2.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"
+
+[[package]]
+name = "mime"
+version = "0.3.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
+
+[[package]]
+name = "mio"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc"
+dependencies = [
+ "libc",
+ "wasi",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
+
+[[package]]
+name = "opaque-debug"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
+
+[[package]]
+name = "openssl-probe"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
+
+[[package]]
+name = "password-hash"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
+dependencies = [
+ "base64ct",
+ "rand_core 0.6.4",
+ "subtle",
+]
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
+
+[[package]]
+name = "pin-utils"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
+
+[[package]]
+name = "pkg-config"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
+
+[[package]]
+name = "poly1305"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
+dependencies = [
+ "cpufeatures",
+ "opaque-debug",
+ "universal-hash",
+]
+
+[[package]]
+name = "potential_utf"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77"
+dependencies = [
+ "zerovec",
+]
+
+[[package]]
+name = "ppv-lite86"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
+dependencies = [
+ "zerocopy",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.105"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "535d180e0ecab6268a3e718bb9fd44db66bbbc256257165fc699dadf70d16fe7"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quinn"
+version = "0.11.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"
+dependencies = [
+ "bytes",
+ "cfg_aliases",
+ "pin-project-lite",
+ "quinn-proto",
+ "quinn-udp",
+ "rustc-hash",
+ "rustls",
+ "socket2",
+ "thiserror",
+ "tokio",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-proto"
+version = "0.11.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31"
+dependencies = [
+ "bytes",
+ "getrandom 0.3.4",
+ "lru-slab",
+ "rand",
+ "ring",
+ "rustc-hash",
+ "rustls",
+ "rustls-pki-types",
+ "slab",
+ "thiserror",
+ "tinyvec",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-udp"
+version = "0.5.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
+dependencies = [
+ "cfg_aliases",
+ "libc",
+ "once_cell",
+ "socket2",
+ "tracing",
+ "windows-sys 0.60.2",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.43"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc74d9a594b72ae6656596548f56f667211f8a97b3d4c3d467150794690dc40a"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
+[[package]]
+name = "rand"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
+dependencies = [
+ "rand_chacha",
+ "rand_core 0.9.5",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
+dependencies = [
+ "ppv-lite86",
+ "rand_core 0.9.5",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
+dependencies = [
+ "getrandom 0.2.17",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
+dependencies = [
+ "getrandom 0.3.4",
+]
+
+[[package]]
+name = "reqwest"
+version = "0.12.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
+dependencies = [
+ "base64",
+ "bytes",
+ "encoding_rs",
+ "futures-channel",
+ "futures-core",
+ "futures-util",
+ "h2",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-rustls",
+ "hyper-util",
+ "js-sys",
+ "log",
+ "mime",
+ "percent-encoding",
+ "pin-project-lite",
+ "quinn",
+ "rustls",
+ "rustls-native-certs",
+ "rustls-pki-types",
+ "serde",
+ "serde_json",
+ "serde_urlencoded",
+ "sync_wrapper",
+ "tokio",
+ "tokio-rustls",
+ "tower",
+ "tower-http",
+ "tower-service",
+ "url",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+]
+
+[[package]]
+name = "ring"
+version = "0.17.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
+dependencies = [
+ "cc",
+ "cfg-if",
+ "getrandom 0.2.17",
+ "libc",
+ "untrusted",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "rsqlite-vfs"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8a1f2315036ef6b1fbacd1972e8ee7688030b0a2121edfc2a6550febd41574d"
+dependencies = [
+ "hashbrown",
+ "thiserror",
+]
+
+[[package]]
+name = "rusqlite"
+version = "0.38.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1c93dd1c9683b438c392c492109cb702b8090b2bfc8fed6f6e4eb4523f17af3"
+dependencies = [
+ "bitflags",
+ "fallible-iterator",
+ "fallible-streaming-iterator",
+ "hashlink",
+ "libsqlite3-sys",
+ "smallvec",
+ "sqlite-wasm-rs",
+]
+
+[[package]]
+name = "rustc-hash"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
+
+[[package]]
+name = "rustc_version"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
+dependencies = [
+ "semver",
+]
+
+[[package]]
+name = "rustix"
+version = "1.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustls"
+version = "0.23.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c665f33d38cea657d9614f766881e4d510e0eda4239891eea56b4cadcf01801b"
+dependencies = [
+ "once_cell",
+ "ring",
+ "rustls-pki-types",
+ "rustls-webpki",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-native-certs"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63"
+dependencies = [
+ "openssl-probe",
+ "rustls-pki-types",
+ "schannel",
+ "security-framework",
+]
+
+[[package]]
+name = "rustls-pki-types"
+version = "1.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"
+dependencies = [
+ "web-time",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-webpki"
+version = "0.103.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53"
+dependencies = [
+ "ring",
+ "rustls-pki-types",
+ "untrusted",
+]
+
+[[package]]
+name = "rustversion"
+version = "1.0.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
+
+[[package]]
+name = "ryu"
+version = "1.0.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a50f4cf475b65d88e057964e0e9bb1f0aa9bbb2036dc65c64596b42932536984"
+
+[[package]]
+name = "salsa20"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213"
+dependencies = [
+ "cipher",
+]
+
+[[package]]
+name = "schannel"
+version = "0.1.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "891d81b926048e76efe18581bf793546b4c0eaf8448d72be8de2bbee5fd166e1"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "security-framework"
+version = "3.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b3297343eaf830f66ede390ea39da1d462b6b0c1b000f420d0a83f898bbbe6ef"
+dependencies = [
+ "bitflags",
+ "core-foundation 0.10.1",
+ "core-foundation-sys",
+ "libc",
+ "security-framework-sys",
+]
+
+[[package]]
+name = "security-framework-sys"
+version = "2.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc1f0cbffaac4852523ce30d8bd3c5cdc873501d96ff467ca09b6767bb8cd5c0"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "semver"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
+
+[[package]]
+name = "serde"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.149"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "serde_urlencoded"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
+dependencies = [
+ "form_urlencoded",
+ "itoa",
+ "ryu",
+ "serde",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "shlex"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
+
+[[package]]
+name = "slab"
+version = "0.4.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589"
+
+[[package]]
+name = "smallvec"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
+
+[[package]]
+name = "socket2"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881"
+dependencies = [
+ "libc",
+ "windows-sys 0.60.2",
+]
+
+[[package]]
+name = "sqlite-wasm-rs"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f4206ed3a67690b9c29b77d728f6acc3ce78f16bf846d83c94f76400320181b"
+dependencies = [
+ "cc",
+ "js-sys",
+ "rsqlite-vfs",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
+[[package]]
+name = "syn"
+version = "2.0.114"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "sync_wrapper"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "synstructure"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "system-configuration"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b"
+dependencies = [
+ "bitflags",
+ "core-foundation 0.9.4",
+ "system-configuration-sys",
+]
+
+[[package]]
+name = "system-configuration-sys"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "tempfile"
+version = "3.24.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "655da9c7eb6305c55742045d5a8d2037996d61d8de95806335c7c86ce0f82e9c"
+dependencies = [
+ "fastrand",
+ "getrandom 0.3.4",
+ "once_cell",
+ "rustix",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tinystr"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869"
+dependencies = [
+ "displaydoc",
+ "zerovec",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa"
+dependencies = [
+ "tinyvec_macros",
+]
+
+[[package]]
+name = "tinyvec_macros"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
+
+[[package]]
+name = "tokio"
+version = "1.49.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86"
+dependencies = [
+ "bytes",
+ "libc",
+ "mio",
+ "pin-project-lite",
+ "socket2",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "tokio-rustls"
+version = "0.26.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"
+dependencies = [
+ "rustls",
+ "tokio",
+]
+
+[[package]]
+name = "tokio-util"
+version = "0.7.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "futures-sink",
+ "pin-project-lite",
+ "tokio",
+]
+
+[[package]]
+name = "tower"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
+dependencies = [
+ "futures-core",
+ "futures-util",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tokio",
+ "tower-layer",
+ "tower-service",
+]
+
+[[package]]
+name = "tower-http"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8"
+dependencies = [
+ "bitflags",
+ "bytes",
+ "futures-util",
+ "http",
+ "http-body",
+ "iri-string",
+ "pin-project-lite",
+ "tower",
+ "tower-layer",
+ "tower-service",
+]
+
+[[package]]
+name = "tower-layer"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
+
+[[package]]
+name = "tower-service"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
+
+[[package]]
+name = "tracing"
+version = "0.1.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
+dependencies = [
+ "pin-project-lite",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
+dependencies = [
+ "once_cell",
+]
+
+[[package]]
+name = "try-lock"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+
+[[package]]
+name = "typenum"
+version = "1.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"
+
+[[package]]
+name = "universal-hash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
+dependencies = [
+ "crypto-common",
+ "subtle",
+]
+
+[[package]]
+name = "untrusted"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
+
+[[package]]
+name = "url"
+version = "2.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
+dependencies = [
+ "form_urlencoded",
+ "idna",
+ "percent-encoding",
+ "serde",
+]
+
+[[package]]
+name = "utf8_iter"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+
+[[package]]
+name = "uuid"
+version = "1.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e2e054861b4bd027cd373e18e8d8d8e6548085000e41290d95ce0c373a654b4a"
+dependencies = [
+ "getrandom 0.3.4",
+ "js-sys",
+ "uuid-rng-internal",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "uuid-rng-internal"
+version = "1.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d0021aebf9af0cbec73af2f884a2cd0a41d984c00e42f27baa11856ab480e2c"
+dependencies = [
+ "getrandom 0.3.4",
+]
+
+[[package]]
+name = "vcpkg"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "want"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
+dependencies = [
+ "try-lock",
+]
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "wasip2"
+version = "1.0.2+wasi-0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"
+dependencies = [
+ "wit-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.108"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "64024a30ec1e37399cf85a7ffefebdb72205ca1c972291c51512360d90bd8566"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-futures"
+version = "0.4.58"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "70a6e77fd0ae8029c9ea0063f87c46fde723e7d887703d74ad2616d792e51e6f"
+dependencies = [
+ "cfg-if",
+ "futures-util",
+ "js-sys",
+ "once_cell",
+ "wasm-bindgen",
+ "web-sys",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.108"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "008b239d9c740232e71bd39e8ef6429d27097518b6b30bdf9086833bd5b6d608"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.108"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5256bae2d58f54820e6490f9839c49780dff84c65aeab9e772f15d5f0e913a55"
+dependencies = [
+ "bumpalo",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.108"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1f01b580c9ac74c8d8f0c0e4afb04eeef2acf145458e52c03845ee9cd23e3d12"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "web-sys"
+version = "0.3.85"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "312e32e551d92129218ea9a2452120f4aabc03529ef03e4d0d82fb2780608598"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "web-time"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-registry"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
+dependencies = [
+ "windows-link",
+ "windows-result",
+ "windows-strings",
+]
+
+[[package]]
+name = "windows-result"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-strings"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
+dependencies = [
+ "windows-targets 0.53.5",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm 0.52.6",
+ "windows_aarch64_msvc 0.52.6",
+ "windows_i686_gnu 0.52.6",
+ "windows_i686_gnullvm 0.52.6",
+ "windows_i686_msvc 0.52.6",
+ "windows_x86_64_gnu 0.52.6",
+ "windows_x86_64_gnullvm 0.52.6",
+ "windows_x86_64_msvc 0.52.6",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.53.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
+dependencies = [
+ "windows-link",
+ "windows_aarch64_gnullvm 0.53.1",
+ "windows_aarch64_msvc 0.53.1",
+ "windows_i686_gnu 0.53.1",
+ "windows_i686_gnullvm 0.53.1",
+ "windows_i686_msvc 0.53.1",
+ "windows_x86_64_gnu 0.53.1",
+ "windows_x86_64_gnullvm 0.53.1",
+ "windows_x86_64_msvc 0.53.1",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
+
+[[package]]
+name = "wit-bindgen"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
+
+[[package]]
+name = "writeable"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9"
+
+[[package]]
+name = "x25519-dalek"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
+dependencies = [
+ "curve25519-dalek",
+ "rand_core 0.6.4",
+ "serde",
+ "zeroize",
+]
+
+[[package]]
+name = "xsalsa20poly1305"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "02a6dad357567f81cd78ee75f7c61f1b30bb2fe4390be8fb7c69e2ac8dffb6c7"
+dependencies = [
+ "aead",
+ "poly1305",
+ "salsa20",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "yoke"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954"
+dependencies = [
+ "stable_deref_trait",
+ "yoke-derive",
+ "zerofrom",
+]
+
+[[package]]
+name = "yoke-derive"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "synstructure",
+]
+
+[[package]]
+name = "zerocopy"
+version = "0.8.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "668f5168d10b9ee831de31933dc111a459c97ec93225beb307aed970d1372dfd"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c7962b26b0a8685668b671ee4b54d007a67d4eaf05fda79ac0ecf41e32270f1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "zerofrom"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5"
+dependencies = [
+ "zerofrom-derive",
+]
+
+[[package]]
+name = "zerofrom-derive"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "synstructure",
+]
+
+[[package]]
+name = "zeroize"
+version = "1.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
+dependencies = [
+ "zeroize_derive",
+]
+
+[[package]]
+name = "zeroize_derive"
+version = "1.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "zerotrie"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851"
+dependencies = [
+ "displaydoc",
+ "yoke",
+ "zerofrom",
+]
+
+[[package]]
+name = "zerovec"
+version = "0.11.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002"
+dependencies = [
+ "yoke",
+ "zerofrom",
+ "zerovec-derive",
+]
+
+[[package]]
+name = "zerovec-derive"
+version = "0.11.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "zmij"
+version = "1.0.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dfcd145825aace48cff44a8844de64bf75feec3080e0aa5cdbde72961ae51a65"
diff --git a/rust/llmchat-sync/Cargo.toml b/rust/llmchat-sync/Cargo.toml
new file mode 100644
index 0000000000..781b8d0f00
--- /dev/null
+++ b/rust/llmchat-sync/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "llmchat-sync"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
+llmchat-db = { path = "../llmchat-db" }
+ente-core = { path = "../core" }
+reqwest = { version = "0.12", default-features = false, features = ["json", "blocking", "http2", "charset", "system-proxy", "rustls-tls-native-roots"] }
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+thiserror = "2"
+uuid = { version = "1", features = ["v4", "rng-getrandom"] }
+hkdf = "0.12"
+sha2 = "0.10"
+
+[dev-dependencies]
+tempfile = "3"
diff --git a/rust/llmchat-sync/src/conflict.rs b/rust/llmchat-sync/src/conflict.rs
new file mode 100644
index 0000000000..b294de134d
--- /dev/null
+++ b/rust/llmchat-sync/src/conflict.rs
@@ -0,0 +1,88 @@
+use std::collections::{HashMap, HashSet};
+
+use llmchat_db::{AttachmentMeta, Message, Sender};
+use uuid::Uuid;
+
+pub fn find_duplicate_message(
+ local_messages: &[Message],
+ sender: &Sender,
+ text: &str,
+ attachments: &[AttachmentMeta],
+ created_at: i64,
+) -> Option<Uuid> {
+ let signature = attachments_signature(attachments);
+ local_messages.iter().find_map(|message| {
+ if &message.sender != sender {
+ return None;
+ }
+ if message.text != text {
+ return None;
+ }
+ if attachments_signature(&message.attachments) != signature {
+ return None;
+ }
+ if (message.created_at - created_at).abs() > 2_000_000 {
+ return None;
+ }
+ Some(message.uuid)
+ })
+}
+
+pub fn order_for_sync(messages: &[Message]) -> Vec<Message> {
+ if messages.is_empty() {
+ return Vec::new();
+ }
+
+ let by_id: HashMap<Uuid, &Message> = messages.iter().map(|m| (m.uuid, m)).collect();
+ let mut children: HashMap<Option<Uuid>, Vec<&Message>> = HashMap::new();
+
+ for message in messages {
+ let parent = message
+ .parent_message_uuid
+ .filter(|parent| by_id.contains_key(parent));
+ children.entry(parent).or_default().push(message);
+ }
+
+ for list in children.values_mut() {
+ list.sort_by(|a, b| {
+ a.created_at
+ .cmp(&b.created_at)
+ .then_with(|| a.uuid.cmp(&b.uuid))
+ });
+ }
+
+ let mut ordered = Vec::with_capacity(messages.len());
+ let mut visited = HashSet::new();
+
+ if let Some(roots) = children.get(&None) {
+ for root in roots {
+ dfs_order(*root, &children, &mut visited, &mut ordered);
+ }
+ }
+
+ ordered
+}
+
+fn dfs_order(
+ node: &Message,
+ children: &HashMap<Option<Uuid>, Vec<&Message>>,
+ visited: &mut HashSet<Uuid>,
+ output: &mut Vec<Message>,
+) {
+ if !visited.insert(node.uuid) {
+ return;
+ }
+ output.push(node.clone());
+ if let Some(kids) = children.get(&Some(node.uuid)) {
+ for child in kids {
+ dfs_order(*child, children, visited, output);
+ }
+ }
+}
+
+fn attachments_signature(attachments: &[AttachmentMeta]) -> Vec<String> {
+ attachments
+ .iter()
+ .map(|att| format!("{:?}:{}", att.kind, att.name))
+ .collect()
+}
diff --git a/rust/llmchat-sync/src/crypto.rs b/rust/llmchat-sync/src/crypto.rs
new file mode 100644
index 0000000000..d7f69636fb
--- /dev/null
+++ b/rust/llmchat-sync/src/crypto.rs
@@ -0,0 +1,70 @@
+use ente_core::crypto::{self, blob};
+use hkdf::Hkdf;
+use serde::{de::DeserializeOwned, Serialize};
+use sha2::Sha256;
+use uuid::Uuid;
+
+use crate::errors::SyncError;
+use crate::models::EncryptedPayload;
+
+pub fn encrypt_payload<T: Serialize>(payload: &T, key: &[u8]) -> Result<EncryptedPayload, SyncError> {
+ let json = serde_json::to_vec(payload)?;
+ let encrypted = blob::encrypt(&json, key)?;
+ Ok(EncryptedPayload {
+ encrypted_data: crypto::encode_b64(&encrypted.encrypted_data),
+ header: crypto::encode_b64(&encrypted.decryption_header),
+ })
+}
+
+pub fn decrypt_payload<T: DeserializeOwned>(
+ encrypted_data: &str,
+ header: &str,
+ key: &[u8],
+) -> Result<T, SyncError> {
+ let ciphertext = crypto::decode_b64(encrypted_data)?;
+ let header = crypto::decode_b64(header)?;
+ let plaintext = blob::decrypt(&ciphertext, &header, key)?;
+ let payload = serde_json::from_slice(&plaintext)?;
+ Ok(payload)
+}
+
+pub fn encrypt_chat_key(chat_key: &[u8], master_key: &[u8]) -> Result<EncryptedPayload, SyncError> {
+ let encrypted = blob::encrypt(chat_key, master_key)?;
+ Ok(EncryptedPayload {
+ encrypted_data: crypto::encode_b64(&encrypted.encrypted_data),
+ header: crypto::encode_b64(&encrypted.decryption_header),
+ })
+}
+
+pub fn decrypt_chat_key(payload: &EncryptedPayload, master_key: &[u8]) -> Result<Vec<u8>, SyncError> {
+ let ciphertext = crypto::decode_b64(&payload.encrypted_data)?;
+ let header = crypto::decode_b64(&payload.header)?;
+ let plaintext = blob::decrypt(&ciphertext, &header, master_key)?;
+ Ok(plaintext)
+}
+
+pub fn derive_attachment_key(chat_key: &[u8], session_uuid: Uuid) -> Result<Vec<u8>, SyncError> {
+ let hk = Hkdf::<Sha256>::new(Some(session_uuid.as_bytes()), chat_key);
+ let mut out = vec![0u8; blob::KEY_BYTES];
+ hk.expand(b"llmchat_attachment_v1", &mut out)
+ .map_err(|_| SyncError::Crypto("hkdf expand failed".to_string()))?;
+ Ok(out)
+}
+
+pub fn encrypt_attachment_bytes(
+ plaintext: &[u8],
+ chat_key: &[u8],
+ session_uuid: Uuid,
+) -> Result<Vec<u8>, SyncError> {
+ let key = derive_attachment_key(chat_key, session_uuid)?;
+ Ok(llmchat_db::crypto::encrypt_blob(plaintext, &key)?)
+}
+
+pub fn decrypt_attachment_bytes(
+ ciphertext: &[u8],
+ chat_key: &[u8],
+ session_uuid: Uuid,
+) -> Result<Vec<u8>, SyncError> {
+ let key = derive_attachment_key(chat_key, session_uuid)?;
+ Ok(llmchat_db::crypto::decrypt_blob(ciphertext, &key)?)
+}
diff --git a/rust/llmchat-sync/src/diff_cursor.rs b/rust/llmchat-sync/src/diff_cursor.rs
new file mode 100644
index 0000000000..e23ba19e68
--- /dev/null
+++ b/rust/llmchat-sync/src/diff_cursor.rs
@@ -0,0 +1,31 @@
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub struct SyncCursor {
+ pub base_since_time: i64,
+ pub since_time: i64,
+ pub max_time: i64,
+ pub since_type: String,
+ pub since_id: String,
+}
+
+impl Default for SyncCursor {
+ fn default() -> Self {
+ Self {
+ base_since_time: 0,
+ since_time: 0,
+ max_time: 0,
+ since_type: "sessions".to_string(),
+ since_id: "00000000-0000-0000-0000-000000000000".to_string(),
+ }
+ }
+}
+
+impl SyncCursor {
+ pub fn is_complete_cycle(&self) -> bool {
+ self.since_type == "sessions"
+ && self.since_time == self.base_since_time
+ && self.since_time == self.max_time
+ }
+}
diff --git a/rust/llmchat-sync/src/errors.rs b/rust/llmchat-sync/src/errors.rs
new file mode 100644
index 0000000000..832f495b3e
--- /dev/null
+++ b/rust/llmchat-sync/src/errors.rs
@@ -0,0 +1,55 @@
+use thiserror::Error;
+
+#[derive(Debug, Error)]
+pub enum SyncError {
+ #[error("not logged in")]
+ NotLoggedIn,
+ #[error("unauthorized")]
+ Unauthorized,
+ #[error("db error: {0}")]
+ Db(String),
+ #[error("crypto error: {0}")]
+ Crypto(String),
+ #[error("http {status}: {message}")]
+ Http {
+ status: u16,
+ message: String,
+ code: Option<String>,
+ },
+ #[error("limit reached: {code}")]
+ LimitReached { code: String, message: Option<String> },
+ #[error("attachment API unavailable")]
+ AttachmentApiUnavailable,
+ #[error("attachment missing: {0}")]
+ AttachmentMissing(String),
+ #[error("invalid response: {0}")]
+ InvalidResponse(String),
+ #[error("serde error: {0}")]
+ Serde(String),
+ #[error("io error: {0}")]
+ Io(String),
+}
+
+impl From<llmchat_db::Error> for SyncError {
+ fn from(err: llmchat_db::Error) -> Self {
+ SyncError::Db(err.to_string())
+ }
+}
+
+impl From<ente_core::crypto::CryptoError> for SyncError {
+ fn from(err: ente_core::crypto::CryptoError) -> Self {
+ SyncError::Crypto(err.to_string())
+ }
+}
+
+impl From<serde_json::Error> for SyncError {
+ fn from(err: serde_json::Error) -> Self {
+ SyncError::Serde(err.to_string())
+ }
+}
+
+impl From<std::io::Error> for SyncError {
+ fn from(err: std::io::Error) -> Self {
+ SyncError::Io(err.to_string())
+ }
+}
diff --git a/rust/llmchat-sync/src/http.rs b/rust/llmchat-sync/src/http.rs
new file mode 100644
index 0000000000..71cdb10909
--- /dev/null
+++ b/rust/llmchat-sync/src/http.rs
@@ -0,0 +1,336 @@
+use std::time::Duration;
+
+use reqwest::blocking::{Client, Response};
+use reqwest::header::{HeaderMap, HeaderName, HeaderValue, LOCATION};
+use serde::de::DeserializeOwned;
+use serde::Serialize;
+use uuid::Uuid;
+
+use crate::errors::SyncError;
+
+#[derive(Debug, Clone)]
+pub struct HttpConfig {
+ pub base_url: String,
+ pub auth_token: String,
+ pub user_agent: Option<String>,
+ pub client_package: Option<String>,
+ pub client_version: Option<String>,
+ pub timeout_secs: Option<u64>,
+}
+
+pub struct HttpClient {
+ base_url: String,
+ client: Client,
+ auth_token: String,
+ user_agent: Option<String>,
+ client_package: Option<String>,
+ client_version: Option<String>,
+}
+
+impl HttpClient {
+ pub fn new(config: HttpConfig) -> Result<Self, SyncError> {
+ let mut builder = Client::builder();
+ if let Some(timeout) = config.timeout_secs {
+ builder = builder.timeout(Duration::from_secs(timeout));
+ }
+ if config.base_url.contains("ngrok-free.app") {
+ builder = builder.danger_accept_invalid_certs(true);
+ }
+ let client = builder.build().map_err(|e| SyncError::Http {
+ status: 0,
+ message: e.to_string(),
+ code: None,
+ })?;
+ Ok(Self {
+ base_url: config.base_url.trim_end_matches('/').to_string(),
+ client,
+ auth_token: config.auth_token,
+ user_agent: config.user_agent,
+ client_package: config.client_package,
+ client_version: config.client_version,
+ })
+ }
+
+ pub fn get_json<T: DeserializeOwned>(
+ &self,
+ path: &str,
+ query: &[(&str, String)],
+ ) -> Result<T, SyncError> {
+ let url = format!("{}{}", self.base_url, path);
+ let resp = self
+ .client
+ .get(&url)
+ .headers(self.build_headers())
+ .query(query)
+ .send()
+ .map_err(map_reqwest_error)?;
+ parse_json_response(resp)
+ }
+
+ pub fn get_json_optional<T: DeserializeOwned>(
+ &self,
+ path: &str,
+ query: &[(&str, String)],
+ ) -> Result<Option<T>, SyncError> {
+ let url = format!("{}{}", self.base_url, path);
+ let resp = self
+ .client
+ .get(&url)
+ .headers(self.build_headers())
+ .query(query)
+ .send()
+ .map_err(map_reqwest_error)?;
+ if resp.status().as_u16() == 404 {
+ return Ok(None);
+ }
+ parse_json_response(resp).map(Some)
+ }
+
+ pub fn post_json<T: DeserializeOwned, B: Serialize>(
+ &self,
+ path: &str,
+ body: &B,
+ ) -> Result<T, SyncError> {
+ let url = format!("{}{}", self.base_url, path);
+ let resp = self
+ .client
+ .post(&url)
+ .headers(self.build_headers())
+ .json(body)
+ .send()
+ .map_err(map_reqwest_error)?;
+ parse_json_response(resp)
+ }
+
+ pub fn post_empty<B: Serialize>(&self, path: &str, body: &B) -> Result<(), SyncError> {
+ let url = format!("{}{}", self.base_url, path);
+ let resp = self
+ .client
+ .post(&url)
+ .headers(self.build_headers())
+ .json(body)
+ .send()
+ .map_err(map_reqwest_error)?;
+ parse_empty_response(resp)
+ }
+
+ pub fn delete(&self, path: &str, query: &[(&str, String)]) -> Result<(), SyncError> {
+ let url = format!("{}{}", self.base_url, path);
+ let resp = self
+ .client
+ .delete(&url)
+ .headers(self.build_headers())
+ .query(query)
+ .send()
+ .map_err(map_reqwest_error)?;
+ parse_empty_response(resp)
+ }
+
+ pub fn get_bytes(&self, url: &str) -> Result<Vec<u8>, SyncError> {
+ let mut current_url = url.to_string();
+ for _ in 0..5 {
+ let resp = self
+ .client
+ .get(&current_url)
+ .headers(self.build_headers())
+ .send()
+ .map_err(map_reqwest_error)?;
+ if resp.status().is_redirection() {
+ if let Some(location) = resp.headers().get(LOCATION) {
+ let next = location
+ .to_str()
+ .map_err(|_| SyncError::InvalidResponse("invalid redirect location".to_string()))?;
+ current_url = next.to_string();
+ continue;
+ }
+ }
+ return parse_bytes_response(resp);
+ }
+ Err(SyncError::InvalidResponse("too many redirects".to_string()))
+ }
+
+ pub fn head_status(&self, path: &str) -> Result<u16, SyncError> {
+ let url = format!("{}{}", self.base_url, path);
+ self.head_status_url(&url)
+ }
+
+ fn head_status_url(&self, url: &str) -> Result<u16, SyncError> {
+ let mut current_url = url.to_string();
+ for _ in 0..5 {
+ let resp = self
+ .client
+ .head(&current_url)
+ .headers(self.build_headers())
+ .send()
+ .map_err(map_reqwest_error)?;
+ let status = resp.status().as_u16();
+ if status == 401 {
+ return Err(SyncError::Unauthorized);
+ }
+ if resp.status().is_redirection() {
+ if let Some(location) = resp.headers().get(LOCATION) {
+ let next = location
+ .to_str()
+ .map_err(|_| SyncError::InvalidResponse("invalid redirect location".to_string()))?;
+ current_url = next.to_string();
+ continue;
+ }
+ }
+ return Ok(status);
+ }
+ Err(SyncError::InvalidResponse("too many redirects".to_string()))
+ }
+
+ pub fn put_bytes(
+ &self,
+ url: &str,
+ body: &[u8],
+ headers: &[(&str, String)],
+ ) -> Result<(), SyncError> {
+ let mut header_map = HeaderMap::new();
+ for (name, value) in headers {
+ let header_name = HeaderName::from_bytes(name.as_bytes())
+ .map_err(|_| SyncError::InvalidResponse("invalid header name".to_string()))?;
+ let header_value = HeaderValue::from_str(value)
+ .map_err(|_| SyncError::InvalidResponse("invalid header value".to_string()))?;
+ header_map.insert(header_name, header_value);
+ }
+
+ let mut current_url = url.to_string();
+ for _ in 0..5 {
+ let resp = self
+ .client
+ .put(&current_url)
+ .headers(header_map.clone())
+ .body(body.to_vec())
+ .send()
+ .map_err(map_reqwest_error)?;
+
+ if resp.status().is_redirection() {
+ if let Some(location) = resp.headers().get(LOCATION) {
+ let next = location
+ .to_str()
+ .map_err(|_| SyncError::InvalidResponse("invalid redirect location".to_string()))?;
+ current_url = next.to_string();
+ continue;
+ }
+ }
+
+ return parse_empty_response(resp);
+ }
+
+ Err(SyncError::InvalidResponse("too many redirects".to_string()))
+ }
+
+ fn build_headers(&self) -> HeaderMap {
+ let mut headers = HeaderMap::new();
+ if let Some(agent) = &self.user_agent {
+ if let Ok(value) = HeaderValue::from_str(agent) {
+ headers.insert("User-Agent", value);
+ }
+ }
+ if let Some(pkg) = &self.client_package {
+ if let Ok(value) = HeaderValue::from_str(pkg) {
+ headers.insert("X-Client-Package", value);
+ }
+ }
+ if let Some(version) = &self.client_version {
+ if let Ok(value) = HeaderValue::from_str(version) {
+ headers.insert("X-Client-Version", value);
+ }
+ }
+ headers.insert("x-request-id", HeaderValue::from_str(&Uuid::new_v4().to_string()).unwrap());
+ if let Ok(value) = HeaderValue::from_str(&self.auth_token) {
+ headers.insert("X-Auth-Token", value);
+ }
+ headers
+ }
+}
+
+#[derive(Debug, serde::Deserialize)]
+struct ErrorResponse {
+ code: Option<String>,
+ message: Option<String>,
+}
+
+fn parse_json_response<T: DeserializeOwned>(resp: Response) -> Result<T, SyncError> {
+ let status = resp.status().as_u16();
+ if status == 401 {
+ return Err(SyncError::Unauthorized);
+ }
+ if status >= 400 {
+ let body = resp.text().unwrap_or_default();
+ return Err(map_error_response(status, &body));
+ }
+ resp.json::<T>().map_err(map_reqwest_error)
+}
+
+fn parse_empty_response(resp: Response) -> Result<(), SyncError> {
+ let status = resp.status().as_u16();
+ if status == 401 {
+ return Err(SyncError::Unauthorized);
+ }
+ if status >= 300 {
+ let body = resp.text().unwrap_or_default();
+ return Err(map_error_response(status, &body));
+ }
+ Ok(())
+}
+
+fn parse_bytes_response(resp: Response) -> Result<Vec<u8>, SyncError> {
+ let status = resp.status().as_u16();
+ if status == 401 {
+ return Err(SyncError::Unauthorized);
+ }
+ if status >= 400 {
+ let body = resp.text().unwrap_or_default();
+ return Err(map_error_response(status, &body));
+ }
+ resp.bytes()
+ .map(|bytes| bytes.to_vec())
+ .map_err(map_reqwest_error)
+}
+
+fn map_error_response(status: u16, body: &str) -> SyncError {
+ if let Ok(err) = serde_json::from_str::<ErrorResponse>(body) {
+ if let Some(code) = err.code.clone() {
+ if matches!(
+ code.as_str(),
+ "LLMCHAT_MESSAGE_LIMIT_REACHED"
+ | "LLMCHAT_ATTACHMENT_LIMIT_REACHED"
+ | "LLMCHAT_PAYLOAD_TOO_LARGE"
+ ) {
+ return SyncError::LimitReached {
+ code,
+ message: err.message,
+ };
+ }
+ }
+ return SyncError::Http {
+ status,
+ message: err.message.unwrap_or_else(|| body.to_string()),
+ code: err.code,
+ };
+ }
+ SyncError::Http {
+ status,
+ message: body.to_string(),
+ code: None,
+ }
+}
+
+fn map_reqwest_error(err: reqwest::Error) -> SyncError {
+ if let Some(status) = err.status() {
+ SyncError::Http {
+ status: status.as_u16(),
+ message: err.to_string(),
+ code: None,
+ }
+ } else {
+ SyncError::Http {
+ status: 0,
+ message: err.to_string(),
+ code: None,
+ }
+ }
+}
diff --git a/rust/llmchat-sync/src/lib.rs b/rust/llmchat-sync/src/lib.rs
new file mode 100644
index 0000000000..3978cb7e20
--- /dev/null
+++ b/rust/llmchat-sync/src/lib.rs
@@ -0,0 +1,10 @@
+pub mod conflict;
+pub mod crypto;
+pub mod diff_cursor;
+pub mod errors;
+pub mod http;
+pub mod models;
+pub mod sync;
+
+pub use errors::SyncError;
+pub use sync::{SyncEngine, SyncResult, SyncStats, SyncAuth};
diff --git a/rust/llmchat-sync/src/models.rs b/rust/llmchat-sync/src/models.rs
new file mode 100644
index 0000000000..71f60b0f82
--- /dev/null
+++ b/rust/llmchat-sync/src/models.rs
@@ -0,0 +1,137 @@
+use serde::{Deserialize, Serialize};
+
+use crate::diff_cursor::SyncCursor;
+use llmchat_db::AttachmentKind;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct EncryptedPayload {
+ #[serde(alias = "encrypted_key", alias = "encryptedKey", alias = "encryptedData")]
+ pub encrypted_data: String,
+ pub header: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ChatKeyPayload {
+ #[serde(rename = "encrypted_key", default, skip_serializing_if = "Option::is_none", alias = "encryptedKey")]
+ pub encrypted_key: Option<String>,
+ #[serde(rename = "encrypted_data", default, skip_serializing_if = "Option::is_none", alias = "encryptedData")]
+ pub encrypted_data: Option<String>,
+ pub header: String,
+}
+
+impl ChatKeyPayload {
+ pub fn from_encrypted(encrypted: &EncryptedPayload) -> Self {
+ Self {
+ encrypted_key: Some(encrypted.encrypted_data.clone()),
+ encrypted_data: Some(encrypted.encrypted_data.clone()),
+ header: encrypted.header.clone(),
+ }
+ }
+
+ pub fn encrypted_value(&self) -> Option<&str> {
+ self.encrypted_data
+ .as_deref()
+ .or(self.encrypted_key.as_deref())
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct RemoteSession {
+ pub session_uuid: String,
+ pub root_session_uuid: Option<String>,
+ pub branch_from_message_uuid: Option<String>,
+ pub encrypted_data: String,
+ pub header: String,
+ pub created_at: i64,
+ pub updated_at: i64,
+ pub is_deleted: Option<bool>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct RemoteMessage {
+ pub message_uuid: String,
+ pub session_uuid: String,
+ pub parent_message_uuid: Option<String>,
+ pub sender: String,
+ pub attachments: Vec<RemoteAttachment>,
+ pub encrypted_data: String,
+ pub header: String,
+ pub created_at: i64,
+ pub updated_at: Option<i64>,
+ pub is_deleted: Option<bool>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct RemoteAttachment {
+ pub id: String,
+ pub size: i64,
+ pub encrypted_name: String,
+ pub kind: Option<AttachmentKind>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct SessionTombstone {
+ pub session_uuid: String,
+ pub deleted_at: Option<i64>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct MessageTombstone {
+ pub message_uuid: String,
+ pub deleted_at: Option<i64>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+#[serde(rename_all = "snake_case")]
+pub struct DiffTombstones {
+ #[serde(default)]
+ pub sessions: Vec<SessionTombstone>,
+ #[serde(default)]
+ pub messages: Vec<MessageTombstone>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct DiffResponse {
+ #[serde(default)]
+ pub sessions: Vec<RemoteSession>,
+ #[serde(default)]
+ pub messages: Vec<RemoteMessage>,
+ #[serde(default)]
+ pub tombstones: DiffTombstones,
+ pub cursor: Option<SyncCursor>,
+ pub timestamp: Option<i64>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct UploadUrlRequest {
+ pub content_length: i64,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub content_md5: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct UploadUrlResponse {
+ pub object_key: String,
+ pub url: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct SessionPayload {
+ pub title: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct MessagePayload {
+ pub text: String,
+}
diff --git a/rust/llmchat-sync/src/sync.rs b/rust/llmchat-sync/src/sync.rs
new file mode 100644
index 0000000000..80db8b7101
--- /dev/null
+++ b/rust/llmchat-sync/src/sync.rs
@@ -0,0 +1,972 @@
+use std::collections::{HashMap, HashSet};
+use std::path::PathBuf;
+
+use ente_core::crypto::keys;
+use llmchat_db::{
+ AttachmentKind, AttachmentMeta, AttachmentStore, Clock, EntityType, FileMetaStore,
+ FsAttachmentStore, LlmChatDb, Message, MetaStore, Sender, SqliteBackend, SystemClock,
+ UploadState,
+};
+use uuid::Uuid;
+
+use crate::conflict::{find_duplicate_message, order_for_sync};
+use crate::crypto::{decrypt_chat_key, decrypt_payload, encrypt_attachment_bytes, encrypt_chat_key, encrypt_payload};
+use crate::diff_cursor::SyncCursor;
+use crate::errors::SyncError;
+use crate::http::{HttpClient, HttpConfig};
+use crate::models::{
+ ChatKeyPayload, DiffResponse, MessagePayload, RemoteAttachment, SessionPayload,
+ UploadUrlRequest, UploadUrlResponse,
+};
+
+const CURSOR_META_KEY: &str = "llmchat.sync.cursor";
+const CHAT_KEY_META_KEY: &str = "llmchat.chat.key";
+
+#[derive(Debug, Clone)]
+pub struct SyncAuth {
+ pub base_url: String,
+ pub auth_token: String,
+ pub master_key: Vec<u8>,
+ pub user_agent: Option<String>,
+ pub client_package: Option<String>,
+ pub client_version: Option<String>,
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct SyncStats {
+ pub sessions: i64,
+ pub messages: i64,
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct SyncResult {
+ pub pulled: SyncStats,
+ pub pushed: SyncStats,
+ pub uploaded_attachments: i64,
+ pub downloaded_attachments: i64,
+}
+
+pub struct SyncEngine {
+ db: LlmChatDb<SqliteBackend>,
+ meta_store: FileMetaStore,
+ attachment_store: FsAttachmentStore,
+ plaintext_dir: Option<PathBuf>,
+ diff_limit: i64,
+}
+
+impl SyncEngine {
+ pub fn new(
+ main_db_path: String,
+ attachments_db_path: String,
+ db_key: Vec<u8>,
+ attachments_dir: String,
+ meta_dir: String,
+ plaintext_dir: Option<String>,
+ ) -> Result<Self, SyncError> {
+ llmchat_db::traits::ensure_directory(&attachments_dir)?;
+ llmchat_db::traits::ensure_directory(&meta_dir)?;
+ if let Some(ref dir) = plaintext_dir {
+ let _ = llmchat_db::traits::ensure_directory(dir);
+ }
+
+ let db = LlmChatDb::open_sqlite_with_defaults(main_db_path, attachments_db_path, db_key)?;
+ let meta_store = FileMetaStore::new(meta_dir);
+ let attachment_store = FsAttachmentStore::new(attachments_dir);
+ Ok(Self {
+ db,
+ meta_store,
+ attachment_store,
+ plaintext_dir: plaintext_dir.map(PathBuf::from),
+ diff_limit: 500,
+ })
+ }
+
+ pub fn sync(&self, auth: SyncAuth) -> Result<SyncResult, SyncError> {
+ if auth.auth_token.trim().is_empty() {
+ return Err(SyncError::NotLoggedIn);
+ }
+ if auth.master_key.len() != llmchat_db::crypto::KEY_BYTES {
+ return Err(SyncError::Crypto("invalid master key length".to_string()));
+ }
+
+ let SyncAuth {
+ base_url,
+ auth_token,
+ master_key,
+ user_agent,
+ client_package,
+ client_version,
+ } = auth;
+
+ let http = HttpClient::new(HttpConfig {
+ base_url,
+ auth_token,
+ user_agent,
+ client_package,
+ client_version,
+ timeout_secs: None,
+ })?;
+
+ let chat_key = self.get_or_create_chat_key(&http, &master_key)?;
+ let mut result = SyncResult::default();
+
+ self.pull(&http, &chat_key, &mut result)?;
+ self.push(&http, &chat_key, &mut result)?;
+
+ Ok(result)
+ }
+
+ pub fn download_attachment(
+ &self,
+ auth: SyncAuth,
+ attachment_id: String,
+ session_uuid: String,
+ ) -> Result<bool, SyncError> {
+ if auth.auth_token.trim().is_empty() {
+ return Err(SyncError::NotLoggedIn);
+ }
+ if auth.master_key.len() != llmchat_db::crypto::KEY_BYTES {
+ return Err(SyncError::Crypto("invalid master key length".to_string()));
+ }
+
+ let session_uuid = Uuid::parse_str(&session_uuid)
+ .map_err(|_| SyncError::InvalidResponse("invalid session uuid".to_string()))?;
+
+ let plaintext_dir = self
+ .plaintext_dir
+ .as_ref()
+ .ok_or_else(|| SyncError::AttachmentMissing(attachment_id.clone()))?;
+ let plaintext_path = plaintext_dir.join(&attachment_id);
+ if plaintext_path.exists() {
+ return Ok(false);
+ }
+
+ let SyncAuth {
+ base_url,
+ auth_token,
+ master_key,
+ user_agent,
+ client_package,
+ client_version,
+ } = auth;
+
+ let base_url = base_url.trim_end_matches('/').to_string();
+ let http = HttpClient::new(HttpConfig {
+ base_url: base_url.clone(),
+ auth_token,
+ user_agent,
+ client_package,
+ client_version,
+ timeout_secs: None,
+ })?;
+
+ let chat_key = self.get_or_create_chat_key(&http, &master_key)?;
+ let encrypted = if self.attachment_store.exists(&attachment_id)? {
+ self.attachment_store.read(&attachment_id)?
+ } else {
+ let url = format!("{}/llmchat/chat/attachment/{}", base_url, attachment_id);
+ let bytes = match http.get_bytes(&url) {
+ Ok(bytes) => bytes,
+ Err(SyncError::Http { status: 404, .. }) => {
+ if let Err(err) = self.force_upload_attachment(
+ &http,
+ &chat_key,
+ session_uuid,
+ &attachment_id,
+ ) {
+ return Err(err);
+ }
+ http.get_bytes(&url)?
+ }
+ Err(err) => return Err(err),
+ };
+ self.attachment_store.write(&attachment_id, &bytes)?;
+ bytes
+ };
+
+ let plaintext = crate::crypto::decrypt_attachment_bytes(&encrypted, &chat_key, session_uuid)?;
+ std::fs::write(plaintext_path, plaintext)?;
+ Ok(true)
+ }
+
+ fn pull(
+ &self,
+ http: &HttpClient,
+ chat_key: &[u8],
+ result: &mut SyncResult,
+ ) -> Result<(), SyncError> {
+ let mut cursor = self.load_cursor()?;
+ let mut seen_cursor = None;
+
+ loop {
+ let query = vec![
+ ("sinceTime", cursor.since_time.to_string()),
+ ("sinceType", cursor.since_type.clone()),
+ ("sinceId", cursor.since_id.clone()),
+ ("limit", self.diff_limit.to_string()),
+ ];
+ let response: DiffResponse = http.get_json("/llmchat/chat/diff", &query)?;
+
+ self.apply_diff(&response, chat_key, result)?;
+
+ let next_cursor = match response.cursor.clone() {
+ Some(cursor) => cursor,
+ None => {
+ if let Some(timestamp) = response.timestamp {
+ SyncCursor {
+ base_since_time: timestamp,
+ since_time: timestamp,
+ max_time: timestamp,
+ since_type: "sessions".to_string(),
+ since_id: "00000000-0000-0000-0000-000000000000".to_string(),
+ }
+ } else {
+ cursor.clone()
+ }
+ }
+ };
+
+ if Some(next_cursor.clone()) == seen_cursor {
+ break;
+ }
+
+ cursor = next_cursor;
+ self.save_cursor(&cursor)?;
+
+ if cursor.is_complete_cycle() {
+ break;
+ }
+
+ seen_cursor = Some(cursor.clone());
+ }
+
+ Ok(())
+ }
+
+ fn apply_diff(
+ &self,
+ response: &DiffResponse,
+ chat_key: &[u8],
+ result: &mut SyncResult,
+ ) -> Result<(), SyncError> {
+ let mut local_messages_cache: HashMap<Uuid, Vec<Message>> = HashMap::new();
+ let mut duplicate_map: HashMap<Uuid, Uuid> = HashMap::new();
+ let mut remote_message_updates: HashMap<Uuid, i64> = HashMap::new();
+
+ for message in &response.messages {
+ if message.is_deleted == Some(true) {
+ continue;
+ }
+ let session_uuid = Uuid::parse_str(&message.session_uuid)
+ .map_err(|e| SyncError::InvalidResponse(e.to_string()))?;
+ let timestamp = message.updated_at.unwrap_or(message.created_at);
+ remote_message_updates
+ .entry(session_uuid)
+ .and_modify(|current| {
+ if *current < timestamp {
+ *current = timestamp;
+ }
+ })
+ .or_insert(timestamp);
+ }
+
+ for session in &response.sessions {
+ if session.is_deleted == Some(true) {
+ continue;
+ }
+ let payload: SessionPayload =
+ decrypt_payload(&session.encrypted_data, &session.header, chat_key)?;
+ let uuid = Uuid::parse_str(&session.session_uuid)
+ .map_err(|e| SyncError::InvalidResponse(e.to_string()))?;
+ let local = self.db.get_session(uuid).ok().flatten();
+ let title_changed = local
+ .as_ref()
+ .map(|existing| existing.title != payload.title)
+ .unwrap_or(true);
+ let mut effective_updated_at = local
+ .as_ref()
+ .map(|existing| existing.updated_at)
+ .unwrap_or(session.updated_at);
+ if let Some(remote_updated) = remote_message_updates.get(&uuid) {
+ if effective_updated_at < *remote_updated {
+ effective_updated_at = *remote_updated;
+ }
+ }
+ if title_changed && effective_updated_at < session.updated_at {
+ effective_updated_at = session.updated_at;
+ }
+
+ let _ = self.db.upsert_session_from_remote(
+ uuid,
+ &payload.title,
+ session.created_at,
+ effective_updated_at,
+ )?;
+ result.pulled.sessions += 1;
+ }
+
+ for message in &response.messages {
+ if message.is_deleted == Some(true) {
+ continue;
+ }
+ let payload: MessagePayload =
+ decrypt_payload(&message.encrypted_data, &message.header, chat_key)?;
+ let message_uuid = Uuid::parse_str(&message.message_uuid)
+ .map_err(|e| SyncError::InvalidResponse(e.to_string()))?;
+ let session_uuid = Uuid::parse_str(&message.session_uuid)
+ .map_err(|e| SyncError::InvalidResponse(e.to_string()))?;
+
+ let sender: Sender = message
+ .sender
+ .parse::<Sender>()
+ .map_err(|e| SyncError::InvalidResponse(e.to_string()))?;
+ let attachments = self.decrypt_remote_attachments(&message.attachments, chat_key)?;
+
+ let local_messages = local_messages_cache.entry(session_uuid).or_insert_with(|| {
+ self.db.get_messages(session_uuid).unwrap_or_default()
+ });
+
+ if let Some(dup_uuid) =
+ find_duplicate_message(local_messages, &sender, &payload.text, &attachments, message.created_at)
+ {
+ duplicate_map.insert(message_uuid, dup_uuid);
+ continue;
+ }
+
+ let parent_uuid = message
+ .parent_message_uuid
+ .as_ref()
+ .and_then(|parent| Uuid::parse_str(parent).ok())
+ .and_then(|parent| duplicate_map.get(&parent).cloned().or(Some(parent)));
+
+ let inserted = self.db.upsert_message_from_remote(
+ message_uuid,
+ session_uuid,
+ sender.as_str(),
+ &payload.text,
+ parent_uuid,
+ attachments.clone(),
+ message.created_at,
+ )?;
+
+ for attachment in &attachments {
+ let _ = self.db.upsert_attachment_with_state(
+ &attachment.id,
+ session_uuid,
+ message_uuid,
+ attachment.size,
+ UploadState::Uploaded,
+ );
+ }
+
+ local_messages.push(inserted);
+ result.pulled.messages += 1;
+ }
+
+ let clock = SystemClock;
+ let now = clock.now_us();
+ for tombstone in &response.tombstones.sessions {
+ let uuid = Uuid::parse_str(&tombstone.session_uuid)
+ .map_err(|e| SyncError::InvalidResponse(e.to_string()))?;
+ let deleted_at = tombstone.deleted_at.or(response.timestamp).unwrap_or(now);
+ let _ = self.db.apply_session_tombstone(uuid, deleted_at);
+ }
+
+ for tombstone in &response.tombstones.messages {
+ let uuid = Uuid::parse_str(&tombstone.message_uuid)
+ .map_err(|e| SyncError::InvalidResponse(e.to_string()))?;
+ let deleted_at = tombstone.deleted_at.or(response.timestamp).unwrap_or(now);
+ let _ = self.db.apply_message_tombstone(uuid, deleted_at);
+ }
+
+ Ok(())
+ }
+
+ fn push(
+ &self,
+ http: &HttpClient,
+ chat_key: &[u8],
+ result: &mut SyncResult,
+ ) -> Result<(), SyncError> {
+ let pending_deletes = self.db.get_pending_deletions()?;
+ for (entity_type, uuid) in pending_deletes {
+ match entity_type {
+ EntityType::Session => {
+ http.delete(
+ "/llmchat/chat/session",
+ &[("id", uuid.to_string())],
+ )?;
+ let _ = self.db.delete_attachment_tracking_for_session(uuid);
+ self.db.hard_delete(entity_type, uuid)?;
+ }
+ EntityType::Message => {
+ http.delete(
+ "/llmchat/chat/message",
+ &[("id", uuid.to_string())],
+ )?;
+ let _ = self.db.delete_attachment_tracking_for_message(uuid);
+ self.db.hard_delete(entity_type, uuid)?;
+ }
+ }
+ }
+
+ let sessions = self.db.get_sessions_needing_sync()?;
+ for session in sessions {
+ let session_uuid = session.uuid;
+ let messages = self.db.get_messages(session_uuid)?;
+ self.reconcile_attachments(session_uuid, &messages)?;
+
+ let force_uploads = self.revalidate_uploaded_attachments(http, session_uuid, &messages)?;
+ let uploaded =
+ self.upload_pending_attachments(http, chat_key, session_uuid, &force_uploads)?;
+ result.uploaded_attachments += uploaded;
+
+ let upload_states = self.collect_attachment_states(&messages)?;
+ let blocked = blocked_messages(&messages, &upload_states);
+
+ let ordered = order_for_sync(&messages);
+ let filtered: Vec<Message> = ordered
+ .into_iter()
+ .filter(|message| !blocked.contains(&message.uuid))
+ .collect();
+
+ let session_payload = SessionPayload {
+ title: session.title.clone(),
+ };
+ let encrypted = encrypt_payload(&session_payload, chat_key)?;
+ let session_request = UpsertSessionRequest {
+ session_uuid: session_uuid.to_string(),
+ root_session_uuid: session_uuid.to_string(),
+ branch_from_message_uuid: None,
+ encrypted_data: encrypted.encrypted_data,
+ header: encrypted.header,
+ created_at: session.created_at,
+ };
+ let _response: serde_json::Value = http.post_json("/llmchat/chat/session", &session_request)?;
+ result.pushed.sessions += 1;
+
+ for message in filtered.iter() {
+ self.push_message_with_retry(http, chat_key, message, result)?;
+ }
+
+ if blocked.is_empty() && filtered.len() == messages.len() {
+ let _ = self
+ .db
+ .mark_session_synced(session_uuid, &session_uuid.to_string());
+ }
+ }
+
+ Ok(())
+ }
+
+ fn push_message_with_retry(
+ &self,
+ http: &HttpClient,
+ chat_key: &[u8],
+ message: &Message,
+ result: &mut SyncResult,
+ ) -> Result<(), SyncError> {
+ match self.push_message(http, chat_key, message) {
+ Ok(()) => {
+ result.pushed.messages += 1;
+ Ok(())
+ }
+ Err(err) => {
+ if !self.is_attachment_size_mismatch(&err) {
+ return Err(err);
+ }
+ self.reset_attachments_for_message(message)?;
+ let empty_force = HashSet::new();
+ let uploaded = self.upload_pending_attachments(
+ http,
+ chat_key,
+ message.session_uuid,
+ &empty_force,
+ )?;
+ result.uploaded_attachments += uploaded;
+ self.push_message(http, chat_key, message)?;
+ result.pushed.messages += 1;
+ Ok(())
+ }
+ }
+ }
+
+ fn push_message(
+ &self,
+ http: &HttpClient,
+ chat_key: &[u8],
+ message: &Message,
+ ) -> Result<(), SyncError> {
+ let message_payload = MessagePayload {
+ text: message.text.clone(),
+ };
+ let encrypted = encrypt_payload(&message_payload, chat_key)?;
+ let attachments = self.encrypt_attachments(message.session_uuid, &message.attachments, chat_key)?;
+
+ let message_request = UpsertMessageRequest {
+ message_uuid: message.uuid.to_string(),
+ session_uuid: message.session_uuid.to_string(),
+ parent_message_uuid: message.parent_message_uuid.map(|v| v.to_string()),
+ sender: message.sender.as_str().to_string(),
+ attachments,
+ encrypted_data: encrypted.encrypted_data,
+ header: encrypted.header,
+ created_at: message.created_at,
+ };
+ let _response: serde_json::Value = http.post_json("/llmchat/chat/message", &message_request)?;
+ Ok(())
+ }
+
+ fn reset_attachments_for_message(&self, message: &Message) -> Result<(), SyncError> {
+ for attachment in &message.attachments {
+ let _ = self.attachment_store.delete(&attachment.id);
+ let _ = self.db.upsert_pending_attachment(
+ &attachment.id,
+ message.session_uuid,
+ message.uuid,
+ attachment.size,
+ );
+ let _ = self
+ .db
+ .set_attachment_upload_state(&attachment.id, UploadState::Pending);
+ }
+ Ok(())
+ }
+
+ fn is_attachment_size_mismatch(&self, error: &SyncError) -> bool {
+ match error {
+ SyncError::Http { status: 400, message, .. } => {
+ message.to_ascii_lowercase().contains("attachment size mismatch")
+ }
+ _ => false,
+ }
+ }
+
+ fn encrypt_attachments(
+ &self,
+ session_uuid: Uuid,
+ attachments: &[AttachmentMeta],
+ chat_key: &[u8],
+ ) -> Result<Vec<RemoteAttachment>, SyncError> {
+ attachments
+ .iter()
+ .map(|attachment| {
+ let encrypted_name =
+ llmchat_db::crypto::encrypt_json_field(&attachment.name, chat_key)?;
+ let encrypted_size =
+ self.encrypted_attachment_size(&attachment.id, session_uuid, chat_key)?;
+ Ok(RemoteAttachment {
+ id: attachment.id.clone(),
+ size: encrypted_size,
+ encrypted_name,
+ kind: Some(attachment.kind),
+ })
+ })
+ .collect()
+ }
+
+ fn decrypt_remote_attachments(
+ &self,
+ attachments: &[RemoteAttachment],
+ chat_key: &[u8],
+ ) -> Result<Vec<AttachmentMeta>, SyncError> {
+ attachments
+ .iter()
+ .map(|attachment| {
+ let name = llmchat_db::crypto::decrypt_json_field(&attachment.encrypted_name, chat_key)?;
+ let kind = attachment.kind.unwrap_or_else(|| infer_kind(&name));
+ Ok(AttachmentMeta {
+ id: attachment.id.clone(),
+ kind,
+ size: attachment.size,
+ name,
+ })
+ })
+ .collect()
+ }
+
+ fn reconcile_attachments(
+ &self,
+ session_uuid: Uuid,
+ messages: &[Message],
+ ) -> Result<(), SyncError> {
+ for message in messages {
+ for attachment in &message.attachments {
+ if self
+ .db
+ .get_attachment_upload_state(&attachment.id)?
+ .is_none()
+ {
+ let _ = self.db.upsert_pending_attachment(
+ &attachment.id,
+ session_uuid,
+ message.uuid,
+ attachment.size,
+ );
+ }
+ }
+ }
+ Ok(())
+ }
+
+ fn collect_attachment_states(
+ &self,
+ messages: &[Message],
+ ) -> Result<HashMap<String, UploadState>, SyncError> {
+ let mut states = HashMap::new();
+ for message in messages {
+ for attachment in &message.attachments {
+ let state = self
+ .db
+ .get_attachment_upload_state(&attachment.id)?
+ .unwrap_or(UploadState::Pending);
+ states.insert(attachment.id.clone(), state);
+ }
+ }
+ Ok(states)
+ }
+
+ fn revalidate_uploaded_attachments(
+ &self,
+ http: &HttpClient,
+ session_uuid: Uuid,
+ messages: &[Message],
+ ) -> Result<HashSet<String>, SyncError> {
+ let states = self.collect_attachment_states(messages)?;
+ let plaintext_dir = self.plaintext_dir.as_ref();
+ let mut force_uploads = HashSet::new();
+ let mut checked = HashSet::new();
+
+ for message in messages {
+ for attachment in &message.attachments {
+ if !checked.insert(attachment.id.clone()) {
+ continue;
+ }
+ let state = states
+ .get(&attachment.id)
+ .copied()
+ .unwrap_or(UploadState::Pending);
+ if state != UploadState::Uploaded {
+ continue;
+ }
+
+ let has_encrypted = self.attachment_store.exists(&attachment.id)?;
+ let has_plaintext = plaintext_dir
+ .map(|dir| dir.join(&attachment.id).exists())
+ .unwrap_or(false);
+ if !has_encrypted && !has_plaintext {
+ continue;
+ }
+
+ let status = match http.head_status(&format!(
+ "/llmchat/chat/attachment/{}",
+ attachment.id
+ )) {
+ Ok(status) => status,
+ Err(SyncError::Unauthorized) => return Err(SyncError::Unauthorized),
+ Err(_) => continue,
+ };
+
+ if status == 404 {
+ let _ = self.db.upsert_pending_attachment(
+ &attachment.id,
+ session_uuid,
+ message.uuid,
+ attachment.size,
+ );
+ let _ = self
+ .db
+ .set_attachment_upload_state(&attachment.id, UploadState::Pending);
+ force_uploads.insert(attachment.id.clone());
+ }
+ }
+ }
+
+ Ok(force_uploads)
+ }
+
+ fn force_upload_attachment(
+ &self,
+ http: &HttpClient,
+ chat_key: &[u8],
+ session_uuid: Uuid,
+ attachment_id: &str,
+ ) -> Result<(), SyncError> {
+ let encrypted = self.ensure_encrypted_bytes(attachment_id, session_uuid, chat_key)?;
+ let request = UploadUrlRequest {
+ content_length: encrypted.len() as i64,
+ content_md5: None,
+ };
+ let upload_url = http.post_json::<UploadUrlResponse, _>(
+ &format!(
+ "/llmchat/chat/attachment/{}/upload-url?force=true",
+ attachment_id
+ ),
+ &request,
+ )?;
+ http.put_bytes(&upload_url.url, &encrypted, &[])?;
+ if self.db.get_attachment_upload_state(attachment_id)?.is_some() {
+ let _ = self.db.mark_attachment_uploaded(attachment_id);
+ }
+ Ok(())
+ }
+
+ fn upload_pending_attachments(
+ &self,
+ http: &HttpClient,
+ chat_key: &[u8],
+ session_uuid: Uuid,
+ force_uploads: &HashSet<String>,
+ ) -> Result<i64, SyncError> {
+ let pending = self.db.get_pending_uploads_for_session(session_uuid)?;
+ let mut uploaded = 0;
+
+ for row in pending {
+ self.db
+ .set_attachment_upload_state(&row.attachment_id, UploadState::Uploading)?;
+
+ let encrypted = match self.ensure_encrypted_bytes(&row.attachment_id, session_uuid, chat_key) {
+ Ok(data) => data,
+ Err(err) => {
+ let _ = self.db.set_attachment_upload_state(&row.attachment_id, UploadState::Failed);
+ return Err(err);
+ }
+ };
+
+ let request = UploadUrlRequest {
+ content_length: encrypted.len() as i64,
+ content_md5: None,
+ };
+
+ let upload_path = if force_uploads.contains(&row.attachment_id) {
+ format!(
+ "/llmchat/chat/attachment/{}/upload-url?force=true",
+ row.attachment_id
+ )
+ } else {
+ format!(
+ "/llmchat/chat/attachment/{}/upload-url",
+ row.attachment_id
+ )
+ };
+
+ let upload_url = match http.post_json::<UploadUrlResponse, _>(&upload_path, &request) {
+ Ok(resp) => Some(resp),
+ Err(SyncError::Http { status: 409, .. }) => {
+ let _ = self.db.mark_attachment_uploaded(&row.attachment_id);
+ uploaded += 1;
+ None
+ }
+ Err(SyncError::Http { status: 404 | 501, .. }) => {
+ let _ = self.db.set_attachment_upload_state(&row.attachment_id, UploadState::Failed);
+ return Err(SyncError::AttachmentApiUnavailable);
+ }
+ Err(err) => {
+ let _ = self.db.set_attachment_upload_state(&row.attachment_id, UploadState::Failed);
+ return Err(err);
+ }
+ };
+
+ if let Some(upload_url) = upload_url {
+ if let Err(err) = http.put_bytes(&upload_url.url, &encrypted, &[]) {
+ let _ = self.db.set_attachment_upload_state(&row.attachment_id, UploadState::Failed);
+ return Err(err);
+ }
+ let _ = self.db.mark_attachment_uploaded(&row.attachment_id);
+ uploaded += 1;
+ }
+ }
+
+ Ok(uploaded)
+ }
+
+ fn encrypted_attachment_size(
+ &self,
+ attachment_id: &str,
+ session_uuid: Uuid,
+ chat_key: &[u8],
+ ) -> Result<i64, SyncError> {
+ if self.attachment_store.exists(attachment_id)? {
+ let size = self.attachment_store.size(attachment_id)?;
+ return Ok(size as i64);
+ }
+
+ let encrypted = self.ensure_encrypted_bytes(attachment_id, session_uuid, chat_key)?;
+ Ok(encrypted.len() as i64)
+ }
+
+ fn ensure_encrypted_bytes(
+ &self,
+ attachment_id: &str,
+ session_uuid: Uuid,
+ chat_key: &[u8],
+ ) -> Result<Vec<u8>, SyncError> {
+ if self.attachment_store.exists(attachment_id)? {
+ return Ok(self.attachment_store.read(attachment_id)?);
+ }
+
+ let plaintext_dir = self
+ .plaintext_dir
+ .as_ref()
+ .ok_or_else(|| SyncError::AttachmentMissing(attachment_id.to_string()))?;
+ let path = plaintext_dir.join(attachment_id);
+ if !path.exists() {
+ return Err(SyncError::AttachmentMissing(attachment_id.to_string()));
+ }
+ let plaintext = std::fs::read(path)?;
+ let encrypted = encrypt_attachment_bytes(&plaintext, chat_key, session_uuid)?;
+ self.attachment_store.write(attachment_id, &encrypted)?;
+ Ok(encrypted)
+ }
+
+ fn load_cursor(&self) -> Result<SyncCursor, SyncError> {
+ match self.meta_store.get(CURSOR_META_KEY)? {
+ Some(data) => Ok(serde_json::from_slice(&data)?),
+ None => Ok(SyncCursor::default()),
+ }
+ }
+
+ fn save_cursor(&self, cursor: &SyncCursor) -> Result<(), SyncError> {
+ let data = serde_json::to_vec(cursor)?;
+ self.meta_store.set(CURSOR_META_KEY, &data)?;
+ Ok(())
+ }
+
+ fn load_chat_key_from_meta(&self, master_key: &[u8]) -> Result<Option<Vec<u8>>, SyncError> {
+ let data = match self.meta_store.get(CHAT_KEY_META_KEY)? {
+ Some(data) => data,
+ None => return Ok(None),
+ };
+ let payload: ChatKeyPayload = serde_json::from_slice(&data)?;
+ let encrypted = payload
+ .encrypted_value()
+ .ok_or_else(|| SyncError::InvalidResponse("missing encrypted chat key".to_string()))?;
+ let encrypted_payload = crate::models::EncryptedPayload {
+ encrypted_data: encrypted.to_string(),
+ header: payload.header,
+ };
+ Ok(Some(decrypt_chat_key(&encrypted_payload, master_key)?))
+ }
+
+ fn save_chat_key_to_meta(&self, payload: &ChatKeyPayload) -> Result<(), SyncError> {
+ let data = serde_json::to_vec(payload)?;
+ self.meta_store.set(CHAT_KEY_META_KEY, &data)?;
+ Ok(())
+ }
+
+ fn get_or_create_chat_key(
+ &self,
+ http: &HttpClient,
+ master_key: &[u8],
+ ) -> Result<Vec<u8>, SyncError> {
+ if let Some(key) = self.load_chat_key_from_meta(master_key)? {
+ return Ok(key);
+ }
+
+ let remote = http.get_json_optional::<ChatKeyPayload>("/llmchat/chat/key", &[]);
+ let remote = match remote {
+ Ok(value) => value,
+ Err(SyncError::Http { status: 400, code: Some(code), .. })
+ if code == "AuthKeyNotCreated" =>
+ {
+ None
+ }
+ Err(err) => return Err(err),
+ };
+
+ if let Some(payload) = remote {
+ let encrypted = payload
+ .encrypted_value()
+ .ok_or_else(|| SyncError::InvalidResponse("missing encrypted chat key".to_string()))?;
+ let encrypted_payload = crate::models::EncryptedPayload {
+ encrypted_data: encrypted.to_string(),
+ header: payload.header.clone(),
+ };
+ let key = decrypt_chat_key(&encrypted_payload, master_key)?;
+ self.save_chat_key_to_meta(&payload)?;
+ return Ok(key);
+ }
+
+ let chat_key = keys::generate_stream_key();
+ let encrypted = encrypt_chat_key(&chat_key, master_key)?;
+ let payload = ChatKeyPayload::from_encrypted(&encrypted);
+ http.post_empty("/llmchat/chat/key", &payload)?;
+ self.save_chat_key_to_meta(&payload)?;
+ Ok(chat_key)
+ }
+}
+
+#[derive(Debug, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+struct UpsertSessionRequest {
+ session_uuid: String,
+ root_session_uuid: String,
+ branch_from_message_uuid: Option<String>,
+ encrypted_data: String,
+ header: String,
+ created_at: i64,
+}
+
+#[derive(Debug, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+struct UpsertMessageRequest {
+ message_uuid: String,
+ session_uuid: String,
+ parent_message_uuid: Option<String>,
+ sender: String,
+ attachments: Vec<RemoteAttachment>,
+ encrypted_data: String,
+ header: String,
+ created_at: i64,
+}
+
+fn blocked_messages(messages: &[Message], states: &HashMap<String, UploadState>) -> HashSet<Uuid> {
+ let mut blocked: HashSet<Uuid> = HashSet::new();
+ let mut children: HashMap<Uuid, Vec<Uuid>> = HashMap::new();
+
+ for message in messages {
+ let parent = message.parent_message_uuid;
+ if let Some(parent) = parent {
+ children.entry(parent).or_default().push(message.uuid);
+ }
+ let is_blocked = message.attachments.iter().any(|att| {
+ states
+ .get(&att.id)
+ .map(|state| *state != UploadState::Uploaded)
+ .unwrap_or(true)
+ });
+ if is_blocked {
+ blocked.insert(message.uuid);
+ }
+ }
+
+ let mut queue: Vec<Uuid> = blocked.iter().cloned().collect();
+ while let Some(current) = queue.pop() {
+ if let Some(kids) = children.get(&current) {
+ for child in kids {
+ if blocked.insert(*child) {
+ queue.push(*child);
+ }
+ }
+ }
+ }
+
+ blocked
+}
+
+fn infer_kind(name: &str) -> AttachmentKind {
+ let lower = name.to_ascii_lowercase();
+ if lower.ends_with(".png")
+ || lower.ends_with(".jpg")
+ || lower.ends_with(".jpeg")
+ || lower.ends_with(".gif")
+ || lower.ends_with(".webp")
+ || lower.ends_with(".heic")
+ || lower.ends_with(".bmp")
+ {
+ AttachmentKind::Image
+ } else {
+ AttachmentKind::Document
+ }
+}
+