Skip to content

armgit / ente

Public Imported from GitHub
0

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

Remove Ensu sync functionality

Manav Rathi24fd7587e0f1
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/AppViewModel.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/AppViewModel.kt
index 65f7c89e6a..0c99737dd3 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/AppViewModel.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/AppViewModel.kt
@@ -17,7 +17,6 @@ import io.ente.ensu.data.logging.FileLogRepository
import io.ente.ensu.data.storage.CredentialStore
import io.ente.ensu.data.llm.InferenceRsProvider
import io.ente.ensu.data.chat.RustChatRepository
-import io.ente.ensu.data.chat.RustChatSyncRepository
import io.ente.ensu.domain.model.LogLevel
import io.ente.ensu.domain.store.AppStore
import kotlinx.coroutines.flow.collectLatest
@@ -42,11 +41,6 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
deviceCapabilityProvider = deviceCapabilityProvider
)
private val chatRepository = RustChatRepository(application, credentialStore)
- private val chatSyncRepository = RustChatSyncRepository(
- context = application,
- credentialStore = credentialStore,
- endpointPreferences = endpointPreferences
- )
val ensuDefaults = runCatching { EnsuRustDefaults.load() }
.onFailure { error ->
logRepository.log(
@@ -62,7 +56,6 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
val store = AppStore(
sessionPreferences = sessionPreferences,
chatRepository = chatRepository,
- chatSyncRepository = chatSyncRepository,
llmProvider = llmProvider,
deviceCapabilityProvider = deviceCapabilityProvider,
ensuDefaults = ensuDefaults,
@@ -72,8 +65,6 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
context = application,
endpointPreferences = endpointPreferences,
credentialStore = credentialStore,
- chatRepository = chatRepository,
- chatSyncRepository = chatSyncRepository,
logRepository = logRepository
)
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt
index 21be364584..bcafcb31f2 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt
@@ -254,16 +254,6 @@ fun HomeView(
onDeleteSession = { session ->
deleteSessionTarget = session
},
- onSync = {
- store.syncNow(
- onSuccess = {
- Toast.makeText(context, "Sync complete", Toast.LENGTH_SHORT).show()
- },
- onError = { message ->
- Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
- }
- )
- },
onOpenSettings = {
navController.navigate(HomeRoute.Settings) {
launchSingleTop = true
@@ -367,7 +357,7 @@ fun HomeView(
if (deleteSessionTarget != null) {
NativeChoiceDialog(
title = "Delete Chat",
- body = "This will delete the chat and sync the change.",
+ body = "This will delete the chat from this device.",
firstButtonLabel = "Delete",
secondButtonLabel = "Cancel",
onFirst = {
@@ -430,7 +420,7 @@ fun HomeView(
if (isShowingSignOutDialog) {
NativeChoiceDialog(
title = "Sign Out",
- body = "Signing out will remove your online chats from this device. Offline chats stay available.",
+ body = "Signing out will remove your account from this device. Local chats stay available.",
firstButtonLabel = "Sign Out",
secondButtonLabel = "Cancel",
onFirst = {
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt
index 0a4aa73a03..e985a23698 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt
@@ -59,7 +59,6 @@ fun SessionDrawer(
userEmail: String?,
onSelectSession: (ChatSession) -> Unit,
onDeleteSession: (ChatSession) -> Unit,
- onSync: () -> Unit,
onOpenSettings: () -> Unit
) {
var searchQuery by remember { mutableStateOf("") }
@@ -86,10 +85,8 @@ fun SessionDrawer(
.windowInsetsPadding(WindowInsets.systemBars)
) {
DrawerHeader(
- isLoggedIn = isLoggedIn,
searchQuery = searchQuery,
- onSearchChange = { searchQuery = it },
- onSync = onSync
+ onSearchChange = { searchQuery = it }
)
HorizontalDivider(color = EnsuColor.border())
@@ -115,10 +112,8 @@ fun SessionDrawer(
@Composable
private fun DrawerHeader(
- isLoggedIn: Boolean,
searchQuery: String,
- onSearchChange: (String) -> Unit,
- onSync: () -> Unit
+ onSearchChange: (String) -> Unit
) {
Column(
modifier = Modifier
@@ -126,24 +121,6 @@ private fun DrawerHeader(
.background(EnsuColor.backgroundBase())
.padding(horizontal = EnsuSpacing.lg.dp, vertical = EnsuSpacing.md.dp)
) {
- if (isLoggedIn) {
- Row(
- modifier = Modifier.fillMaxWidth(),
- verticalAlignment = Alignment.CenterVertically
- ) {
- Spacer(modifier = Modifier.weight(1f))
-
- DrawerPrimaryTile(
- iconRes = HugeIcons.ArrowReloadHorizontalIcon,
- label = "Sync",
- onClick = onSync,
- isEnabled = true
- )
- }
-
- Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
- }
-
DrawerSearchControls(
query = searchQuery,
onQueryChange = onSearchChange,
@@ -153,37 +130,6 @@ private fun DrawerHeader(
}
}
-@Composable
-private fun DrawerPrimaryTile(
- iconRes: Int,
- label: String,
- onClick: () -> Unit,
- isEnabled: Boolean,
- modifier: Modifier = Modifier
-) {
- val tint = if (isEnabled) EnsuColor.textPrimary() else EnsuColor.textMuted()
-
- Row(
- modifier = modifier
- .clip(RoundedCornerShape(EnsuCornerRadius.card.dp))
- .background(EnsuColor.fillFaint())
- .clickable(enabled = isEnabled, onClick = onClick)
- .padding(horizontal = EnsuSpacing.lg.dp, vertical = EnsuSpacing.md.dp),
- verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.Center
- ) {
- Icon(
- painter = painterResource(iconRes),
- contentDescription = label,
- modifier = Modifier.size(18.dp),
- tint = tint
- )
- Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
- Text(text = label, style = EnsuTypography.body, color = tint)
- }
-}
-
-
@Composable
private fun DrawerSearchControls(
query: String,
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/EnsuAuthService.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/EnsuAuthService.kt
index e7286dd2b7..14dd2e17dd 100644
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/EnsuAuthService.kt
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/EnsuAuthService.kt
@@ -14,8 +14,6 @@ import io.ente.ensu.data.network.AuthorizationResponse
import io.ente.ensu.data.network.NetworkConfiguration
import io.ente.ensu.data.network.NetworkFactory
import io.ente.ensu.data.storage.CredentialStore
-import io.ente.ensu.domain.chat.ChatRepository
-import io.ente.ensu.domain.chat.ChatSyncRepository
import io.ente.ensu.domain.logging.LogRepository
import io.ente.ensu.domain.model.LogLevel
import kotlinx.coroutines.Dispatchers
@@ -32,8 +30,6 @@ class EnsuAuthService(
private val context: Context,
private val endpointPreferences: EndpointPreferencesDataStore,
private val credentialStore: CredentialStore,
- private val chatRepository: ChatRepository,
- private val chatSyncRepository: ChatSyncRepository,
private val logRepository: LogRepository
) {
private val authTokenProvider = EnsuAuthTokenProvider(credentialStore)
@@ -244,8 +240,6 @@ class EnsuAuthService(
suspend fun clearCredentials() {
credentialStore.clear()
- chatRepository.exitOnlineMode()
- chatSyncRepository.resetSyncState()
}
private suspend fun pingEndpoint(endpoint: HttpUrl) {
@@ -271,25 +265,8 @@ class EnsuAuthService(
val tokenBytes = secrets.token.toUByteArray().toByteArray()
val token = Base64.encodeToString(tokenBytes, Base64.NO_WRAP or Base64.URL_SAFE)
- if (!credentialStore.isSameUser(userId)) {
- chatSyncRepository.resetSyncState()
- }
-
credentialStore.save(email, userId, masterKey, secretKey, token)
- runCatching {
- val chatKey = chatSyncRepository.prepareOnlineDb()
- chatRepository.enterOnlineMode(chatKey)
- }.onFailure { error ->
- logRepository.log(
- LogLevel.Warning,
- "Failed to prepare online chat",
- details = error.message,
- tag = "Auth",
- throwable = error
- )
- }
-
// Best-effort zeroing of sensitive material after persisting.
masterKey.fill(0)
secretKey.fill(0)
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.kt
index 78b85a1769..f91b4888d1 100644
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.kt
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.kt
@@ -23,13 +23,10 @@ class RustChatRepository(
private val filePaths = FilePathManager(context)
private val attachmentsDir = filePaths.attachmentsDir
- private val offlineDbFile = filePaths.mainDbFile
- private val onlineDbFile = filePaths.onlineDbFile
- private val syncDbFile = filePaths.syncDbFile
- private var offlineDbKey = credentialStore.getOrCreateChatDbKey()
- private var onlineDbKey: ByteArray? = null
- private var usingOnlineDb = false
- private var db: EnsuDb = openDb(offlineDbFile, offlineDbKey)
+ private val dbFile = filePaths.mainDbFile
+ private val attachmentsDbFile = filePaths.attachmentsDbFile
+ private var dbKey = credentialStore.getOrCreateChatDbKey()
+ private var db: EnsuDb = openDb(dbFile, dbKey)
override fun listSessions(): List<ChatSession> = withDbRecovery {
val sessions = db.listSessions()
@@ -137,57 +134,34 @@ class RustChatRepository(
db.updateSessionTitle(sessionId, title)
}
- override fun enterOnlineMode(chatKey: ByteArray) {
- onlineDbKey = chatKey
- usingOnlineDb = true
- db = openDb(onlineDbFile, chatKey)
- }
-
- override fun exitOnlineMode() {
- usingOnlineDb = false
- onlineDbKey = null
- offlineDbKey = credentialStore.getOrCreateChatDbKey()
- db = openDb(offlineDbFile, offlineDbKey)
- }
-
override fun deleteAllData() {
- offlineDbFile.delete()
- onlineDbFile.delete()
- syncDbFile.delete()
- filePaths.encryptedAttachmentsDir.deleteRecursively()
- filePaths.syncMetaDir.deleteRecursively()
+ dbFile.delete()
+ attachmentsDbFile.delete()
filePaths.attachmentsDir.deleteRecursively()
- filePaths.plaintextAttachmentsDir.deleteRecursively()
- filePaths.encryptedAttachmentsDir.mkdirs()
- filePaths.syncMetaDir.mkdirs()
filePaths.attachmentsDir.mkdirs()
- filePaths.plaintextAttachmentsDir.mkdirs()
- usingOnlineDb = false
- onlineDbKey = null
- offlineDbKey = credentialStore.getOrCreateChatDbKey()
- db = openDb(offlineDbFile, offlineDbKey)
+ dbKey = credentialStore.getOrCreateChatDbKey()
+ db = openDb(dbFile, dbKey)
}
private fun openDb(dbFile: File, key: ByteArray): EnsuDb {
return EnsuDb.open(
dbFile.absolutePath,
- syncDbFile.absolutePath,
+ attachmentsDbFile.absolutePath,
key
)
}
private fun <T> withDbRecovery(block: () -> T): T {
- val targetDbFile = if (usingOnlineDb) onlineDbFile else offlineDbFile
- if (!syncDbFile.exists() || !targetDbFile.exists()) {
- reopenDb(targetDbFile)
+ if (!attachmentsDbFile.exists() || !dbFile.exists()) {
+ reopenDb()
}
return try {
block()
} catch (error: DbException) {
if (isReadonlyDbError(error)) {
- reopenDb(targetDbFile)
+ reopenDb()
return block()
}
if (shouldResetDb(error)) {
@@ -198,12 +172,12 @@ class RustChatRepository(
}
}
- private fun reopenDb(targetDbFile: File) {
- targetDbFile.parentFile?.mkdirs()
- syncDbFile.parentFile?.mkdirs()
- targetDbFile.setWritable(true)
- syncDbFile.setWritable(true)
- db = openDb(targetDbFile, currentDbKey())
+ private fun reopenDb() {
+ dbFile.parentFile?.mkdirs()
+ attachmentsDbFile.parentFile?.mkdirs()
+ dbFile.setWritable(true)
+ attachmentsDbFile.setWritable(true)
+ db = openDb(dbFile, dbKey)
}
private fun shouldResetDb(error: DbException): Boolean {
@@ -222,18 +196,9 @@ class RustChatRepository(
return message.contains("readonly database", ignoreCase = true)
}
- private fun currentDbKey(): ByteArray {
- return if (usingOnlineDb) {
- onlineDbKey ?: throw IllegalStateException("Missing online DB key")
- } else {
- offlineDbKey
- }
- }
-
private fun resetDb() {
- val targetDbFile = if (usingOnlineDb) onlineDbFile else offlineDbFile
- targetDbFile.delete()
- syncDbFile.delete()
- db = openDb(targetDbFile, currentDbKey())
+ dbFile.delete()
+ attachmentsDbFile.delete()
+ db = openDb(dbFile, dbKey)
}
}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatSyncRepository.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatSyncRepository.kt
deleted file mode 100644
index d3cead25ba..0000000000
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatSyncRepository.kt
+++ /dev/null
@@ -1,215 +0,0 @@
-package io.ente.ensu.data.chat
-
-import android.content.Context
-import io.ente.ensu.data.EndpointPreferencesDataStore
-import io.ente.ensu.data.network.NetworkConfiguration
-import io.ente.ensu.data.storage.CredentialStore
-import io.ente.ensu.data.storage.FilePathManager
-import io.ente.ensu.domain.chat.ChatSyncRepository
-import io.ente.ensu.domain.model.MigrationConfig as DomainMigrationConfig
-import io.ente.ensu.domain.model.MigrationPriority as DomainMigrationPriority
-import io.ente.ensu.domain.model.MigrationProgress as DomainMigrationProgress
-import io.ente.ensu.domain.model.MigrationState as DomainMigrationState
-import io.ente.labs.ensu_sync.EnsuSync
-import io.ente.labs.ensu_sync.MigrationConfig as RustMigrationConfig
-import io.ente.labs.ensu_sync.MigrationPriority as RustMigrationPriority
-import io.ente.labs.ensu_sync.MigrationProgress as RustMigrationProgress
-import io.ente.labs.ensu_sync.MigrationProgressCallback
-import io.ente.labs.ensu_sync.MigrationState as RustMigrationState
-import io.ente.labs.ensu_sync.SyncAuth
-import io.ente.labs.ensu_sync.SyncException
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.flow.first
-import kotlinx.coroutines.withContext
-
-class RustChatSyncRepository(
- private val context: Context,
- private val credentialStore: CredentialStore,
- private val endpointPreferences: EndpointPreferencesDataStore
-) : ChatSyncRepository {
-
- private val filePaths = FilePathManager(context)
- private var syncEngine: EnsuSync? = null
- private var chatKey: ByteArray? = null
-
- override suspend fun sync() {
- withContext(Dispatchers.IO) {
- try {
- ensureSyncEngine().sync(buildAuth())
- } catch (err: Throwable) {
- if (shouldResetSync(err)) {
- resetSyncStateInternal()
- try {
- ensureSyncEngine().sync(buildAuth())
- return@withContext
- } catch (retryErr: Throwable) {
- throw IllegalStateException(syncErrorMessage(retryErr), retryErr)
- }
- }
- throw IllegalStateException(syncErrorMessage(err), err)
- }
- }
- }
-
- override suspend fun syncWithProgress(
- config: DomainMigrationConfig,
- onProgress: (DomainMigrationProgress) -> Unit
- ) {
- withContext(Dispatchers.IO) {
- val callback = object : MigrationProgressCallback {
- override fun onProgress(progress: RustMigrationProgress) {
- onProgress(progress.toDomain())
- }
- }
- ensureSyncEngine().syncWithProgress(buildAuth(), config.toRust(), callback)
- }
- }
-
- override suspend fun checkMigrationStatusLocal(): DomainMigrationState? {
- return withContext(Dispatchers.IO) {
- runCatching { syncEngine?.checkMigrationStatusLocal() }
- .getOrNull()
- ?.toDomain()
- }
- }
-
- override suspend fun checkMigrationStatus(): DomainMigrationState {
- return withContext(Dispatchers.IO) {
- ensureSyncEngine().checkMigrationStatus(buildAuth()).toDomain()
- }
- }
-
- override suspend fun downloadAttachment(attachmentId: String, sessionId: String): Boolean {
- return withContext(Dispatchers.IO) {
- ensureSyncEngine().downloadAttachment(attachmentId, sessionId, buildAuth())
- }
- }
-
- override suspend fun prepareOnlineDb(): ByteArray {
- return withContext(Dispatchers.IO) {
- resetSyncStateInternal()
- val auth = buildAuth()
- val key = io.ente.labs.ensu_sync.fetchChatKey(auth, filePaths.syncDbFile.absolutePath)
- chatKey = key
- val engine = buildSyncEngine(key).also { syncEngine = it }
- val offlineKey = credentialStore.getOrCreateChatDbKey()
- engine.seedFromOffline(filePaths.mainDbFile.absolutePath, offlineKey)
- key
- }
- }
-
- override suspend fun resetSyncState() {
- withContext(Dispatchers.IO) {
- resetSyncStateInternal()
- }
- }
-
- private suspend fun ensureSyncEngine(): EnsuSync {
- return syncEngine ?: run {
- val key = chatKey ?: prepareOnlineDb()
- buildSyncEngine(key).also { syncEngine = it }
- }
- }
-
- private fun buildSyncEngine(dbKey: ByteArray): EnsuSync {
- return EnsuSync.open(
- mainDbPath = filePaths.onlineDbFile.absolutePath,
- attachmentsDbPath = filePaths.syncDbFile.absolutePath,
- dbKey = dbKey,
- attachmentsDir = filePaths.encryptedAttachmentsDir.absolutePath,
- metaDir = filePaths.syncMetaDir.absolutePath,
- plaintextDir = filePaths.plaintextAttachmentsDir.absolutePath
- )
- }
-
- private suspend fun buildAuth(): SyncAuth {
- val endpoint = endpointPreferences.endpointFlow.first()
- val baseUrl = endpoint ?: NetworkConfiguration.default.apiEndpoint.toString()
- val token = credentialStore.getToken()?.let(::normalizeToken)
- ?: throw IllegalStateException("Missing auth token")
- val masterKey = credentialStore.getMasterKey()
- ?: throw IllegalStateException("Missing master key")
-
- val clientVersion = runCatching {
- context.packageManager.getPackageInfo(context.packageName, 0).versionName
- }.getOrNull()
-
- return SyncAuth(
- baseUrl = baseUrl,
- authToken = token,
- masterKey = masterKey,
- userAgent = "EnteNative-Android",
- clientPackage = context.packageName,
- clientVersion = clientVersion
- )
- }
-
- private fun normalizeToken(token: String): String {
- val remainder = token.length % 4
- return if (remainder == 0) token else token + "=".repeat(4 - remainder)
- }
-
- private fun shouldResetSync(error: Throwable): Boolean {
- val message = syncErrorMessage(error)
- return ChatRecovery.shouldResetFromMessage(message)
- }
-
- private fun resetSyncStateInternal() {
- runCatching { syncEngine?.resetSyncState() }
- syncEngine = null
- chatKey = null
- filePaths.onlineDbFile.delete()
- filePaths.syncDbFile.delete()
- filePaths.syncMetaDir.deleteRecursively()
- filePaths.encryptedAttachmentsDir.deleteRecursively()
- filePaths.encryptedAttachmentsDir.mkdirs()
- filePaths.syncMetaDir.mkdirs()
- }
-
- private fun syncErrorMessage(error: Throwable): String {
- val syncMessage = generateSequence(error) { it.cause }
- .filterIsInstance<SyncException.Message>()
- .firstOrNull()
- if (syncMessage != null) {
- return syncMessage.v1
- }
-
- val inProgress = generateSequence(error) { it.cause }
- .filterIsInstance<SyncException.SyncInProgress>()
- .firstOrNull()
- if (inProgress != null) {
- return "Sync already in progress"
- }
-
- val rootCause = generateSequence(error) { it.cause }.lastOrNull() ?: error
- return rootCause.message ?: error.message ?: rootCause.toString()
- }
-
- private fun DomainMigrationConfig.toRust(): RustMigrationConfig {
- return RustMigrationConfig(
- batchSize = batchSize,
- priority = when (priority) {
- DomainMigrationPriority.RECENT_FIRST -> RustMigrationPriority.RECENT_FIRST
- DomainMigrationPriority.OLDEST_FIRST -> RustMigrationPriority.OLDEST_FIRST
- }
- )
- }
-
- private fun RustMigrationState.toDomain(): DomainMigrationState {
- return when (this) {
- RustMigrationState.NOT_NEEDED -> DomainMigrationState.NOT_NEEDED
- RustMigrationState.IN_PROGRESS -> DomainMigrationState.IN_PROGRESS
- RustMigrationState.COMPLETE -> DomainMigrationState.COMPLETE
- RustMigrationState.FAILED -> DomainMigrationState.FAILED
- }
- }
-
- private fun RustMigrationProgress.toDomain(): DomainMigrationProgress {
- return DomainMigrationProgress(
- state = state.toDomain(),
- processed = processed,
- remaining = remaining,
- total = total
- )
- }
-}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/storage/FilePathManager.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/storage/FilePathManager.kt
index 3285396804..4c88d62ff7 100644
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/storage/FilePathManager.kt
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/storage/FilePathManager.kt
@@ -7,12 +7,7 @@ class FilePathManager(context: Context) {
private val appDataDir: File = ensureDir(context.filesDir)
val attachmentsDir: File = ensureDir(File(appDataDir, "attachments"))
val mainDbFile: File = File(appDataDir, "llmchat.db")
- val onlineDbFile: File = File(appDataDir, "llmchat_online.db")
- val syncDbFile: File = File(appDataDir, "llmchat_sync.db")
- val syncBaseDir: File = ensureDir(File(appDataDir, "llmchat"))
- val encryptedAttachmentsDir: File = ensureDir(File(syncBaseDir, "chat_attachments_encrypted"))
- val syncMetaDir: File = ensureDir(File(syncBaseDir, "sync_meta"))
- val plaintextAttachmentsDir: File = attachmentsDir
+ val attachmentsDbFile: File = File(appDataDir, "llmchat_sync.db")
private fun ensureDir(dir: File): File {
if (!dir.exists()) {
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/chat/ChatRepository.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/chat/ChatRepository.kt
index f5afc42e7c..5bcf3f86e1 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/chat/ChatRepository.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/chat/ChatRepository.kt
@@ -22,7 +22,5 @@ interface ChatRepository {
fun updateMessageText(messageId: String, text: String)
fun updateSessionTitle(sessionId: String, title: String)
- fun enterOnlineMode(chatKey: ByteArray)
- fun exitOnlineMode()
fun deleteAllData()
}
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/chat/ChatSyncRepository.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/chat/ChatSyncRepository.kt
deleted file mode 100644
index 831fdc5d3f..0000000000
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/chat/ChatSyncRepository.kt
+++ /dev/null
@@ -1,15 +0,0 @@
-package io.ente.ensu.domain.chat
-
-import io.ente.ensu.domain.model.MigrationConfig
-import io.ente.ensu.domain.model.MigrationProgress
-import io.ente.ensu.domain.model.MigrationState
-
-interface ChatSyncRepository {
- suspend fun sync()
- suspend fun syncWithProgress(config: MigrationConfig, onProgress: (MigrationProgress) -> Unit)
- suspend fun checkMigrationStatusLocal(): MigrationState?
- suspend fun checkMigrationStatus(): MigrationState
- suspend fun downloadAttachment(attachmentId: String, sessionId: String): Boolean
- suspend fun prepareOnlineDb(): ByteArray
- suspend fun resetSyncState()
-}
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/MigrationModels.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/MigrationModels.kt
deleted file mode 100644
index 0f8f56bba6..0000000000
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/MigrationModels.kt
+++ /dev/null
@@ -1,25 +0,0 @@
-package io.ente.ensu.domain.model
-
-data class MigrationConfig(
- val batchSize: Long,
- val priority: MigrationPriority
-)
-
-enum class MigrationPriority {
- RECENT_FIRST,
- OLDEST_FIRST
-}
-
-enum class MigrationState {
- NOT_NEEDED,
- IN_PROGRESS,
- COMPLETE,
- FAILED
-}
-
-data class MigrationProgress(
- val state: MigrationState,
- val processed: Long,
- val remaining: Long,
- val total: Long
-)
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/AppState.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/AppState.kt
index a991b89f8e..33b7af9159 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/AppState.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/AppState.kt
@@ -7,6 +7,5 @@ data class AppState(
val auth: AuthState = AuthState(),
val chat: ChatState = ChatState(),
val developerSettings: DeveloperSettingsState = DeveloperSettingsState(),
- val modelSettings: ModelSettingsState = ModelSettingsState(),
- val sync: SyncState = SyncState.Idle
+ val modelSettings: ModelSettingsState = ModelSettingsState()
)
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/SyncState.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/SyncState.kt
deleted file mode 100644
index 089b1141b8..0000000000
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/SyncState.kt
+++ /dev/null
@@ -1,8 +0,0 @@
-package io.ente.ensu.domain.state
-
-sealed class SyncState {
- data object Idle : SyncState()
- data object Syncing : SyncState()
- data class Migrating(val processed: Long, val total: Long) : SyncState()
- data class Error(val message: String) : SyncState()
-}
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.kt
index c610986d2b..de272f16e9 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.kt
@@ -1,7 +1,6 @@
package io.ente.ensu.domain.store
import io.ente.ensu.domain.chat.ChatRepository
-import io.ente.ensu.domain.chat.ChatSyncRepository
import io.ente.ensu.domain.device.ChatDeviceCapability
import io.ente.ensu.domain.device.DeviceCapabilityProvider
import io.ente.ensu.domain.device.UnknownDeviceCapabilityProvider
@@ -25,7 +24,6 @@ import kotlinx.coroutines.launch
class AppStore(
private val sessionPreferences: SessionPreferences,
private val chatRepository: ChatRepository,
- private val chatSyncRepository: ChatSyncRepository? = null,
private val llmProvider: LlmProvider,
private val deviceCapabilityProvider: DeviceCapabilityProvider = UnknownDeviceCapabilityProvider,
val ensuDefaults: EnsuDefaults,
@@ -36,10 +34,9 @@ class AppStore(
val state: StateFlow<AppState> = _state.asStateFlow()
private val messageStore = mutableMapOf<String, MutableList<ChatMessage>>()
- private val attachmentActions = AttachmentStoreActions(_state, chatSyncRepository, messageStore)
+ private val attachmentActions = AttachmentStoreActions(_state, messageStore)
private val modelSettingsActions =
ModelSettingsActions(_state, sessionPreferences, llmProvider, logRepository, ensuDefaults)
- private val syncActions = SyncStoreActions(_state, chatSyncRepository, logRepository)
private val chatActions = ChatStoreActions(
state = _state,
sessionPreferences = sessionPreferences,
@@ -49,22 +46,14 @@ class AppStore(
logRepository = logRepository,
messageStore = messageStore,
attachmentActions = attachmentActions,
- syncActions = syncActions,
modelSettingsActions = modelSettingsActions,
ensuDefaults = ensuDefaults
)
- private val authActions = AuthStoreActions(_state, logRepository) {
- syncActions.syncAfterLogin()
- }
-
- init {
- syncActions.setReloadSessions { chatActions.loadSessionsFromDb() }
- }
+ private val authActions = AuthStoreActions(_state, logRepository)
fun bootstrap(scope: CoroutineScope) {
chatActions.setScope(scope)
attachmentActions.setScope(scope)
- syncActions.setScope(scope)
modelSettingsActions.setScope(scope)
refreshDeviceCapability(scope)
chatActions.bootstrap(scope)
@@ -199,11 +188,6 @@ class AppStore(
chatActions.handleLogout()
}
- fun syncNow(
- onSuccess: (() -> Unit)? = null,
- onError: ((String) -> Unit)? = null
- ) = syncActions.syncNow(onSuccess, onError)
-
fun cancelAttachmentDownload(attachmentId: String) =
attachmentActions.cancelAttachmentDownload(attachmentId)
}
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AttachmentStoreActions.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AttachmentStoreActions.kt
index bf98ee979b..96238831d3 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AttachmentStoreActions.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AttachmentStoreActions.kt
@@ -1,6 +1,5 @@
package io.ente.ensu.domain.store
-import io.ente.ensu.domain.chat.ChatSyncRepository
import io.ente.ensu.domain.model.Attachment
import io.ente.ensu.domain.model.AttachmentDownloadItem
import io.ente.ensu.domain.model.AttachmentDownloadStatus
@@ -21,7 +20,6 @@ import java.util.concurrent.ConcurrentLinkedDeque
internal class AttachmentStoreActions(
private val state: MutableStateFlow<AppState>,
- private val chatSyncRepository: ChatSyncRepository?,
private val messageStore: MutableMap<String, MutableList<ChatMessage>>
) {
private val attachmentDownloads = ConcurrentHashMap<String, AttachmentDownloadItem>()
@@ -183,19 +181,10 @@ internal class AttachmentStoreActions(
updateAttachmentDownloadState()
val job = scope.launch(Dispatchers.IO) {
- val result = runCatching {
- chatSyncRepository?.downloadAttachment(id, item.sessionId)
- ?: throw IllegalStateException("Sync unavailable")
- }
- val status = if (result.isSuccess) {
- AttachmentDownloadStatus.Completed
- } else {
- AttachmentDownloadStatus.Failed
- }
withContext(Dispatchers.Main) {
attachmentDownloads[id]?.let { current ->
if (current.status != AttachmentDownloadStatus.Canceled) {
- attachmentDownloads[id] = current.copy(status = status)
+ attachmentDownloads[id] = current.copy(status = AttachmentDownloadStatus.Failed)
}
}
attachmentDownloadActive.remove(id)
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AuthStoreActions.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AuthStoreActions.kt
index 456e05ac61..eb21c1559c 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AuthStoreActions.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AuthStoreActions.kt
@@ -9,8 +9,7 @@ import kotlinx.coroutines.flow.update
internal class AuthStoreActions(
private val state: MutableStateFlow<AppState>,
- private val logRepository: LogRepository,
- private val onSync: () -> Unit
+ private val logRepository: LogRepository
) {
fun signIn(email: String) {
state.update { appState ->
@@ -18,7 +17,6 @@ internal class AuthStoreActions(
}
// Do not log PII like user email.
logRepository.log(LogLevel.Info, "Signed in", tag = "Auth")
- onSync()
}
fun signOut() {
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt
index 78e9b1ad9c..3b4f91fedb 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt
@@ -43,7 +43,6 @@ internal class ChatStoreActions(
private val logRepository: LogRepository,
private val messageStore: MutableMap<String, MutableList<ChatMessage>>,
private val attachmentActions: AttachmentStoreActions,
- private val syncActions: SyncStoreActions,
private val modelSettingsActions: ModelSettingsActions,
private val ensuDefaults: EnsuDefaults
) {
@@ -216,7 +215,6 @@ internal class ChatStoreActions(
trimSessionCaches(sessions.map { it.id }.toSet())
scope?.launch { sessionPreferences.setSelectedSessionId(newCurrent) }
- syncActions.syncNow()
logRepository.log(LogLevel.Info, "Session deleted", tag = "Chat")
}
@@ -309,7 +307,6 @@ internal class ChatStoreActions(
}
llmProvider.resetContext()
startGeneration(sessionId, parent)
- syncActions.requestSync()
}
fun sendMessage() {
@@ -359,7 +356,6 @@ internal class ChatStoreActions(
updateCurrentSessionPreview(sessionId, text, timestamp)
rebuildChatState(sessionId)
startGeneration(sessionId, userMessage)
- syncActions.requestSync()
logRepository.log(
LogLevel.Info,
"Message sent",
@@ -531,7 +527,6 @@ internal class ChatStoreActions(
throwable = err
)
}
- syncActions.syncAfterGeneration()
return@launch
}
@@ -712,7 +707,6 @@ internal class ChatStoreActions(
)
)
}
- syncActions.syncAfterGeneration()
}
scheduleSessionSummary(sessionId)
}
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/SyncStoreActions.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/SyncStoreActions.kt
deleted file mode 100644
index 93f05c0b7b..0000000000
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/SyncStoreActions.kt
+++ /dev/null
@@ -1,231 +0,0 @@
-package io.ente.ensu.domain.store
-
-import io.ente.ensu.domain.chat.ChatSyncRepository
-import io.ente.ensu.domain.logging.LogRepository
-import io.ente.ensu.domain.model.LogLevel
-import io.ente.ensu.domain.model.MigrationConfig
-import io.ente.ensu.domain.model.MigrationPriority
-import io.ente.ensu.domain.model.MigrationProgress
-import io.ente.ensu.domain.model.MigrationState
-import io.ente.ensu.domain.state.AppState
-import io.ente.ensu.domain.state.SyncState
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.flow.MutableStateFlow
-import kotlinx.coroutines.flow.update
-import kotlinx.coroutines.launch
-import kotlinx.coroutines.withContext
-
-internal class SyncStoreActions(
- private val state: MutableStateFlow<AppState>,
- private val chatSyncRepository: ChatSyncRepository?,
- private val logRepository: LogRepository
-) {
- private var scope: CoroutineScope? = null
- private var pendingSyncRequested = false
- private var pendingSyncErrorHandler: ((String) -> Unit)? = null
- private var pendingSyncSuccessHandler: (() -> Unit)? = null
- private var reloadSessions: (() -> Unit)? = null
- private val migrationConfig = MigrationConfig(
- batchSize = 25L,
- priority = MigrationPriority.RECENT_FIRST
- )
-
- fun setScope(scope: CoroutineScope) {
- this.scope = scope
- }
-
- fun setReloadSessions(loader: () -> Unit) {
- reloadSessions = loader
- }
-
- fun syncNow(
- onSuccess: (() -> Unit)? = null,
- onError: ((String) -> Unit)? = null
- ) {
- requestSync(onSuccess, onError)
- }
-
- fun syncAfterLogin() {
- val scope = scope ?: return
- scope.launch {
- val repo = chatSyncRepository ?: return@launch
- try {
- val localStatus: MigrationState? = withContext(Dispatchers.IO) {
- repo.checkMigrationStatusLocal()
- }
- when (localStatus) {
- MigrationState.IN_PROGRESS -> performBatchedSync()
- MigrationState.NOT_NEEDED, MigrationState.COMPLETE -> performSyncInternal()
- MigrationState.FAILED -> {
- state.update { it.copy(sync = SyncState.Error("Migration failed")) }
- }
- else -> {
- val status: MigrationState = withContext(Dispatchers.IO) {
- repo.checkMigrationStatus()
- }
- when (status) {
- MigrationState.IN_PROGRESS -> performBatchedSync()
- MigrationState.NOT_NEEDED, MigrationState.COMPLETE -> performSyncInternal()
- MigrationState.FAILED -> {
- state.update { it.copy(sync = SyncState.Error("Migration failed")) }
- }
- else -> {}
- }
- }
- }
- } catch (err: Throwable) {
- val message = syncErrorMessage(err)
- logRepository.log(
- LogLevel.Warning,
- "Migration status check failed",
- details = message,
- tag = "Sync",
- throwable = err
- )
- }
- }
- }
-
- fun requestSync(
- onSuccess: (() -> Unit)? = null,
- onError: ((String) -> Unit)? = null
- ) {
- if (state.value.chat.isGenerating) {
- pendingSyncRequested = true
- if (onError != null) {
- pendingSyncErrorHandler = onError
- }
- if (onSuccess != null) {
- pendingSyncSuccessHandler = onSuccess
- }
- return
- }
-
- val handler = pendingSyncErrorHandler ?: onError
- val successHandler = pendingSyncSuccessHandler ?: onSuccess
- pendingSyncRequested = false
- pendingSyncErrorHandler = null
- pendingSyncSuccessHandler = null
- performSync(handler, successHandler)
- }
-
- fun syncAfterGeneration() {
- val handler = pendingSyncErrorHandler
- val successHandler = pendingSyncSuccessHandler
- val shouldAutoSync = state.value.auth.isLoggedIn
- if (!pendingSyncRequested && !shouldAutoSync) {
- pendingSyncErrorHandler = null
- pendingSyncSuccessHandler = null
- return
- }
- if (!shouldAutoSync && handler == null && successHandler == null) {
- pendingSyncRequested = false
- pendingSyncErrorHandler = null
- pendingSyncSuccessHandler = null
- return
- }
- pendingSyncRequested = false
- pendingSyncErrorHandler = null
- pendingSyncSuccessHandler = null
- performSync(handler, successHandler)
- }
-
- private fun performSync(
- onError: ((String) -> Unit)? = null,
- onSuccess: (() -> Unit)? = null
- ) {
- val scope = scope ?: return
- scope.launch {
- performSyncInternal(onError, onSuccess)
- }
- }
-
- private suspend fun performSyncInternal(
- onError: ((String) -> Unit)? = null,
- onSuccess: (() -> Unit)? = null
- ) {
- val repo = chatSyncRepository ?: return
- if (!state.value.auth.isLoggedIn) {
- state.update { it.copy(sync = SyncState.Idle) }
- return
- }
- try {
- state.update { it.copy(sync = SyncState.Syncing) }
- logRepository.log(LogLevel.Info, "Sync started", tag = "Sync")
- withContext(Dispatchers.IO) {
- repo.sync()
- }
- reloadSessions?.invoke()
- logRepository.log(LogLevel.Info, "Sync success", tag = "Sync")
- state.update { it.copy(sync = SyncState.Idle) }
- if (onSuccess != null) {
- withContext(Dispatchers.Main) {
- onSuccess()
- }
- }
- } catch (err: Throwable) {
- val message = syncErrorMessage(err)
- logRepository.log(
- LogLevel.Error,
- "Sync failed",
- details = message,
- tag = "Sync",
- throwable = err
- )
- state.update { it.copy(sync = SyncState.Error(message)) }
- if (onError != null) {
- withContext(Dispatchers.Main) {
- onError(formatSyncErrorMessage(message))
- }
- }
- }
- }
-
- private fun formatSyncErrorMessage(message: String): String {
- val normalized = message.trim().lowercase()
- return if (normalized.contains("sync already in progress")) {
- message
- } else {
- "Sync failed: $message"
- }
- }
-
- private suspend fun performBatchedSync() {
- val repo = chatSyncRepository ?: return
- try {
- state.update { it.copy(sync = SyncState.Migrating(0, 0)) }
- withContext(Dispatchers.IO) {
- repo.syncWithProgress(migrationConfig) { progress: MigrationProgress ->
- state.update {
- it.copy(sync = SyncState.Migrating(progress.processed, progress.total))
- }
- }
- }
- reloadSessions?.invoke()
- state.update { it.copy(sync = SyncState.Idle) }
- } catch (err: Throwable) {
- val message = syncErrorMessage(err)
- logRepository.log(
- LogLevel.Error,
- "Migration sync failed",
- details = message,
- tag = "Sync",
- throwable = err
- )
- state.update { it.copy(sync = SyncState.Error(message)) }
- }
- }
-
- private fun syncErrorMessage(error: Throwable): String {
- var current: Throwable? = error
- while (current != null) {
- val message = current.message
- if (!message.isNullOrBlank()) {
- return message
- }
- current = current.cause
- }
- return "Unknown error"
- }
-}
diff --git a/mobile/native/android/packages/rust/scripts/build-rust.sh b/mobile/native/android/packages/rust/scripts/build-rust.sh
index ea95eae431..baf063b79c 100755
--- a/mobile/native/android/packages/rust/scripts/build-rust.sh
+++ b/mobile/native/android/packages/rust/scripts/build-rust.sh
@@ -13,7 +13,6 @@ OUT_DIR=""
CRATES=(
bindings/uniffi/core
bindings/uniffi/ensu/db
- bindings/uniffi/ensu/sync
bindings/uniffi/ensu/inference
bindings/uniffi/ensu/transcription
)
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu.xcodeproj/project.pbxproj b/mobile/native/darwin/Apps/Ensu/Ensu.xcodeproj/project.pbxproj
index ce6412021d..ffd23feac7 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu.xcodeproj/project.pbxproj
+++ b/mobile/native/darwin/Apps/Ensu/Ensu.xcodeproj/project.pbxproj
@@ -136,7 +136,7 @@
isa = PBXNativeTarget;
buildConfigurationList = DA72BC872E5F87A100D128FF /* Build configuration list for PBXNativeTarget "Ensu" */;
buildPhases = (
- CC142736A470612F436ECF8E /* Build Rust (core/db/sync/inference/transcription) */,
+ CC142736A470612F436ECF8E /* Build Rust (core/db/inference/transcription) */,
DA72BC5D2E5F87A000D128FF /* Sources */,
DA72BC5E2E5F87A000D128FF /* Frameworks */,
DA72BC5F2E5F87A000D128FF /* Resources */,
@@ -224,18 +224,17 @@
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
- CC142736A470612F436ECF8E /* Build Rust (core/db/sync/inference/transcription) */ = {
+ CC142736A470612F436ECF8E /* Build Rust (core/db/inference/transcription) */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
- name = "Build Rust (core/db/sync/inference/transcription)";
+ name = "Build Rust (core/db/inference/transcription)";
outputPaths = (
"$(TARGET_TEMP_DIR)/ensu_rust/libcore.a",
"$(TARGET_TEMP_DIR)/ensu_rust/libdb.a",
- "$(TARGET_TEMP_DIR)/ensu_rust/libsync.a",
"$(TARGET_TEMP_DIR)/ensu_rust/libinference.a",
"$(TARGET_TEMP_DIR)/ensu_rust/libtranscription.a",
"$(SRCROOT)/Ensu/Generated/EndpointConfig.swift",
@@ -288,7 +287,7 @@
);
IPHONEOS_DEPLOYMENT_TARGET = 16.0;
MARKETING_VERSION = 0.1.18;
- OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/coreFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/dbFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/syncFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/inferenceFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/transcriptionFFI.modulemap";
+ OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/coreFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/dbFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/inferenceFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/transcriptionFFI.modulemap";
PRODUCT_BUNDLE_IDENTIFIER = io.ente.ensu.tests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
@@ -314,7 +313,7 @@
);
IPHONEOS_DEPLOYMENT_TARGET = 16.0;
MARKETING_VERSION = 0.1.18;
- OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/coreFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/dbFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/syncFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/inferenceFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/transcriptionFFI.modulemap";
+ OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/coreFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/dbFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/inferenceFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/transcriptionFFI.modulemap";
PRODUCT_BUNDLE_IDENTIFIER = io.ente.ensu.tests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
@@ -492,11 +491,10 @@
"-force_load",
"$(TARGET_TEMP_DIR)/ensu_rust/libcore.a",
"$(TARGET_TEMP_DIR)/ensu_rust/libdb.a",
- "$(TARGET_TEMP_DIR)/ensu_rust/libsync.a",
"$(TARGET_TEMP_DIR)/ensu_rust/libinference.a",
"$(TARGET_TEMP_DIR)/ensu_rust/libtranscription.a",
);
- OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/coreFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/dbFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/syncFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/inferenceFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/transcriptionFFI.modulemap";
+ OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/coreFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/dbFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/inferenceFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/transcriptionFFI.modulemap";
PRODUCT_BUNDLE_IDENTIFIER = io.ente.ensu;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
@@ -551,11 +549,10 @@
"-force_load",
"$(TARGET_TEMP_DIR)/ensu_rust/libcore.a",
"$(TARGET_TEMP_DIR)/ensu_rust/libdb.a",
- "$(TARGET_TEMP_DIR)/ensu_rust/libsync.a",
"$(TARGET_TEMP_DIR)/ensu_rust/libinference.a",
"$(TARGET_TEMP_DIR)/ensu_rust/libtranscription.a",
);
- OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/coreFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/dbFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/syncFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/inferenceFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/transcriptionFFI.modulemap";
+ OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/coreFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/dbFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/inferenceFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/transcriptionFFI.modulemap";
PRODUCT_BUNDLE_IDENTIFIER = io.ente.ensu;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "$(APP_STORE_PROFILE_SPECIFIER)";
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatDataCleaner.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatDataCleaner.swift
index ee78075c2f..d71dfa4212 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatDataCleaner.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatDataCleaner.swift
@@ -7,35 +7,11 @@ enum ChatDataCleaner {
let dbDir = baseDir.appendingPathComponent("llmchat", isDirectory: true)
let mainDbUrl = dbDir.appendingPathComponent("llmchat.db")
- let syncDbUrl = dbDir.appendingPathComponent("llmchat_sync.db")
- let onlineDbUrl = dbDir.appendingPathComponent("llmchat_online.db")
+ let attachmentsDbUrl = dbDir.appendingPathComponent("llmchat_sync.db")
let attachmentsDirUrl = dbDir.appendingPathComponent("chat_attachments", isDirectory: true)
- let encryptedAttachmentsDirUrl = dbDir.appendingPathComponent("chat_attachments_encrypted", isDirectory: true)
- let metaDirUrl = dbDir.appendingPathComponent("sync_meta", isDirectory: true)
- let plaintextDirUrl = attachmentsDirUrl
try? FileManager.default.removeItem(at: mainDbUrl)
- try? FileManager.default.removeItem(at: syncDbUrl)
- try? FileManager.default.removeItem(at: onlineDbUrl)
+ try? FileManager.default.removeItem(at: attachmentsDbUrl)
try? FileManager.default.removeItem(at: attachmentsDirUrl)
- try? FileManager.default.removeItem(at: encryptedAttachmentsDirUrl)
- try? FileManager.default.removeItem(at: metaDirUrl)
- try? FileManager.default.removeItem(at: plaintextDirUrl)
- }
-
- static func deleteSyncState() {
- let baseDir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
- ?? FileManager.default.temporaryDirectory
- let dbDir = baseDir.appendingPathComponent("llmchat", isDirectory: true)
-
- let syncDbUrl = dbDir.appendingPathComponent("llmchat_sync.db")
- let onlineDbUrl = dbDir.appendingPathComponent("llmchat_online.db")
- let metaDirUrl = dbDir.appendingPathComponent("sync_meta", isDirectory: true)
- let encryptedAttachmentsDirUrl = dbDir.appendingPathComponent("chat_attachments_encrypted", isDirectory: true)
-
- try? FileManager.default.removeItem(at: syncDbUrl)
- try? FileManager.default.removeItem(at: onlineDbUrl)
- try? FileManager.default.removeItem(at: metaDirUrl)
- try? FileManager.default.removeItem(at: encryptedAttachmentsDirUrl)
}
}
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatView.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatView.swift
index a93f299f5e..7dc9970e99 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatView.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatView.swift
@@ -20,8 +20,6 @@ struct ChatView: View {
private var toastTrigger: ToastTrigger {
ToastTrigger(
- syncError: viewModel.syncErrorMessage,
- syncSuccess: viewModel.syncSuccessMessage,
generationError: viewModel.generationErrorMessage
)
}
@@ -444,9 +442,6 @@ struct ChatView: View {
onDeleteSession: { session in
viewState.deleteSession = session
},
- onSync: {
- viewModel.syncNow(showErrors: true, showSuccess: true)
- },
onOpenSettings: {
viewState.isDrawerOpen = false
viewState.showSettings = true
@@ -464,16 +459,6 @@ struct ChatView: View {
}
private func handleToastTrigger(_ trigger: ToastTrigger) {
- if let message = trigger.syncError {
- showToast(message, duration: 2)
- viewModel.syncErrorMessage = nil
- return
- }
- if let message = trigger.syncSuccess {
- showToast(message, duration: 2)
- viewModel.syncSuccessMessage = nil
- return
- }
if let message = trigger.generationError {
showToast(message, duration: 2)
viewModel.generationErrorMessage = nil
@@ -538,8 +523,6 @@ private final class ChatViewState: ObservableObject {
}
private struct ToastTrigger: Equatable {
- let syncError: String?
- let syncSuccess: String?
let generationError: String?
}
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatViewModel.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatViewModel.swift
index 294480fe80..029e5f00fc 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatViewModel.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatViewModel.swift
@@ -3,48 +3,6 @@ import SwiftUI
#if canImport(EnteCore)
import EnteCore
#else
-struct SyncAuth {
- let baseUrl: String
- let authToken: String
- let masterKey: Data
- let userAgent: String
- let clientPackage: String
- let clientVersion: String?
-}
-
-enum SyncError: Error {
- case Message(String)
- case SyncInProgress
-}
-
-struct MigrationConfig {
- let batchSize: Int64
- let priority: MigrationPriority
-}
-
-enum MigrationPriority {
- case recentFirst
- case oldestFirst
-}
-
-enum MigrationState {
- case notNeeded
- case inProgress
- case complete
- case failed
-}
-
-struct MigrationProgress {
- let state: MigrationState
- let processed: Int64
- let remaining: Int64
- let total: Int64
-}
-
-protocol MigrationProgressCallback {
- func onProgress(progress: MigrationProgress)
-}
-
final class CredentialStore {
static let shared = CredentialStore()
var hasConfiguredAccount: Bool { false }
@@ -56,19 +14,6 @@ final class CredentialStore {
}
}
-struct EntePlatform {
- static let current = EntePlatform()
- var userAgent: String { "ensu" }
-}
-
-enum EnteApp {
- case ensu
-
- var packageIdentifier: String {
- "ensu"
- }
-}
-
enum EnsuLogLevel: String {
case info
case warning
@@ -100,20 +45,6 @@ final class EnsuLogging {
func createLogsArchive() throws -> URL { URL(fileURLWithPath: "") }
}
-struct NetworkConfiguration {
- let apiEndpoint: URL
-
- static var `default`: NetworkConfiguration {
- NetworkConfiguration(apiEndpoint: URL(string: "https://api.ente.com")!)
- }
-}
-
-enum EnsuDeveloperSettings {
- static var networkConfiguration: NetworkConfiguration {
- .default
- }
-}
-
struct InferenceModelTarget: Equatable {
let id: String
let url: String
@@ -305,91 +236,12 @@ final class EnsuDb {
_ = (uuid, title)
}
}
-
-final class EnsuSync {
- static func open(
- mainDbPath: String,
- attachmentsDbPath: String,
- dbKey: Data,
- attachmentsDir: String,
- metaDir: String,
- plaintextDir: String
- ) throws -> EnsuSync {
- _ = (mainDbPath, attachmentsDbPath, dbKey, attachmentsDir, metaDir, plaintextDir)
- return EnsuSync()
- }
-
- func sync(auth: SyncAuth) throws -> Bool {
- _ = auth
- return true
- }
-
- func checkMigrationStatusLocal() -> MigrationState? {
- nil
- }
-
- func checkMigrationStatus(auth: SyncAuth) throws -> MigrationState {
- _ = auth
- return .inProgress
- }
-
- func syncWithProgress(
- auth: SyncAuth,
- config: MigrationConfig,
- callback: MigrationProgressCallback
- ) throws -> Bool {
- _ = (auth, config, callback)
- return true
- }
-
- func resetSyncState() throws {
- }
-
- func seedFromOffline(offlineDbPath: String, offlineDbKey: Data) throws {
- _ = (offlineDbPath, offlineDbKey)
- }
-
- func downloadAttachment(attachmentId: String, sessionUuid: String, auth: SyncAuth) throws -> Bool {
- _ = (attachmentId, sessionUuid, auth)
- return true
- }
-}
-
-func fetchChatKey(auth: SyncAuth, syncDbPath: String) throws -> Data {
- _ = (auth, syncDbPath)
- return Data()
-}
#endif
#if canImport(EnteCore)
typealias LlmChatSession = Session
-enum SyncState: Equatable {
- case idle
- case syncing
- case migrating(processed: Int64, total: Int64)
- case error(String)
-}
-
-final class MigrationProgressHandler: MigrationProgressCallback {
- private let handler: @Sendable (MigrationProgress) -> Void
-
- init(_ handler: @escaping @Sendable (MigrationProgress) -> Void) {
- self.handler = handler
- }
-
- func onProgress(progress: MigrationProgress) {
- handler(progress)
- }
-}
-
-private struct OnlineStorePreparation {
- let chatKey: Data
- let chatDb: EnsuDb
- let syncEngine: EnsuSync
-}
-
@MainActor
final class ChatViewModel: ObservableObject {
private struct ModelReadyKey: Equatable {
@@ -462,9 +314,6 @@ final class ChatViewModel: ObservableObject {
@Published var showUnsupportedDeviceDialog: Bool = false
@Published var attachmentDownloads: [AttachmentDownloadItem] = []
@Published var currentSessionMissingAttachments: [AttachmentDownloadItem] = []
- @Published var syncState: SyncState = .idle
- @Published var syncErrorMessage: String?
- @Published var syncSuccessMessage: String?
@Published var generationErrorMessage: String?
@Published var voiceInputState: VoiceInputState = .initial
@Published var draftCursorMoveToken = UUID()
@@ -473,26 +322,12 @@ final class ChatViewModel: ObservableObject {
private let deviceCapabilityProvider = ProcessInfoChatDeviceCapabilityProvider()
private let voiceTranscriber: VoiceTranscriptionService
private var chatDb: EnsuDb
- private var syncEngine: EnsuSync
private let attachmentsDir: URL
- private let offlineDbPath: String
- private let onlineDbPath: String
- private let syncDbPath: String
- private let syncMetaDir: URL
- private let encryptedAttachmentsDir: URL
- private let offlineDbKey: Data
- private var onlineDbKey: Data?
- private var isOnlineMode = false
+ private let chatDbPath: String
+ private let attachmentsDbPath: String
+ private let chatDbKey: Data
private let modelSettings = ModelSettingsStore.shared
- private var activeDbPath: String {
- isOnlineMode ? onlineDbPath : offlineDbPath
- }
-
- private var activeDbKey: Data? {
- isOnlineMode ? onlineDbKey : offlineDbKey
- }
-
private var messageStore: [UUID: [MessageNode]] = [:]
private var branchSelections: [UUID: [String: UUID]] = [:]
private var childrenByParentCache: [UUID: [UUID: [MessageNode]]] = [:]
@@ -510,9 +345,6 @@ final class ChatViewModel: ObservableObject {
private var stopRequested = false
private var activeGenerationId: UUID?
private var activeGenerationSessionId: UUID?
- private var pendingSyncRequested = false
- private var pendingSyncShowErrors = false
- private var pendingSyncShowSuccess = false
private var modelDownloadLoggedStart = false
private let downloadProgressTracker = DownloadProgressTracker()
private var pendingOverflow: PendingOverflow?
@@ -541,37 +373,17 @@ final class ChatViewModel: ObservableObject {
let attachmentsDir = dbDir.appendingPathComponent("chat_attachments", isDirectory: true)
try? FileManager.default.createDirectory(at: attachmentsDir, withIntermediateDirectories: true, attributes: nil)
- let offlineKey = CredentialStore.shared.getOrCreateChatDbKey()
- let offlineDbPath = dbDir.appendingPathComponent("llmchat.db").path
- let onlineDbPath = dbDir.appendingPathComponent("llmchat_online.db").path
- let syncDbPath = dbDir.appendingPathComponent("llmchat_sync.db").path
+ let chatDbKey = CredentialStore.shared.getOrCreateChatDbKey()
+ let chatDbPath = dbDir.appendingPathComponent("llmchat.db").path
+ let attachmentsDbPath = dbDir.appendingPathComponent("llmchat_sync.db").path
let chatDb: EnsuDb
do {
- chatDb = try EnsuDb.open(mainDbPath: offlineDbPath, attachmentsDbPath: syncDbPath, key: offlineKey)
+ chatDb = try EnsuDb.open(mainDbPath: chatDbPath, attachmentsDbPath: attachmentsDbPath, key: chatDbKey)
} catch {
fatalError("Failed to open chat DB: \(error)")
}
- let syncMetaDir = dbDir.appendingPathComponent("sync_meta", isDirectory: true)
- try? FileManager.default.createDirectory(at: syncMetaDir, withIntermediateDirectories: true, attributes: nil)
- let encryptedAttachmentsDir = dbDir.appendingPathComponent("chat_attachments_encrypted", isDirectory: true)
- try? FileManager.default.createDirectory(at: encryptedAttachmentsDir, withIntermediateDirectories: true, attributes: nil)
-
- let syncEngine: EnsuSync
- do {
- syncEngine = try EnsuSync.open(
- mainDbPath: offlineDbPath,
- attachmentsDbPath: syncDbPath,
- dbKey: offlineKey,
- attachmentsDir: encryptedAttachmentsDir.path,
- metaDir: syncMetaDir.path,
- plaintextDir: attachmentsDir.path
- )
- } catch {
- fatalError("Failed to open chat sync: \(error)")
- }
-
// Load sessions/messages.
let loaded = (try? chatDb.listSessions()) ?? []
let sessions = Self.buildSessions(from: loaded, chatDb: chatDb, summaries: summaries)
@@ -580,14 +392,10 @@ final class ChatViewModel: ObservableObject {
self.provider = provider
self.voiceTranscriber = voiceTranscriber
self.chatDb = chatDb
- self.syncEngine = syncEngine
self.attachmentsDir = attachmentsDir
- self.offlineDbPath = offlineDbPath
- self.onlineDbPath = onlineDbPath
- self.syncDbPath = syncDbPath
- self.syncMetaDir = syncMetaDir
- self.encryptedAttachmentsDir = encryptedAttachmentsDir
- self.offlineDbKey = offlineKey
+ self.chatDbPath = chatDbPath
+ self.attachmentsDbPath = attachmentsDbPath
+ self.chatDbKey = chatDbKey
self.sessionSummaries = summaries
self.sessions = sessions
@@ -645,29 +453,14 @@ final class ChatViewModel: ObservableObject {
"This device doesn't have enough memory to run Ensu's AI model. " +
"You can view existing chats, but can't send new messages."
- private func reopenSyncStoresIfNeeded(force: Bool = false) {
- let hasSyncDb = FileManager.default.fileExists(atPath: syncDbPath)
- let hasActiveDb = FileManager.default.fileExists(atPath: activeDbPath)
- if !force && hasSyncDb && hasActiveDb {
- return
- }
-
- guard let key = activeDbKey else {
- logger.error("Missing active DB key")
+ private func reopenChatStoreIfNeeded(force: Bool = false) {
+ let hasAttachmentsDb = FileManager.default.fileExists(atPath: attachmentsDbPath)
+ let hasChatDb = FileManager.default.fileExists(atPath: chatDbPath)
+ if !force && hasAttachmentsDb && hasChatDb {
return
}
do {
- try? FileManager.default.createDirectory(
- at: syncMetaDir,
- withIntermediateDirectories: true,
- attributes: nil
- )
- try? FileManager.default.createDirectory(
- at: encryptedAttachmentsDir,
- withIntermediateDirectories: true,
- attributes: nil
- )
try? FileManager.default.createDirectory(
at: attachmentsDir,
withIntermediateDirectories: true,
@@ -675,96 +468,15 @@ final class ChatViewModel: ObservableObject {
)
chatDb = try EnsuDb.open(
- mainDbPath: activeDbPath,
- attachmentsDbPath: syncDbPath,
- key: key
- )
- syncEngine = try EnsuSync.open(
- mainDbPath: activeDbPath,
- attachmentsDbPath: syncDbPath,
- dbKey: key,
- attachmentsDir: encryptedAttachmentsDir.path,
- metaDir: syncMetaDir.path,
- plaintextDir: attachmentsDir.path
+ mainDbPath: chatDbPath,
+ attachmentsDbPath: attachmentsDbPath,
+ key: chatDbKey
)
} catch {
- logger.error("Failed to reopen sync stores: \(error)")
+ logger.error("Failed to reopen chat store: \(error)")
}
}
- private func prepareOnlineStores(auth: SyncAuth) async throws {
- let syncDbPath = syncDbPath
- let onlineDbPath = onlineDbPath
- let offlineDbPath = offlineDbPath
- let offlineDbKey = offlineDbKey
- let syncMetaDir = syncMetaDir
- let encryptedAttachmentsDir = encryptedAttachmentsDir
- let attachmentsDir = attachmentsDir
- let existingSyncEngine = syncEngine
-
- let preparation = try await Task.detached {
- if FileManager.default.fileExists(atPath: syncDbPath) {
- try? existingSyncEngine.resetSyncState()
- }
- try? FileManager.default.removeItem(atPath: onlineDbPath)
- ChatDataCleaner.deleteSyncState()
- try? FileManager.default.createDirectory(
- at: syncMetaDir,
- withIntermediateDirectories: true,
- attributes: nil
- )
- try? FileManager.default.createDirectory(
- at: encryptedAttachmentsDir,
- withIntermediateDirectories: true,
- attributes: nil
- )
- try? FileManager.default.createDirectory(
- at: attachmentsDir,
- withIntermediateDirectories: true,
- attributes: nil
- )
-
- let chatKey = try fetchChatKey(auth: auth, syncDbPath: syncDbPath)
-
- let chatDb = try EnsuDb.open(
- mainDbPath: onlineDbPath,
- attachmentsDbPath: syncDbPath,
- key: chatKey
- )
- let newSyncEngine = try EnsuSync.open(
- mainDbPath: onlineDbPath,
- attachmentsDbPath: syncDbPath,
- dbKey: chatKey,
- attachmentsDir: encryptedAttachmentsDir.path,
- metaDir: syncMetaDir.path,
- plaintextDir: attachmentsDir.path
- )
- try newSyncEngine.seedFromOffline(offlineDbPath: offlineDbPath, offlineDbKey: offlineDbKey)
- return OnlineStorePreparation(chatKey: chatKey, chatDb: chatDb, syncEngine: newSyncEngine)
- }.value
-
- onlineDbKey = preparation.chatKey
- isOnlineMode = true
- chatDb = preparation.chatDb
- syncEngine = preparation.syncEngine
- }
-
- func handleLogout() {
- if FileManager.default.fileExists(atPath: syncDbPath) {
- do {
- try syncEngine.resetSyncState()
- } catch {
- logger.warning("Failed to reset sync state: \(error)")
- }
- }
- ChatDataCleaner.deleteSyncState()
- try? FileManager.default.removeItem(atPath: onlineDbPath)
- onlineDbKey = nil
- isOnlineMode = false
- reopenSyncStoresIfNeeded(force: true)
- reloadFromDb()
- }
-
var currentSession: ChatSession? {
guard let currentSessionId else { return nil }
return sessions.first { $0.id == currentSessionId }
@@ -863,7 +575,6 @@ final class ChatViewModel: ObservableObject {
}
logger.info("Session deleted", details: "id=\(session.id.uuidString)")
try? chatDb.deleteSession(uuid: session.id.uuidString)
- deleteOfflineSessionIfNeeded(session.id)
sessionSummaries.removeValue(forKey: sessionSummaryKey(session.id))
persistSessionSummaries()
@@ -882,159 +593,6 @@ final class ChatViewModel: ObservableObject {
refreshAttachmentDownloadState()
}
}
- syncNow()
- }
-
- private func deleteOfflineSessionIfNeeded(_ sessionId: UUID) {
- guard isOnlineMode else { return }
- do {
- let offlineDb = try EnsuDb.open(
- mainDbPath: offlineDbPath,
- attachmentsDbPath: syncDbPath,
- key: offlineDbKey
- )
- try offlineDb.deleteSession(uuid: sessionId.uuidString)
- } catch {
- logger.warning("Failed to delete offline session", details: "id=\(sessionId.uuidString) error=\(error)")
- }
- }
-
- func syncNow(showErrors: Bool = true, showSuccess: Bool = false) {
- if isGenerating {
- pendingSyncRequested = true
- pendingSyncShowErrors = pendingSyncShowErrors || showErrors
- pendingSyncShowSuccess = pendingSyncShowSuccess || showSuccess
- return
- }
-
- let shouldSync = pendingSyncRequested || showErrors || showSuccess
- let shouldShowErrors = pendingSyncShowErrors || showErrors
- let shouldShowSuccess = pendingSyncShowSuccess || showSuccess
- pendingSyncRequested = false
- pendingSyncShowErrors = false
- pendingSyncShowSuccess = false
- guard shouldSync else { return }
- performSync(showErrors: shouldShowErrors, showSuccess: shouldShowSuccess)
- }
-
- func syncAfterLogin() {
- guard let auth = buildSyncAuth() else {
- syncState = .error("Sign in to sync")
- return
- }
-
- Task.detached { [weak self] in
- guard let self else { return }
- do {
- try await self.prepareOnlineStores(auth: auth)
- } catch {
- await MainActor.run {
- self.syncState = .error("Failed to prepare online chats")
- }
- return
- }
-
- await MainActor.run {
- self.reloadFromDb()
- }
-
- let syncEngine = await self.syncEngine
- if let localStatus = syncEngine.checkMigrationStatusLocal() {
- await self.handleMigrationStatus(localStatus, auth: auth)
- return
- }
-
- do {
- let status = try syncEngine.checkMigrationStatus(auth: auth)
- await self.handleMigrationStatus(status, auth: auth)
- } catch {
- await MainActor.run {
- self.syncState = .error("Offline")
- }
- }
- }
- }
-
- private func handleMigrationStatus(_ status: MigrationState, auth: SyncAuth) async {
- switch status {
- case .inProgress:
- await performBatchedSync(auth: auth)
- case .notNeeded, .complete:
- performSyncWithAuth(auth: auth, showErrors: false, showSuccess: false)
- case .failed:
- await MainActor.run {
- self.syncState = .error("Migration failed")
- }
- }
- }
-
- private func performSync(showErrors: Bool, showSuccess: Bool) {
- reopenSyncStoresIfNeeded()
- guard let auth = buildSyncAuth() else {
- if showErrors {
- syncErrorMessage = "Sync failed: Sign in to sync"
- }
- return
- }
- performSyncWithAuth(auth: auth, showErrors: showErrors, showSuccess: showSuccess)
- }
-
- private func performSyncWithAuth(auth: SyncAuth, showErrors: Bool, showSuccess: Bool) {
- let log = logger
- syncState = .syncing
- log.info("Sync started")
-
- let syncEngine = self.syncEngine
- Task.detached { [weak self, log] in
- guard let self else { return }
- do {
- _ = try syncEngine.sync(auth: auth)
- log.info("Sync success")
- await MainActor.run {
- self.syncState = .idle
- self.reloadFromDb()
- if showSuccess {
- self.syncSuccessMessage = "Sync complete"
- }
- }
- } catch {
- let message = syncErrorMessage(from: error)
- let needsReset = ChatRecovery.shouldResetFromMessage(message)
- let userMessage = needsReset
- ? "\(message). Reset chat data to recover."
- : message
- log.error("Sync failed", error, details: message)
- await MainActor.run {
- self.syncState = .error(userMessage)
- if showErrors {
- self.syncErrorMessage = self.formatSyncErrorMessage(userMessage)
- }
- }
- }
- }
- }
-
- private func performBatchedSync(auth: SyncAuth) async {
- let config = MigrationConfig(batchSize: 25, priority: .recentFirst)
- syncState = .migrating(processed: 0, total: 0)
-
- let syncEngine = syncEngine
- do {
- let handler = MigrationProgressHandler { [weak self] progress in
- Task { @MainActor in
- self?.syncState = .migrating(processed: progress.processed, total: progress.total)
- }
- }
- try await Task.detached {
- _ = try syncEngine.syncWithProgress(auth: auth, config: config, callback: handler)
- }.value
- syncState = .idle
- reloadFromDb()
- } catch {
- let message = syncErrorMessage(from: error)
- syncState = .error(message)
- syncErrorMessage = formatSyncErrorMessage(message)
- }
}
func deleteAllData() async {
@@ -1047,7 +605,6 @@ final class ChatViewModel: ObservableObject {
childrenByParentCache.removeAll()
attachmentDownloads = []
currentSessionMissingAttachments = []
- syncState = .idle
refreshAttachmentDownloadState()
}
@@ -1342,7 +899,6 @@ final class ChatViewModel: ObservableObject {
updateSessionPreview(sessionId: sessionId, preview: trimmed, date: timestamp)
rebuildMessages(for: sessionId)
startGeneration(for: userNode)
- syncNow(showErrors: false)
}
func stopGenerating() {
@@ -1621,7 +1177,6 @@ final class ChatViewModel: ObservableObject {
}
self.provider.resetContext()
self.startGeneration(for: userNode)
- self.syncNow(showErrors: false)
}
}
@@ -1699,7 +1254,6 @@ final class ChatViewModel: ObservableObject {
activeGenerationId = nil
activeGenerationSessionId = nil
}
- syncNow(showErrors: false)
return
}
if self.activeGenerationId == generationId {
@@ -1716,7 +1270,6 @@ final class ChatViewModel: ObservableObject {
activeGenerationId = nil
activeGenerationSessionId = nil
}
- syncNow(showErrors: false)
return
}
@@ -1745,7 +1298,6 @@ final class ChatViewModel: ObservableObject {
maxOutput: generationLimits.maxOutput
)
rebuildMessages(for: userNode.sessionId)
- syncNow(showErrors: false)
return
}
@@ -1919,7 +1471,6 @@ final class ChatViewModel: ObservableObject {
if currentSessionId == parent.sessionId {
rebuildMessages(for: parent.sessionId)
}
- syncNow(showErrors: false)
scheduleSessionSummary(for: parent.sessionId)
}
@@ -2030,49 +1581,6 @@ final class ChatViewModel: ObservableObject {
return (progress, isDownloaded)
}
- private func buildSyncAuth() -> SyncAuth? {
- guard CredentialStore.shared.hasConfiguredAccount,
- let token = CredentialStore.shared.token,
- let masterKey = CredentialStore.shared.masterKey else {
- return nil
- }
-
- let baseUrl = EnsuDeveloperSettings.networkConfiguration.apiEndpoint.absoluteString
- let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
- return SyncAuth(
- baseUrl: baseUrl,
- authToken: token,
- masterKey: masterKey,
- userAgent: EntePlatform.current.userAgent,
- clientPackage: EnteApp.ensu.packageIdentifier,
- clientVersion: version
- )
- }
-
- private nonisolated func syncErrorMessage(from error: Error) -> String {
- if let syncError = error as? SyncError {
- switch syncError {
- case let .Message(message):
- return message
- case .SyncInProgress:
- return "Sync already in progress"
- }
- }
- let description = error.localizedDescription
- if description.isEmpty {
- return String(describing: error)
- }
- return description
- }
-
- private func formatSyncErrorMessage(_ message: String) -> String {
- let normalized = message.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
- if normalized.contains("sync already in progress") {
- return message
- }
- return "Sync failed: \(message)"
- }
-
private func queueMissingAttachments(for sessionId: UUID, missing: [AttachmentDownloadItem]? = nil) {
Task { @MainActor in
let resolvedMissing: [AttachmentDownloadItem]
@@ -2160,11 +1668,8 @@ final class ChatViewModel: ObservableObject {
}
private func startNextAttachmentDownloads() {
- reopenSyncStoresIfNeeded()
guard attachmentDownloadTasks.count < maxAttachmentDownloads else { return }
- guard let auth = buildSyncAuth() else { return }
- let syncEngine = self.syncEngine
while attachmentDownloadTasks.count < maxAttachmentDownloads, !attachmentDownloadQueue.isEmpty {
let id = attachmentDownloadQueue.removeFirst()
guard let index = attachmentDownloads.firstIndex(where: { $0.id == id }) else { continue }
@@ -2172,29 +1677,10 @@ final class ChatViewModel: ObservableObject {
attachmentDownloads[index].status == AttachmentDownloadItem.Status.completed {
continue
}
- let sessionId = attachmentDownloads[index].sessionId
- attachmentDownloads[index].status = AttachmentDownloadItem.Status.downloading
-
- let task = Task.detached { [weak self] in
- guard let self else { return }
- do {
- _ = try syncEngine.downloadAttachment(
- attachmentId: id,
- sessionUuid: sessionId.uuidString,
- auth: auth
- )
- await MainActor.run {
- self.updateAttachmentDownloadStatus(id: id, status: AttachmentDownloadItem.Status.completed, errorMessage: nil)
- }
- } catch {
- let message = self.syncErrorMessage(from: error)
- await MainActor.run {
- self.updateAttachmentDownloadStatus(id: id, status: AttachmentDownloadItem.Status.failed, errorMessage: message)
- }
- }
- }
- attachmentDownloadTasks[id] = task
+ attachmentDownloads[index].status = AttachmentDownloadItem.Status.failed
+ attachmentDownloads[index].errorMessage = "Attachment is not available on this device."
}
+ refreshAttachmentDownloadState()
}
private func updateAttachmentDownloadStatus(
@@ -2284,7 +1770,7 @@ final class ChatViewModel: ObservableObject {
private func reloadFromDb() {
reloadTask?.cancel()
- reopenSyncStoresIfNeeded()
+ reopenChatStoreIfNeeded()
let chatDb = chatDb
let summaries = sessionSummaries
let selected = currentSessionId
@@ -2341,7 +1827,7 @@ final class ChatViewModel: ObservableObject {
}
private func loadMessagesFromDb(for sessionId: UUID) {
- reopenSyncStoresIfNeeded()
+ reopenChatStoreIfNeeded()
if messageStore[sessionId] == nil {
messageStore[sessionId] = []
branchSelections[sessionId] = [:]
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/SessionDrawerView.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/SessionDrawerView.swift
index 278707d98b..b215d47907 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/SessionDrawerView.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/SessionDrawerView.swift
@@ -8,7 +8,6 @@ struct SessionDrawerView: View {
let email: String?
let onSelectSession: (ChatSession) -> Void
let onDeleteSession: (ChatSession) -> Void
- let onSync: () -> Void
let onOpenSettings: () -> Void
@State private var searchQuery: String = ""
@@ -47,20 +46,6 @@ struct SessionDrawerView: View {
private var drawerHeader: some View {
VStack(alignment: .leading, spacing: 0) {
- if isLoggedIn {
- HStack {
- Spacer()
-
- drawerPrimaryTile(
- icon: "ArrowReloadHorizontalIcon",
- title: "Sync",
- action: onSync,
- expands: false
- )
- }
- .padding(.bottom, EnsuSpacing.sm)
- }
-
headerControls
}
.padding(.horizontal, EnsuSpacing.lg)
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/HomeView.swift b/mobile/native/darwin/Apps/Ensu/Ensu/HomeView.swift
index 5d415fac89..bb941d71fb 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/HomeView.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/HomeView.swift
@@ -5,26 +5,15 @@ struct HomeView: View {
@EnvironmentObject private var appState: EnsuAppState
@StateObject private var chatModel = ChatViewModel()
@State private var isShowingAuth = false
- @State private var didTriggerInitialSync = false
var body: some View {
ChatView(viewModel: chatModel, isShowingAuth: $isShowingAuth)
.platformFullScreenCover(isPresented: $isShowingAuth) {
AuthFlowView()
}
- .task {
- guard appState.isLoggedIn, !didTriggerInitialSync else { return }
- didTriggerInitialSync = true
- chatModel.syncAfterLogin()
- }
.onChange(of: appState.isLoggedIn) { isLoggedIn in
if isLoggedIn {
isShowingAuth = false
- didTriggerInitialSync = true
- chatModel.syncAfterLogin()
- } else {
- didTriggerInitialSync = false
- chatModel.handleLogout()
}
}
}
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuAppState.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuAppState.swift
index 8a0b1250c1..57e5d76598 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuAppState.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuAppState.swift
@@ -14,7 +14,6 @@ final class EnsuAppState: ObservableObject {
func logout() {
CredentialStore.shared.clear()
- ChatDataCleaner.deleteSyncState()
refreshLoginState()
}
}
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuAuthService.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuAuthService.swift
index 70c9ea5d64..c94aca5d2e 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuAuthService.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuAuthService.swift
@@ -253,7 +253,6 @@ final class EnsuAuthService {
if !CredentialStore.shared.isSameUser(userId) {
CredentialStore.shared.clear()
- ChatDataCleaner.deleteSyncState()
}
try CredentialStore.shared.save(
diff --git a/mobile/native/darwin/Apps/Ensu/scripts/build-rust.sh b/mobile/native/darwin/Apps/Ensu/scripts/build-rust.sh
index a0508c8cdf..f05d1e5651 100755
--- a/mobile/native/darwin/Apps/Ensu/scripts/build-rust.sh
+++ b/mobile/native/darwin/Apps/Ensu/scripts/build-rust.sh
@@ -20,7 +20,7 @@ for tool in cargo rustup cmake; do
command -v "$tool" >/dev/null || { echo "error: $tool not on PATH" >&2; exit 1; }
done
-for name in core db sync inference transcription; do
+for name in core db inference transcription; do
for ext in .swift FFI.h FFI.modulemap; do
[[ -f "$GENERATED_DIR/$name$ext" ]] || {
echo "error: missing $GENERATED_DIR/$name$ext" >&2
@@ -122,6 +122,5 @@ build_crate() {
build_crate core "$REPO_ROOT/rust/bindings/uniffi/core" libcore.a
build_crate db "$REPO_ROOT/rust/bindings/uniffi/ensu/db" libdb.a
-build_crate sync "$REPO_ROOT/rust/bindings/uniffi/ensu/sync" libsync.a
build_crate inference "$REPO_ROOT/rust/bindings/uniffi/ensu/inference" libinference.a
build_crate transcription "$REPO_ROOT/rust/bindings/uniffi/ensu/transcription" libtranscription.a
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 5cc68b3b9e..53a7f593ca 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -278,15 +278,6 @@ dependencies = [
"stable_deref_trait",
]
-[[package]]
-name = "ascii-canvas"
-version = "3.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8824ecca2e851cec16968d54a01dd372ef8f95b244fb84b84e70128be347c3c6"
-dependencies = [
- "term",
-]
-
[[package]]
name = "askama"
version = "0.14.0"
@@ -345,39 +336,18 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9"
-[[package]]
-name = "async-attributes"
-version = "1.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a3203e79f4dd9bdda415ed03cf14dae5a2bf775c683a00f94e9cd1faf0f596e5"
-dependencies = [
- "quote",
- "syn 1.0.109",
-]
-
[[package]]
name = "async-broadcast"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"
dependencies = [
- "event-listener 5.4.1",
+ "event-listener",
"event-listener-strategy",
"futures-core",
"pin-project-lite",
]
-[[package]]
-name = "async-channel"
-version = "1.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35"
-dependencies = [
- "concurrent-queue",
- "event-listener 2.5.3",
- "futures-core",
-]
-
[[package]]
name = "async-channel"
version = "2.5.0"
@@ -404,21 +374,6 @@ dependencies = [
"slab",
]
-[[package]]
-name = "async-global-executor"
-version = "2.4.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c"
-dependencies = [
- "async-channel 2.5.0",
- "async-executor",
- "async-io",
- "async-lock",
- "blocking",
- "futures-lite",
- "once_cell",
-]
-
[[package]]
name = "async-io"
version = "2.6.0"
@@ -443,34 +398,25 @@ version = "3.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"
dependencies = [
- "event-listener 5.4.1",
+ "event-listener",
"event-listener-strategy",
"pin-project-lite",
]
-[[package]]
-name = "async-object-pool"
-version = "0.1.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "333c456b97c3f2d50604e8b2624253b7f787208cb72eb75e64b0ad11b221652c"
-dependencies = [
- "async-std",
-]
-
[[package]]
name = "async-process"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"
dependencies = [
- "async-channel 2.5.0",
+ "async-channel",
"async-io",
"async-lock",
"async-signal",
"async-task",
"blocking",
"cfg-if",
- "event-listener 5.4.1",
+ "event-listener",
"futures-lite",
"rustix",
]
@@ -504,34 +450,6 @@ dependencies = [
"windows-sys 0.61.2",
]
-[[package]]
-name = "async-std"
-version = "1.13.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2c8e079a4ab67ae52b7403632e4618815d6db36d2a010cfe41b02c1b1578f93b"
-dependencies = [
- "async-attributes",
- "async-channel 1.9.0",
- "async-global-executor",
- "async-io",
- "async-lock",
- "async-process",
- "crossbeam-utils",
- "futures-channel",
- "futures-core",
- "futures-io",
- "futures-lite",
- "gloo-timers",
- "kv-log-macro",
- "log",
- "memchr",
- "once_cell",
- "pin-project-lite",
- "pin-utils",
- "slab",
- "wasm-bindgen-futures",
-]
-
[[package]]
name = "async-task"
version = "4.7.1"
@@ -736,17 +654,6 @@ version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
-[[package]]
-name = "basic-cookies"
-version = "0.1.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "67bd8fd42c16bdb08688243dc5f0cc117a3ca9efeeaba3a345a18a6159ad96f7"
-dependencies = [
- "lalrpop",
- "lalrpop-util",
- "regex",
-]
-
[[package]]
name = "basic-toml"
version = "0.1.10"
@@ -787,30 +694,15 @@ dependencies = [
"unicode-normalization",
]
-[[package]]
-name = "bit-set"
-version = "0.5.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1"
-dependencies = [
- "bit-vec 0.6.3",
-]
-
[[package]]
name = "bit-set"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
dependencies = [
- "bit-vec 0.8.0",
+ "bit-vec",
]
-[[package]]
-name = "bit-vec"
-version = "0.6.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb"
-
[[package]]
name = "bit-vec"
version = "0.8.0"
@@ -918,7 +810,7 @@ version = "1.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21"
dependencies = [
- "async-channel 2.5.0",
+ "async-channel",
"async-task",
"futures-io",
"futures-lite",
@@ -2119,16 +2011,6 @@ dependencies = [
"dirs-sys 0.5.0",
]
-[[package]]
-name = "dirs-next"
-version = "2.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b98cf8ebf19c3d1b223e151f99a4f9f0690dca41414773390fc824184ac833e1"
-dependencies = [
- "cfg-if",
- "dirs-sys-next",
-]
-
[[package]]
name = "dirs-sys"
version = "0.4.1"
@@ -2153,17 +2035,6 @@ dependencies = [
"windows-sys 0.61.2",
]
-[[package]]
-name = "dirs-sys-next"
-version = "0.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d"
-dependencies = [
- "libc",
- "redox_users 0.4.6",
- "winapi",
-]
-
[[package]]
name = "dispatch2"
version = "0.3.1"
@@ -2225,7 +2096,7 @@ version = "0.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521e380c0c8afb8d9a1e83a1822ee03556fc3e3e7dbc1fd30be14e37f9cb3f89"
dependencies = [
- "bit-set 0.8.0",
+ "bit-set",
"cssparser",
"foldhash 0.2.0",
"html5ever",
@@ -2320,15 +2191,6 @@ version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"
-[[package]]
-name = "ena"
-version = "0.14.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3d248bdd43ce613d87415282f69b9bb99d947d290b10962dd6c56233312c2ad5"
-dependencies = [
- "log",
-]
-
[[package]]
name = "encode_unicode"
version = "1.0.0"
@@ -2433,7 +2295,6 @@ name = "ensu-desktop"
version = "0.1.18-beta"
dependencies = [
"ensu-db",
- "ensu-sync",
"ente-core",
"inference_rs",
"keyring",
@@ -2451,24 +2312,6 @@ dependencies = [
"windows-sys 0.61.2",
]
-[[package]]
-name = "ensu-sync"
-version = "0.0.0"
-dependencies = [
- "ensu-db",
- "ente-core",
- "hkdf 0.13.0",
- "httpmock",
- "reqwest 0.12.28",
- "serde",
- "serde_json",
- "sha2 0.11.0",
- "tempfile",
- "thiserror 2.0.18",
- "uuid",
- "zeroize",
-]
-
[[package]]
name = "ensu-transcription"
version = "0.0.0"
@@ -2843,12 +2686,6 @@ dependencies = [
"windows-sys 0.61.2",
]
-[[package]]
-name = "event-listener"
-version = "2.5.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"
-
[[package]]
name = "event-listener"
version = "5.4.1"
@@ -2866,7 +2703,7 @@ version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
dependencies = [
- "event-listener 5.4.1",
+ "event-listener",
"pin-project-lite",
]
@@ -2903,7 +2740,7 @@ version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e24cb5a94bcae1e5408b0effca5cd7172ea3c5755049c5f3af4cd283a165298"
dependencies = [
- "bit-set 0.8.0",
+ "bit-set",
"regex-automata 0.4.14",
"regex-syntax",
]
@@ -3008,12 +2845,6 @@ dependencies = [
"writeable 0.5.5",
]
-[[package]]
-name = "fixedbitset"
-version = "0.4.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
-
[[package]]
name = "flate2"
version = "1.1.9"
@@ -3573,18 +3404,6 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
-[[package]]
-name = "gloo-timers"
-version = "0.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994"
-dependencies = [
- "futures-channel",
- "futures-core",
- "js-sys",
- "wasm-bindgen",
-]
-
[[package]]
name = "gobject-sys"
version = "0.18.0"
@@ -3670,7 +3489,7 @@ dependencies = [
"fnv",
"futures-core",
"futures-sink",
- "http 1.4.0",
+ "http",
"indexmap 2.14.0",
"slab",
"tokio",
@@ -3852,17 +3671,6 @@ dependencies = [
"markup5ever",
]
-[[package]]
-name = "http"
-version = "0.2.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1"
-dependencies = [
- "bytes",
- "fnv",
- "itoa",
-]
-
[[package]]
name = "http"
version = "1.4.0"
@@ -3873,17 +3681,6 @@ dependencies = [
"itoa",
]
-[[package]]
-name = "http-body"
-version = "0.4.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2"
-dependencies = [
- "bytes",
- "http 0.2.12",
- "pin-project-lite",
-]
-
[[package]]
name = "http-body"
version = "1.0.1"
@@ -3891,7 +3688,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"
dependencies = [
"bytes",
- "http 1.4.0",
+ "http",
]
[[package]]
@@ -3902,8 +3699,8 @@ checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"
dependencies = [
"bytes",
"futures-core",
- "http 1.4.0",
- "http-body 1.0.1",
+ "http",
+ "http-body",
"pin-project-lite",
]
@@ -3919,34 +3716,6 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
-[[package]]
-name = "httpmock"
-version = "0.7.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "08ec9586ee0910472dec1a1f0f8acf52f0fdde93aea74d70d4a3107b4be0fd5b"
-dependencies = [
- "assert-json-diff",
- "async-object-pool",
- "async-std",
- "async-trait",
- "base64 0.21.7",
- "basic-cookies",
- "crossbeam-utils",
- "form_urlencoded",
- "futures-util",
- "hyper 0.14.32",
- "lazy_static",
- "levenshtein",
- "log",
- "regex",
- "serde",
- "serde_json",
- "serde_regex",
- "similar",
- "tokio",
- "url",
-]
-
[[package]]
name = "humantime"
version = "2.3.0"
@@ -3962,29 +3731,6 @@ dependencies = [
"typenum",
]
-[[package]]
-name = "hyper"
-version = "0.14.32"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "41dfc780fdec9373c01bae43289ea34c972e40ee3c9f6b3c8801a35f35586ce7"
-dependencies = [
- "bytes",
- "futures-channel",
- "futures-core",
- "futures-util",
- "http 0.2.12",
- "http-body 0.4.6",
- "httparse",
- "httpdate",
- "itoa",
- "pin-project-lite",
- "socket2 0.5.10",
- "tokio",
- "tower-service",
- "tracing",
- "want",
-]
-
[[package]]
name = "hyper"
version = "1.9.0"
@@ -3996,8 +3742,8 @@ dependencies = [
"futures-channel",
"futures-core",
"h2",
- "http 1.4.0",
- "http-body 1.0.1",
+ "http",
+ "http-body",
"httparse",
"httpdate",
"itoa",
@@ -4013,8 +3759,8 @@ version = "0.27.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f"
dependencies = [
- "http 1.4.0",
- "hyper 1.9.0",
+ "http",
+ "hyper",
"hyper-util",
"rustls",
"rustls-native-certs",
@@ -4032,7 +3778,7 @@ checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0"
dependencies = [
"bytes",
"http-body-util",
- "hyper 1.9.0",
+ "hyper",
"hyper-util",
"native-tls",
"tokio",
@@ -4050,14 +3796,14 @@ dependencies = [
"bytes",
"futures-channel",
"futures-util",
- "http 1.4.0",
- "http-body 1.0.1",
- "hyper 1.9.0",
+ "http",
+ "http-body",
+ "hyper",
"ipnet",
"libc",
"percent-encoding",
"pin-project-lite",
- "socket2 0.6.3",
+ "socket2",
"system-configuration",
"tokio",
"tower-service",
@@ -4855,15 +4601,6 @@ dependencies = [
"either",
]
-[[package]]
-name = "itertools"
-version = "0.11.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57"
-dependencies = [
- "either",
-]
-
[[package]]
name = "itertools"
version = "0.12.1"
@@ -5118,46 +4855,6 @@ dependencies = [
"libc",
]
-[[package]]
-name = "kv-log-macro"
-version = "1.0.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0de8b303297635ad57c9f5059fd9cee7a47f8e8daa09df0fcd07dd39fb22977f"
-dependencies = [
- "log",
-]
-
-[[package]]
-name = "lalrpop"
-version = "0.20.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "55cb077ad656299f160924eb2912aa147d7339ea7d69e1b5517326fdcec3c1ca"
-dependencies = [
- "ascii-canvas",
- "bit-set 0.5.3",
- "ena",
- "itertools 0.11.0",
- "lalrpop-util",
- "petgraph",
- "pico-args",
- "regex",
- "regex-syntax",
- "string_cache 0.8.9",
- "term",
- "tiny-keccak",
- "unicode-xid",
- "walkdir",
-]
-
-[[package]]
-name = "lalrpop-util"
-version = "0.20.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "507460a910eb7b32ee961886ff48539633b788a36b65692b95f225b844c82553"
-dependencies = [
- "regex-automata 0.4.14",
-]
-
[[package]]
name = "lazy_static"
version = "1.5.0"
@@ -5176,12 +4873,6 @@ version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"
-[[package]]
-name = "levenshtein"
-version = "1.0.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "db13adb97ab515a3691f56e4dbab09283d0b86cb45abd991d8634a9d6f501760"
-
[[package]]
name = "libappindicator"
version = "0.9.0"
@@ -5375,9 +5066,6 @@ name = "log"
version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
-dependencies = [
- "value-bag",
-]
[[package]]
name = "loop9"
@@ -5554,10 +5242,10 @@ dependencies = [
"bytes",
"colored 3.1.1",
"futures-core",
- "http 1.4.0",
- "http-body 1.0.1",
+ "http",
+ "http-body",
"http-body-util",
- "hyper 1.9.0",
+ "hyper",
"hyper-util",
"log",
"pin-project-lite",
@@ -6447,16 +6135,6 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
-[[package]]
-name = "petgraph"
-version = "0.6.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db"
-dependencies = [
- "fixedbitset",
- "indexmap 2.14.0",
-]
-
[[package]]
name = "phf"
version = "0.11.3"
@@ -6528,12 +6206,6 @@ dependencies = [
"siphasher",
]
-[[package]]
-name = "pico-args"
-version = "0.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"
-
[[package]]
name = "pin-project-lite"
version = "0.2.17"
@@ -6905,7 +6577,7 @@ dependencies = [
"quinn-udp",
"rustc-hash",
"rustls",
- "socket2 0.6.3",
+ "socket2",
"thiserror 2.0.18",
"tokio",
"tracing",
@@ -6943,7 +6615,7 @@ dependencies = [
"cfg_aliases",
"libc",
"once_cell",
- "socket2 0.6.3",
+ "socket2",
"tracing",
"windows-sys 0.60.2",
]
@@ -7294,10 +6966,10 @@ dependencies = [
"futures-core",
"futures-util",
"h2",
- "http 1.4.0",
- "http-body 1.0.1",
+ "http",
+ "http-body",
"http-body-util",
- "hyper 1.9.0",
+ "hyper",
"hyper-rustls",
"hyper-tls",
"hyper-util",
@@ -7341,10 +7013,10 @@ dependencies = [
"futures-core",
"futures-util",
"h2",
- "http 1.4.0",
- "http-body 1.0.1",
+ "http",
+ "http-body",
"http-body-util",
- "hyper 1.9.0",
+ "hyper",
"hyper-rustls",
"hyper-util",
"js-sys",
@@ -7380,7 +7052,7 @@ checksum = "07bc3f1384cffa4f274dad2d4ddd73aed32fed8f786d96c6be8aa4e5fd3c3b58"
dependencies = [
"anyhow",
"async-trait",
- "http 1.4.0",
+ "http",
"reqwest 0.13.4",
"serde",
"thiserror 2.0.18",
@@ -7397,8 +7069,8 @@ dependencies = [
"async-trait",
"futures",
"getrandom 0.2.17",
- "http 1.4.0",
- "hyper 1.9.0",
+ "http",
+ "hyper",
"reqwest 0.13.4",
"reqwest-middleware",
"retry-policies",
@@ -7417,7 +7089,7 @@ dependencies = [
"anyhow",
"async-trait",
"getrandom 0.2.17",
- "http 1.4.0",
+ "http",
"matchit",
"reqwest 0.13.4",
"reqwest-middleware",
@@ -7986,16 +7658,6 @@ dependencies = [
"zmij",
]
-[[package]]
-name = "serde_regex"
-version = "1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a8136f1a4ea815d7eac4101cfd0b16dc0cb5e1fe1b8609dfd728058656b7badf"
-dependencies = [
- "regex",
- "serde",
-]
-
[[package]]
name = "serde_repr"
version = "0.1.20"
@@ -8304,16 +7966,6 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7c388c1b5e93756d0c740965c41e8822f866621d41acbdf6336a6a168f8840c"
-[[package]]
-name = "socket2"
-version = "0.5.10"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678"
-dependencies = [
- "libc",
- "windows-sys 0.52.0",
-]
-
[[package]]
name = "socket2"
version = "0.6.3"
@@ -8418,7 +8070,7 @@ dependencies = [
"crc",
"crossbeam-queue",
"either",
- "event-listener 5.4.1",
+ "event-listener",
"futures-core",
"futures-intrusive",
"futures-io",
@@ -8542,18 +8194,6 @@ version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82"
-[[package]]
-name = "string_cache"
-version = "0.8.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f"
-dependencies = [
- "new_debug_unreachable",
- "parking_lot",
- "phf_shared 0.11.3",
- "precomputed-hash",
-]
-
[[package]]
name = "string_cache"
version = "0.9.0"
@@ -8674,15 +8314,6 @@ dependencies = [
"unicode-ident",
]
-[[package]]
-name = "sync"
-version = "0.0.0"
-dependencies = [
- "ensu-sync",
- "thiserror 2.0.18",
- "uniffi",
-]
-
[[package]]
name = "sync_wrapper"
version = "1.0.2"
@@ -8827,7 +8458,7 @@ dependencies = [
"glob",
"gtk",
"heck 0.5.0",
- "http 1.4.0",
+ "http",
"jni 0.21.1",
"libc",
"log",
@@ -9024,7 +8655,7 @@ dependencies = [
"dirs 6.0.0",
"flate2",
"futures-util",
- "http 1.4.0",
+ "http",
"infer",
"log",
"minisign-verify",
@@ -9056,7 +8687,7 @@ dependencies = [
"cookie",
"dpi",
"gtk",
- "http 1.4.0",
+ "http",
"jni 0.21.1",
"objc2",
"objc2-ui-kit",
@@ -9079,7 +8710,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b83849ee63ecb27a8e8d0fe51915ca215076914aca43f96db1179f0f415f6cd9"
dependencies = [
"gtk",
- "http 1.4.0",
+ "http",
"jni 0.21.1",
"log",
"objc2",
@@ -9111,7 +8742,7 @@ dependencies = [
"dom_query",
"dunce",
"glob",
- "http 1.4.0",
+ "http",
"infer",
"json-patch",
"log",
@@ -9170,17 +8801,6 @@ dependencies = [
"utf-8",
]
-[[package]]
-name = "term"
-version = "0.7.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c59df8ac95d96ff9bede18eb7300b0fda5e5d8d90960e76f8e14ae765eedbf1f"
-dependencies = [
- "dirs-next",
- "rustversion",
- "winapi",
-]
-
[[package]]
name = "termcolor"
version = "1.4.1"
@@ -9307,15 +8927,6 @@ dependencies = [
"time-core",
]
-[[package]]
-name = "tiny-keccak"
-version = "2.0.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"
-dependencies = [
- "crunchy",
-]
-
[[package]]
name = "tinystr"
version = "0.7.6"
@@ -9369,7 +8980,7 @@ dependencies = [
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
- "socket2 0.6.3",
+ "socket2",
"tokio-macros",
"windows-sys 0.61.2",
]
@@ -9606,8 +9217,8 @@ dependencies = [
"bitflags 2.11.0",
"bytes",
"futures-util",
- "http 1.4.0",
- "http-body 1.0.1",
+ "http",
+ "http-body",
"pin-project-lite",
"tower",
"tower-layer",
@@ -10027,7 +9638,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e994ba84b0bd1b1b0cf92878b7ef898a5c1760108fe7b6010327e274917a808c"
dependencies = [
"base64 0.22.1",
- "http 1.4.0",
+ "http",
"httparse",
"log",
]
@@ -10148,12 +9759,6 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
-[[package]]
-name = "value-bag"
-version = "1.12.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7ba6f5989077681266825251a52748b8c1d8a4ad098cc37e440103d0ea717fc0"
-
[[package]]
name = "vcpkg"
version = "0.2.15"
@@ -10392,7 +9997,7 @@ checksum = "d7cff6eef815df1834fd250e3a2ff436044d82a9f1bc1980ca1dbdf07effc538"
dependencies = [
"phf 0.13.1",
"phf_codegen",
- "string_cache 0.9.0",
+ "string_cache",
"string_cache_codegen",
]
@@ -11198,7 +10803,7 @@ dependencies = [
"dunce",
"gdkx11",
"gtk",
- "http 1.4.0",
+ "http",
"javascriptcore-rs",
"jni 0.21.1",
"libc",
@@ -11365,7 +10970,7 @@ dependencies = [
"async-recursion",
"async-trait",
"enumflags2",
- "event-listener 5.4.1",
+ "event-listener",
"futures-core",
"futures-sink",
"futures-util",
@@ -11402,7 +11007,7 @@ dependencies = [
"async-trait",
"blocking",
"enumflags2",
- "event-listener 5.4.1",
+ "event-listener",
"futures-core",
"futures-lite",
"hex",
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 41f170a6fb..c7f532f903 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -10,7 +10,6 @@ members = [
"bindings/uniffi/core",
"bindings/uniffi/ensu/db",
"bindings/uniffi/ensu/inference",
- "bindings/uniffi/ensu/sync",
"bindings/uniffi/ensu/transcription",
"bindings/wasm/ente-wasm",
"bindings/wasm/core",
@@ -19,7 +18,6 @@ members = [
"crates/core",
"crates/ensu/db",
"crates/ensu/inference",
- "crates/ensu/sync",
"crates/ensu/transcription",
"crates/image",
"crates/photos",
@@ -29,7 +27,6 @@ members = [
[workspace.dependencies]
ensu-db = { path = "crates/ensu/db" }
-ensu-sync = { path = "crates/ensu/sync" }
ensu-transcription = { path = "crates/ensu/transcription" }
ente-accounts = { path = "crates/accounts" }
ente-contacts = { path = "crates/contacts" }
diff --git a/rust/apps/codegen/src/main.rs b/rust/apps/codegen/src/main.rs
index 14efec3d79..9233ea3aed 100644
--- a/rust/apps/codegen/src/main.rs
+++ b/rust/apps/codegen/src/main.rs
@@ -85,10 +85,6 @@ fn generate_native_ios() -> Result<(), DynError> {
crate_name: "db",
crate_dir: rust_root.join("bindings/uniffi/ensu/db"),
},
- UniffiCrate {
- crate_name: "sync",
- crate_dir: rust_root.join("bindings/uniffi/ensu/sync"),
- },
UniffiCrate {
crate_name: "inference",
crate_dir: rust_root.join("bindings/uniffi/ensu/inference"),
@@ -109,7 +105,6 @@ fn generate_native_ios() -> Result<(), DynError> {
}
sanitize_generated_swift_bindings(&generated_dir.join("db.swift"), "db")?;
- sanitize_generated_swift_bindings(&generated_dir.join("sync.swift"), "sync")?;
Ok(())
}
@@ -143,14 +138,6 @@ fn generate_native_android() -> Result<(), DynError> {
out_dir: rust_out_dir.clone(),
stale_path: rust_out_dir.join("io/ente/labs/ensu_db/db.kt"),
},
- AndroidCrate {
- uniffi: UniffiCrate {
- crate_name: "sync",
- crate_dir: rust_root.join("bindings/uniffi/ensu/sync"),
- },
- out_dir: rust_out_dir.clone(),
- stale_path: rust_out_dir.join("io/ente/labs/ensu_sync/sync.kt"),
- },
AndroidCrate {
uniffi: UniffiCrate {
crate_name: "inference",
diff --git a/rust/apps/ensu/src-tauri/Cargo.toml b/rust/apps/ensu/src-tauri/Cargo.toml
index 1638a0a9de..9a52424362 100644
--- a/rust/apps/ensu/src-tauri/Cargo.toml
+++ b/rust/apps/ensu/src-tauri/Cargo.toml
@@ -16,7 +16,6 @@ tauri-plugin-updater = "2.10.1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
ensu-db.workspace = true
-ensu-sync.workspace = true
ente-core = { workspace = true, features = ["srp"] }
inference_rs.workspace = true
uuid = { version = "1", features = ["v4"] }
diff --git a/rust/apps/ensu/src-tauri/src/commands.rs b/rust/apps/ensu/src-tauri/src/commands.rs
index 92d404d4bb..0fb3b59b51 100644
--- a/rust/apps/ensu/src-tauri/src/commands.rs
+++ b/rust/apps/ensu/src-tauri/src/commands.rs
@@ -8,8 +8,7 @@ use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use ensu_db::backend::sqlite::SqliteBackend;
-use ensu_db::{EnsuDb, Error as DbError, SyncStateDb};
-use ensu_sync as chat_sync;
+use ensu_db::{EnsuDb, Error as DbError};
use ente_core::{auth as core_auth, crypto as core_crypto};
use inference_rs as llm;
use serde::{Deserialize, Serialize};
@@ -55,13 +54,10 @@ struct ChatDbHolder {
const SECURE_STORAGE_SERVICE: &str = "io.ente.ensu";
const CHAT_DB_FILE_NAME_V2: &str = "ensu_llmchat_v2.db";
const LEGACY_CHAT_DB_FILE_NAME: &str = "ensu_llmchat.db";
-const SYNC_DB_FILE_NAME_V2: &str = "llmchat_sync_v2.db";
-const LEGACY_SYNC_DB_FILE_NAME: &str = "llmchat_sync.db";
+const ATTACHMENTS_DB_FILE_NAME_V2: &str = "llmchat_sync_v2.db";
+const LEGACY_ATTACHMENTS_DB_FILE_NAME: &str = "llmchat_sync.db";
const ATTACHMENTS_DIR_NAME_V2: &str = "ensu_llmchat_attachments_v2";
const LEGACY_ATTACHMENTS_DIR_NAME: &str = "ensu_llmchat_attachments";
-const SYNC_CURSOR_META_KEY: &str = "llmchat.sync.cursor";
-const SYNC_CHAT_KEY_META_KEY: &str = "llmchat.chat.key";
-const SYNC_OFFLINE_SEED_META_KEY: &str = "llmchat.offline.seeded.v1";
const LLM_PANIC_JOB_ID: i64 = 0;
#[derive(Debug, Serialize)]
@@ -341,18 +337,6 @@ impl From<DbError> for ApiError {
}
}
-fn map_sync_error(err: chat_sync::SyncError) -> ApiError {
- match err {
- chat_sync::SyncError::LimitReached { code, message } => {
- let message = message.unwrap_or_else(|| "Sync limit reached".to_string());
- ApiError::new(&code, message)
- }
- chat_sync::SyncError::Unauthorized => ApiError::new("unauthorized", err.to_string()),
- chat_sync::SyncError::NotLoggedIn => ApiError::new("not_logged_in", err.to_string()),
- other => ApiError::new("sync", other.to_string()),
- }
-}
-
#[derive(Serialize)]
pub struct SrpCredentials {
kek: String,
@@ -733,18 +717,6 @@ pub struct ChatAttachmentInput {
uploaded_at: Option<i64>,
}
-#[derive(Deserialize, Clone)]
-#[serde(rename_all = "camelCase")]
-pub struct ChatSyncInput {
- key_b64: String,
- base_url: String,
- auth_token: String,
- master_key_b64: String,
- user_agent: Option<String>,
- client_package: Option<String>,
- client_version: Option<String>,
-}
-
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatDbMigrateLegacyInput {
@@ -752,42 +724,6 @@ pub struct ChatDbMigrateLegacyInput {
legacy_key_b64: String,
}
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ChatSyncStatsDto {
- sessions: i64,
- messages: i64,
-}
-
-impl From<chat_sync::SyncStats> for ChatSyncStatsDto {
- fn from(stats: chat_sync::SyncStats) -> Self {
- Self {
- sessions: stats.sessions,
- messages: stats.messages,
- }
- }
-}
-
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ChatSyncResultDto {
- pulled: ChatSyncStatsDto,
- pushed: ChatSyncStatsDto,
- uploaded_attachments: i64,
- downloaded_attachments: i64,
-}
-
-impl From<chat_sync::SyncResult> for ChatSyncResultDto {
- fn from(result: chat_sync::SyncResult) -> Self {
- Self {
- pulled: result.pulled.into(),
- pushed: result.pushed.into(),
- uploaded_attachments: result.uploaded_attachments,
- downloaded_attachments: result.downloaded_attachments,
- }
- }
-}
-
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatDbMigrateLegacyResult {
@@ -939,13 +875,6 @@ pub struct ChatMessageUpsertInput {
attachments: Option<Vec<ChatAttachmentInput>>,
}
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ChatDeletionDto {
- entity_type: String,
- uuid: String,
-}
-
#[tauri::command]
pub async fn chat_db_list_sessions(
state: State<'_, ChatDbState>,
@@ -1072,29 +1001,6 @@ pub async fn chat_db_get_messages(
.await
}
-#[tauri::command]
-pub async fn chat_db_get_messages_for_sync(
- state: State<'_, ChatDbState>,
- app: AppHandle,
- key_b64: String,
- session_uuid: String,
- include_deleted: bool,
-) -> Result<Vec<ChatMessageDto>, ApiError> {
- let uuid = parse_uuid(&session_uuid)?;
- with_chat_db_async(&state, app, key_b64, move |db| {
- let messages = if include_deleted {
- db.get_messages_for_sync(uuid, true)?
- } else {
- db.get_messages_needing_sync(uuid)?
- };
- messages
- .into_iter()
- .map(|message| build_message_dto(db, message))
- .collect()
- })
- .await
-}
-
#[tauri::command]
pub async fn chat_db_insert_message(
state: State<'_, ChatDbState>,
@@ -1142,22 +1048,6 @@ pub async fn chat_db_update_message_text(
.await
}
-#[tauri::command]
-pub async fn chat_db_list_sessions_for_sync(
- state: State<'_, ChatDbState>,
- app: AppHandle,
- key_b64: String,
-) -> Result<Vec<ChatSessionDto>, ApiError> {
- with_chat_db_async(&state, app, key_b64, |db| {
- Ok(db
- .get_sessions_needing_sync()?
- .into_iter()
- .map(ChatSessionDto::from)
- .collect())
- })
- .await
-}
-
#[tauri::command]
pub async fn chat_db_upsert_session(
state: State<'_, ChatDbState>,
@@ -1241,109 +1131,6 @@ pub async fn chat_db_insert_message_with_uuid(
.await
}
-#[tauri::command]
-pub async fn chat_db_mark_session_synced(
- state: State<'_, ChatDbState>,
- app: AppHandle,
- key_b64: String,
- session_uuid: String,
- remote_id: String,
-) -> Result<(), ApiError> {
- let uuid = parse_uuid(&session_uuid)?;
- with_chat_db_async(&state, app, key_b64, move |db| {
- db.mark_session_synced(uuid, &remote_id)?;
- Ok(())
- })
- .await
-}
-
-#[tauri::command]
-pub async fn chat_db_mark_session_deleted(
- state: State<'_, ChatDbState>,
- app: AppHandle,
- key_b64: String,
- session_uuid: String,
- deleted_at: i64,
-) -> Result<(), ApiError> {
- let uuid = parse_uuid(&session_uuid)?;
- with_chat_db_async(&state, app, key_b64, move |db| {
- db.apply_session_tombstone(uuid, deleted_at)?;
- Ok(())
- })
- .await
-}
-
-#[tauri::command]
-pub async fn chat_db_mark_message_deleted(
- state: State<'_, ChatDbState>,
- app: AppHandle,
- key_b64: String,
- message_uuid: String,
- deleted_at: i64,
-) -> Result<(), ApiError> {
- let uuid = parse_uuid(&message_uuid)?;
- with_chat_db_async(&state, app, key_b64, move |db| {
- db.apply_message_tombstone(uuid, deleted_at)?;
- Ok(())
- })
- .await
-}
-
-#[tauri::command]
-pub async fn chat_db_mark_attachment_uploaded(
- state: State<'_, ChatDbState>,
- app: AppHandle,
- key_b64: String,
- message_uuid: String,
- attachment_id: String,
-) -> Result<(), ApiError> {
- let _ = parse_uuid(&message_uuid)?;
- with_chat_db_async(&state, app, key_b64, move |db| {
- db.mark_attachment_uploaded(&attachment_id)?;
- Ok(())
- })
- .await
-}
-
-#[tauri::command]
-pub async fn chat_db_get_pending_deletions(
- state: State<'_, ChatDbState>,
- app: AppHandle,
- key_b64: String,
-) -> Result<Vec<ChatDeletionDto>, ApiError> {
- with_chat_db_async(&state, app, key_b64, move |db| {
- let deletions = db.get_pending_deletions()?;
- Ok(deletions
- .into_iter()
- .map(|(entity, uuid)| ChatDeletionDto {
- entity_type: match entity {
- ensu_db::EntityType::Session => "session".to_string(),
- ensu_db::EntityType::Message => "message".to_string(),
- },
- uuid: uuid.to_string(),
- })
- .collect())
- })
- .await
-}
-
-#[tauri::command]
-pub async fn chat_db_hard_delete(
- state: State<'_, ChatDbState>,
- app: AppHandle,
- key_b64: String,
- entity_type: String,
- uuid: String,
-) -> Result<(), ApiError> {
- let entity_type = parse_entity_type(&entity_type)?;
- let uuid = parse_uuid(&uuid)?;
- with_chat_db_async(&state, app, key_b64, move |db| {
- db.hard_delete(entity_type, uuid)?;
- Ok(())
- })
- .await
-}
-
#[tauri::command]
pub async fn chat_db_reset(state: State<'_, ChatDbState>, app: AppHandle) -> Result<(), ApiError> {
let inner = state.inner.clone();
@@ -1358,17 +1145,19 @@ pub async fn chat_db_reset(state: State<'_, ChatDbState>, app: AppHandle) -> Res
let path = chat_db_path(&app)?;
let wal_path = PathBuf::from(format!("{}-wal", path.display()));
let shm_path = PathBuf::from(format!("{}-shm", path.display()));
- let sync_path = sync_db_path(&app)?;
- let sync_wal_path = PathBuf::from(format!("{}-wal", sync_path.display()));
- let sync_shm_path = PathBuf::from(format!("{}-shm", sync_path.display()));
+ let attachments_db_path = attachments_db_path(&app)?;
+ let attachments_db_wal_path =
+ PathBuf::from(format!("{}-wal", attachments_db_path.display()));
+ let attachments_db_shm_path =
+ PathBuf::from(format!("{}-shm", attachments_db_path.display()));
for candidate in [
path,
wal_path,
shm_path,
- sync_path,
- sync_wal_path,
- sync_shm_path,
+ attachments_db_path,
+ attachments_db_wal_path,
+ attachments_db_shm_path,
] {
if candidate.exists() {
fs::remove_file(&candidate).map_err(|err| ApiError::new("io", err.to_string()))?;
@@ -1391,98 +1180,6 @@ pub async fn chat_db_migrate_legacy(
.map_err(|_| chat_db_thread_error())?
}
-#[tauri::command]
-pub async fn chat_sync(
- app: AppHandle,
- input: ChatSyncInput,
-) -> Result<ChatSyncResultDto, ApiError> {
- async_runtime::spawn_blocking(move || {
- match catch_unwind(AssertUnwindSafe(|| {
- logging::log(
- "Sync",
- format!(
- "chat_sync start base_url={} has_user_agent={} has_client_package={} has_client_version={}",
- input.base_url,
- input.user_agent.is_some(),
- input.client_package.is_some(),
- input.client_version.is_some()
- ),
- );
- let key = core_crypto::decode_b64(&input.key_b64).map_err(ApiError::from)?;
- let master_key =
- core_crypto::decode_b64(&input.master_key_b64).map_err(ApiError::from)?;
-
- let db_path = chat_db_path(&app)?;
- let sync_path = sync_db_path(&app)?;
- let attachments_dir = attachments_dir_path(&app)?;
- let meta_dir = sync_meta_dir_path(&app)?;
-
- logging::log(
- "Sync",
- format!(
- "chat_sync paths db={} sync={} attachments_dir={} meta_dir={}",
- db_path.display(),
- sync_path.display(),
- attachments_dir.display(),
- meta_dir.display()
- ),
- );
-
- let engine = chat_sync::SyncEngine::new(
- db_path.to_string_lossy().to_string(),
- sync_path.to_string_lossy().to_string(),
- key,
- attachments_dir.to_string_lossy().to_string(),
- meta_dir.to_string_lossy().to_string(),
- None,
- )
- .map_err(|err| {
- logging::log("Sync", format!("failed to create sync engine error={err}"));
- ApiError::new("sync", err.to_string())
- })?;
-
- let auth = chat_sync::SyncAuth {
- base_url: input.base_url,
- auth_token: input.auth_token,
- master_key: master_key.into(),
- user_agent: input.user_agent,
- client_package: input.client_package,
- client_version: input.client_version,
- };
-
- let result = engine.sync(auth).map_err(|err| {
- logging::log("Sync", format!("sync failed error={err}"));
- map_sync_error(err)
- })?;
- logging::log(
- "Sync",
- format!(
- "chat_sync success pulled_sessions={} pulled_messages={} pushed_sessions={} pushed_messages={} uploaded_attachments={} downloaded_attachments={}",
- result.pulled.sessions,
- result.pulled.messages,
- result.pushed.sessions,
- result.pushed.messages,
- result.uploaded_attachments,
- result.downloaded_attachments
- ),
- );
- Ok(ChatSyncResultDto::from(result))
- })) {
- Ok(result) => result,
- Err(payload) => {
- let message = panic_message(payload);
- log_command_panic("chat_sync", &message);
- Err(ApiError::new("sync_panic", format!("chat_sync panicked: {message}")))
- }
- }
- })
- .await
- .map_err(|err| {
- logging::log("Sync", format!("sync task join failed error={err}"));
- ApiError::new("sync", "Sync task failed")
- })?
-}
-
#[derive(Serialize, Clone)]
#[serde(tag = "type", rename_all = "snake_case")]
enum LlmEvent {
@@ -2021,17 +1718,6 @@ fn normalize_sender(sender: &str) -> Result<&'static str, ApiError> {
}
}
-fn parse_entity_type(value: &str) -> Result<ensu_db::EntityType, ApiError> {
- match value {
- "session" => Ok(ensu_db::EntityType::Session),
- "message" => Ok(ensu_db::EntityType::Message),
- other => Err(ApiError::new(
- "db_invalid_entity_type",
- format!("Unsupported entity type: {other}"),
- )),
- }
-}
-
fn parse_uuid(value: &str) -> Result<Uuid, ApiError> {
Uuid::parse_str(value).map_err(|err| ApiError::new("uuid", err.to_string()))
}
@@ -2137,8 +1823,8 @@ fn chat_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {
Ok(app_data_dir(app)?.join(CHAT_DB_FILE_NAME_V2))
}
-fn sync_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {
- Ok(app_data_dir(app)?.join(SYNC_DB_FILE_NAME_V2))
+fn attachments_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {
+ Ok(app_data_dir(app)?.join(ATTACHMENTS_DB_FILE_NAME_V2))
}
fn attachments_dir_path(app: &AppHandle) -> Result<PathBuf, ApiError> {
@@ -2149,19 +1835,12 @@ fn attachments_dir_path(app: &AppHandle) -> Result<PathBuf, ApiError> {
Ok(attachments_dir)
}
-fn sync_meta_dir_path(app: &AppHandle) -> Result<PathBuf, ApiError> {
- let dir = app_data_dir(app)?;
- let meta_dir = dir.join("sync_meta");
- std::fs::create_dir_all(&meta_dir).map_err(|err| ApiError::new("io", err.to_string()))?;
- Ok(meta_dir)
-}
-
fn legacy_chat_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {
Ok(app_data_dir(app)?.join(LEGACY_CHAT_DB_FILE_NAME))
}
-fn legacy_sync_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {
- Ok(app_data_dir(app)?.join(LEGACY_SYNC_DB_FILE_NAME))
+fn legacy_attachments_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {
+ Ok(app_data_dir(app)?.join(LEGACY_ATTACHMENTS_DB_FILE_NAME))
}
fn legacy_attachments_dir_path(app: &AppHandle) -> Result<PathBuf, ApiError> {
@@ -2170,16 +1849,16 @@ fn legacy_attachments_dir_path(app: &AppHandle) -> Result<PathBuf, ApiError> {
fn cleanup_legacy_chat_artifacts(app: &AppHandle) -> Result<(), ApiError> {
let legacy_db_path = legacy_chat_db_path(app)?;
- let legacy_sync_path = legacy_sync_db_path(app)?;
+ let legacy_attachments_db_path = legacy_attachments_db_path(app)?;
let legacy_attachments_dir = legacy_attachments_dir_path(app)?;
for candidate in [
legacy_db_path.clone(),
PathBuf::from(format!("{}-wal", legacy_db_path.display())),
PathBuf::from(format!("{}-shm", legacy_db_path.display())),
- legacy_sync_path.clone(),
- PathBuf::from(format!("{}-wal", legacy_sync_path.display())),
- PathBuf::from(format!("{}-shm", legacy_sync_path.display())),
+ legacy_attachments_db_path.clone(),
+ PathBuf::from(format!("{}-wal", legacy_attachments_db_path.display())),
+ PathBuf::from(format!("{}-shm", legacy_attachments_db_path.display())),
] {
if candidate.exists() {
fs::remove_file(&candidate).map_err(|err| ApiError::new("io", err.to_string()))?;
@@ -2198,8 +1877,6 @@ fn verify_migrated_chat_db(
target_db: &EnsuDb<SqliteBackend>,
source_session_ids: &[Uuid],
source_message_ids_by_session: &HashMap<Uuid, Vec<Uuid>>,
- migrated_meta_keys: &[&str],
- target_sync_state: &SyncStateDb<SqliteBackend>,
target_attachments_dir: &Path,
expected_attachment_ids: &[String],
) -> Result<(), ApiError> {
@@ -2237,19 +1914,6 @@ fn verify_migrated_chat_db(
}
}
- for meta_key in migrated_meta_keys {
- if target_sync_state
- .get_meta(meta_key)
- .map_err(ApiError::from)?
- .is_none()
- {
- return Err(ApiError::new(
- "db_migration_verification",
- format!("Missing migrated sync meta key {meta_key}"),
- ));
- }
- }
-
for attachment_id in expected_attachment_ids {
let target_path = target_attachments_dir.join(attachment_id);
if !target_path.exists() {
@@ -2277,50 +1941,30 @@ fn migrate_legacy_chat_db(
});
}
- let legacy_sync_path = legacy_sync_db_path(app)?;
+ let legacy_attachments_db_path = legacy_attachments_db_path(app)?;
let legacy_attachments_dir = legacy_attachments_dir_path(app)?;
let target_db_path = chat_db_path(app)?;
- let target_sync_path = sync_db_path(app)?;
+ let target_attachments_db_path = attachments_db_path(app)?;
let target_attachments_dir = attachments_dir_path(app)?;
let legacy_key = core_crypto::decode_b64(&input.legacy_key_b64).map_err(ApiError::from)?;
let key = core_crypto::decode_b64(&input.key_b64).map_err(ApiError::from)?;
let legacy_db =
- EnsuDb::open_sqlite_with_defaults(&legacy_db_path, &legacy_sync_path, legacy_key)
+ EnsuDb::open_sqlite_with_defaults(&legacy_db_path, &legacy_attachments_db_path, legacy_key)
+ .map_err(ApiError::from)?;
+ let target_db =
+ EnsuDb::open_sqlite_with_defaults(&target_db_path, &target_attachments_db_path, key)
.map_err(ApiError::from)?;
- let target_db = EnsuDb::open_sqlite_with_defaults(&target_db_path, &target_sync_path, key)
- .map_err(ApiError::from)?;
- let legacy_sync_state =
- SyncStateDb::open_sqlite_with_defaults(&legacy_sync_path).map_err(ApiError::from)?;
- let target_sync_state =
- SyncStateDb::open_sqlite_with_defaults(&target_sync_path).map_err(ApiError::from)?;
let mut migrated_sessions = 0_i64;
let mut migrated_messages = 0_i64;
let mut migrated_attachments = 0_i64;
- let mut migrated_meta_keys = Vec::new();
let mut source_session_ids = Vec::new();
let mut source_message_ids_by_session = HashMap::new();
let mut expected_attachment_ids = Vec::new();
let legacy_sessions = legacy_db.list_all_sessions().map_err(ApiError::from)?;
- for meta_key in [
- SYNC_CURSOR_META_KEY,
- SYNC_CHAT_KEY_META_KEY,
- SYNC_OFFLINE_SEED_META_KEY,
- ] {
- if let Some(value) = legacy_sync_state
- .get_meta(meta_key)
- .map_err(ApiError::from)?
- {
- target_sync_state
- .set_meta(meta_key, &value)
- .map_err(ApiError::from)?;
- migrated_meta_keys.push(meta_key);
- }
- }
-
for session in legacy_sessions {
source_session_ids.push(session.uuid);
target_db
@@ -2334,18 +1978,6 @@ fn migrate_legacy_chat_db(
session.deleted_at,
)
.map_err(ApiError::from)?;
- if let Some(state) = legacy_sync_state
- .get_session_state(session.uuid)
- .map_err(ApiError::from)?
- {
- target_sync_state
- .set_session_state(
- session.uuid,
- state.remote_id.as_deref(),
- state.server_updated_at,
- )
- .map_err(ApiError::from)?;
- }
migrated_sessions += 1;
for message in legacy_db
@@ -2400,19 +2032,6 @@ fn migrate_legacy_chat_db(
.set_message_remote_id(message.uuid, remote_id)
.map_err(ApiError::from)?;
}
- if let Some(state) = legacy_sync_state
- .get_message_state(message.uuid)
- .map_err(ApiError::from)?
- {
- target_sync_state
- .set_message_state(
- message.uuid,
- state.remote_id.as_deref(),
- state.server_updated_at,
- )
- .map_err(ApiError::from)?;
- }
-
for attachment in attachments {
if let Some(remote_id) = legacy_db
.get_attachment_remote_id(&attachment.id)
@@ -2452,13 +2071,10 @@ fn migrate_legacy_chat_db(
&target_db,
&source_session_ids,
&source_message_ids_by_session,
- &migrated_meta_keys,
- &target_sync_state,
&target_attachments_dir,
&expected_attachment_ids,
)?;
- drop(legacy_sync_state);
drop(legacy_db);
cleanup_legacy_chat_artifacts(app)?;
@@ -2493,19 +2109,21 @@ where
if needs_open {
let key = core_crypto::decode_b64(key_b64).map_err(ApiError::from)?;
let path = chat_db_path(app)?;
- let sync_path = sync_db_path(app)?;
+ let attachments_db_path = attachments_db_path(app)?;
logging::log(
"ChatDb",
format!(
- "opening chat DB db={} sync={}",
+ "opening chat DB db={} attachments={}",
path.display(),
- sync_path.display()
+ attachments_db_path.display()
),
);
- let db = EnsuDb::open_sqlite_with_defaults(path, sync_path, key).map_err(|err| {
- logging::log("ChatDb", format!("failed to open chat DB error={err}"));
- ApiError::from(err)
- })?;
+ let db = EnsuDb::open_sqlite_with_defaults(path, attachments_db_path, key).map_err(
+ |err| {
+ logging::log("ChatDb", format!("failed to open chat DB error={err}"));
+ ApiError::from(err)
+ },
+ )?;
*guard = Some(ChatDbHolder {
key_b64: key_b64.to_string(),
db: Arc::new(db),
diff --git a/rust/apps/ensu/src-tauri/src/main.rs b/rust/apps/ensu/src-tauri/src/main.rs
index 090d09dfeb..1806a8409d 100644
--- a/rust/apps/ensu/src-tauri/src/main.rs
+++ b/rust/apps/ensu/src-tauri/src/main.rs
@@ -58,23 +58,14 @@ fn main() {
commands::chat_db_update_session_title,
commands::chat_db_delete_session,
commands::chat_db_get_messages,
- commands::chat_db_get_messages_for_sync,
commands::chat_db_insert_message,
commands::chat_db_update_message_text,
- commands::chat_db_list_sessions_for_sync,
commands::chat_db_upsert_session,
commands::chat_db_insert_message_with_uuid,
- commands::chat_db_mark_session_synced,
- commands::chat_db_mark_session_deleted,
- commands::chat_db_mark_message_deleted,
- commands::chat_db_mark_attachment_uploaded,
commands::chat_db_compress_attachment_image,
commands::chat_db_compress_attachment_image_file,
- commands::chat_db_get_pending_deletions,
- commands::chat_db_hard_delete,
commands::chat_db_reset,
commands::chat_db_migrate_legacy,
- commands::chat_sync,
commands::llm_init_backend,
commands::llm_load_model,
commands::llm_create_context,
diff --git a/rust/bindings/uniffi/ensu/sync/Cargo.toml b/rust/bindings/uniffi/ensu/sync/Cargo.toml
deleted file mode 100644
index a640568dcf..0000000000
--- a/rust/bindings/uniffi/ensu/sync/Cargo.toml
+++ /dev/null
@@ -1,13 +0,0 @@
-[package]
-name = "sync"
-edition = "2024"
-
-[lib]
-crate-type = ["staticlib", "cdylib"]
-
-[dependencies]
-ensu-sync.workspace = true
-thiserror = "2"
-uniffi = { version = "0.31.0" }
-
-[build-dependencies]
diff --git a/rust/bindings/uniffi/ensu/sync/build.rs b/rust/bindings/uniffi/ensu/sync/build.rs
deleted file mode 100644
index f328e4d9d0..0000000000
--- a/rust/bindings/uniffi/ensu/sync/build.rs
+++ /dev/null
@@ -1 +0,0 @@
-fn main() {}
diff --git a/rust/bindings/uniffi/ensu/sync/src/api.rs b/rust/bindings/uniffi/ensu/sync/src/api.rs
deleted file mode 100644
index 6a9c64775b..0000000000
--- a/rust/bindings/uniffi/ensu/sync/src/api.rs
+++ /dev/null
@@ -1,259 +0,0 @@
-use ensu_sync as core;
-use thiserror::Error;
-
-#[derive(Debug, Error, uniffi::Error)]
-pub enum SyncError {
- #[error("{0}")]
- Message(String),
- #[error("sync already in progress")]
- SyncInProgress,
-}
-
-impl From<core::SyncError> for SyncError {
- fn from(err: core::SyncError) -> Self {
- match err {
- core::SyncError::SyncInProgress => SyncError::SyncInProgress,
- other => SyncError::Message(other.to_string()),
- }
- }
-}
-
-#[derive(Debug, Clone, uniffi::Record)]
-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>,
-}
-
-impl From<SyncAuth> for core::SyncAuth {
- fn from(value: SyncAuth) -> Self {
- core::SyncAuth {
- base_url: value.base_url,
- auth_token: value.auth_token,
- master_key: value.master_key.into(),
- user_agent: value.user_agent,
- client_package: value.client_package,
- client_version: value.client_version,
- }
- }
-}
-
-#[derive(Debug, Clone, uniffi::Record)]
-pub struct MigrationConfig {
- pub batch_size: i64,
- pub priority: MigrationPriority,
-}
-
-#[derive(Debug, Clone, uniffi::Enum)]
-pub enum MigrationPriority {
- RecentFirst,
- OldestFirst,
-}
-
-impl From<MigrationPriority> for core::MigrationPriority {
- fn from(value: MigrationPriority) -> Self {
- match value {
- MigrationPriority::RecentFirst => core::MigrationPriority::RecentFirst,
- MigrationPriority::OldestFirst => core::MigrationPriority::OldestFirst,
- }
- }
-}
-
-impl From<core::MigrationPriority> for MigrationPriority {
- fn from(value: core::MigrationPriority) -> Self {
- match value {
- core::MigrationPriority::RecentFirst => MigrationPriority::RecentFirst,
- core::MigrationPriority::OldestFirst => MigrationPriority::OldestFirst,
- }
- }
-}
-
-impl From<MigrationConfig> for core::MigrationConfig {
- fn from(value: MigrationConfig) -> Self {
- core::MigrationConfig {
- batch_size: value.batch_size,
- priority: value.priority.into(),
- }
- }
-}
-
-#[derive(Debug, Clone, uniffi::Enum)]
-pub enum MigrationState {
- NotNeeded,
- InProgress,
- Complete,
- Failed,
-}
-
-impl From<core::MigrationState> for MigrationState {
- fn from(value: core::MigrationState) -> Self {
- match value {
- core::MigrationState::NotNeeded => MigrationState::NotNeeded,
- core::MigrationState::InProgress => MigrationState::InProgress,
- core::MigrationState::Complete => MigrationState::Complete,
- core::MigrationState::Failed => MigrationState::Failed,
- }
- }
-}
-
-#[derive(Debug, Clone, uniffi::Record)]
-pub struct MigrationProgress {
- pub state: MigrationState,
- pub processed: i64,
- pub remaining: i64,
- pub total: i64,
-}
-
-impl From<core::MigrationProgress> for MigrationProgress {
- fn from(value: core::MigrationProgress) -> Self {
- MigrationProgress {
- state: value.state.into(),
- processed: value.processed,
- remaining: value.remaining,
- total: value.total,
- }
- }
-}
-
-#[uniffi::export(callback_interface)]
-pub trait MigrationProgressCallback: Send + Sync {
- fn on_progress(&self, progress: MigrationProgress);
-}
-
-struct MigrationCallbackAdapter {
- inner: Box<dyn MigrationProgressCallback>,
-}
-
-impl core::MigrationProgressCallback for MigrationCallbackAdapter {
- fn on_progress(&self, progress: core::MigrationProgress) {
- self.inner.on_progress(progress.into());
- }
-}
-
-#[derive(Debug, Clone, uniffi::Record)]
-pub struct SyncStats {
- pub sessions: i64,
- pub messages: i64,
-}
-
-impl From<core::SyncStats> for SyncStats {
- fn from(value: core::SyncStats) -> Self {
- SyncStats {
- sessions: value.sessions,
- messages: value.messages,
- }
- }
-}
-
-#[derive(Debug, Clone, uniffi::Record)]
-pub struct SyncResult {
- pub pulled: SyncStats,
- pub pushed: SyncStats,
- pub uploaded_attachments: i64,
- pub downloaded_attachments: i64,
-}
-
-impl From<core::SyncResult> for SyncResult {
- fn from(value: core::SyncResult) -> Self {
- SyncResult {
- pulled: value.pulled.into(),
- pushed: value.pushed.into(),
- uploaded_attachments: value.uploaded_attachments,
- downloaded_attachments: value.downloaded_attachments,
- }
- }
-}
-
-#[uniffi::export]
-pub fn fetch_chat_key(auth: SyncAuth, sync_db_path: String) -> Result<Vec<u8>, SyncError> {
- let key = core::fetch_chat_key(auth.into(), sync_db_path)?;
- Ok(key)
-}
-
-#[derive(uniffi::Object)]
-pub struct EnsuSync {
- inner: core::SyncEngine,
-}
-
-#[uniffi::export]
-impl EnsuSync {
- #[uniffi::constructor]
- pub fn open(
- 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> {
- let inner = core::SyncEngine::new(
- main_db_path,
- attachments_db_path,
- db_key,
- attachments_dir,
- meta_dir,
- plaintext_dir,
- )?;
- Ok(Self { inner })
- }
-
- pub fn sync(&self, auth: SyncAuth) -> Result<SyncResult, SyncError> {
- let result = self.inner.sync(auth.into())?;
- Ok(result.into())
- }
-
- pub fn check_migration_status_local(&self) -> Option<MigrationState> {
- self.inner
- .check_migration_status_local()
- .ok()
- .flatten()
- .map(Into::into)
- }
-
- pub fn check_migration_status(&self, auth: SyncAuth) -> Result<MigrationState, SyncError> {
- let state = self.inner.check_migration_status(auth.into())?;
- Ok(state.into())
- }
-
- pub fn reset_sync_state(&self) -> Result<(), SyncError> {
- self.inner.reset_sync_state()?;
- Ok(())
- }
-
- pub fn seed_from_offline(
- &self,
- offline_db_path: String,
- offline_db_key: Vec<u8>,
- ) -> Result<(), SyncError> {
- self.inner
- .seed_from_offline(offline_db_path, offline_db_key)?;
- Ok(())
- }
-
- pub fn sync_with_progress(
- &self,
- auth: SyncAuth,
- config: MigrationConfig,
- callback: Box<dyn MigrationProgressCallback>,
- ) -> Result<SyncResult, SyncError> {
- let adapter = MigrationCallbackAdapter { inner: callback };
- let result = self
- .inner
- .sync_with_progress(auth.into(), config.into(), &adapter)?;
- Ok(result.into())
- }
-
- pub fn download_attachment(
- &self,
- attachment_id: String,
- session_uuid: String,
- auth: SyncAuth,
- ) -> Result<bool, SyncError> {
- self.inner
- .download_attachment(auth.into(), attachment_id, session_uuid)
- .map_err(Into::into)
- }
-}
diff --git a/rust/bindings/uniffi/ensu/sync/src/api.udl b/rust/bindings/uniffi/ensu/sync/src/api.udl
deleted file mode 100644
index bf7f2b4068..0000000000
--- a/rust/bindings/uniffi/ensu/sync/src/api.udl
+++ /dev/null
@@ -1,38 +0,0 @@
-[Error]
-interface SyncError {
- Message(string message);
-};
-
-dictionary SyncAuth {
- string base_url;
- string auth_token;
- sequence<u8> master_key;
- string? user_agent;
- string? client_package;
- string? client_version;
-};
-
-dictionary SyncStats {
- i64 sessions;
- i64 messages;
-};
-
-dictionary SyncResult {
- SyncStats pulled;
- SyncStats pushed;
- i64 uploaded_attachments;
- i64 downloaded_attachments;
-};
-
-namespace sync {
- interface EnsuSync {
- [Constructor, Throws=SyncError]
- EnsuSync(string main_db_path, string attachments_db_path, sequence<u8> db_key, string attachments_dir, string meta_dir, string? plaintext_dir);
-
- [Throws=SyncError]
- SyncResult sync(SyncAuth auth);
-
- [Throws=SyncError]
- boolean download_attachment(string attachment_id, string session_uuid, SyncAuth auth);
- };
-};
diff --git a/rust/bindings/uniffi/ensu/sync/src/lib.rs b/rust/bindings/uniffi/ensu/sync/src/lib.rs
deleted file mode 100644
index 419faf34bb..0000000000
--- a/rust/bindings/uniffi/ensu/sync/src/lib.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-#![allow(unexpected_cfgs)]
-
-mod api;
-
-uniffi::setup_scaffolding!("sync");
-
-pub use api::*;
diff --git a/rust/bindings/uniffi/ensu/sync/uniffi.toml b/rust/bindings/uniffi/ensu/sync/uniffi.toml
deleted file mode 100644
index dceee8d322..0000000000
--- a/rust/bindings/uniffi/ensu/sync/uniffi.toml
+++ /dev/null
@@ -1,8 +0,0 @@
-[bindings.swift]
-link_frameworks = ["Foundation"]
-
-[bindings.kotlin]
-package_name = "io.ente.labs.ensu_sync"
-cdylib_name = "sync"
-android = true
-kotlin_target_version = "1.9.0"
diff --git a/rust/crates/ensu/README.md b/rust/crates/ensu/README.md
index 3a7e19a946..668ff43f68 100644
--- a/rust/crates/ensu/README.md
+++ b/rust/crates/ensu/README.md
@@ -7,7 +7,6 @@ For the current Ensu packaging map, see [`packaging.md`](packaging.md).
## Crates
- `db/` (`ensu-db`) β€” local chat database.
-- `sync/` (`ensu-sync`) β€” sync engine (uses `ensu-db`).
- `inference/` (`inference_rs`) β€” inference runtime.
## UniFFI bindings
@@ -15,5 +14,4 @@ For the current Ensu packaging map, see [`packaging.md`](packaging.md).
UniFFI wrapper crates live under `../../bindings/uniffi/ensu/`:
- `../../bindings/uniffi/ensu/db`
-- `../../bindings/uniffi/ensu/sync`
- `../../bindings/uniffi/ensu/inference`
diff --git a/rust/crates/ensu/db/src/ensu.rs b/rust/crates/ensu/db/src/ensu.rs
index 20a70fb600..13af8e4b96 100644
--- a/rust/crates/ensu/db/src/ensu.rs
+++ b/rust/crates/ensu/db/src/ensu.rs
@@ -5,7 +5,7 @@ use uuid::Uuid;
use crate::Result;
use crate::attachments_db::{AttachmentUploadRow, AttachmentsDb, UploadState};
use crate::db::ChatDb;
-use crate::models::{Attachment, AttachmentMeta, EntityType, Message, Session, SessionWithPreview};
+use crate::models::{Attachment, AttachmentMeta, Message, Session, SessionWithPreview};
use crate::traits::{Clock, UuidGen};
/// High-level DB that ties together the main chat DB and the attachments upload-state DB.
@@ -228,10 +228,6 @@ impl<B: crate::Backend> EnsuDb<B> {
.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,
@@ -262,96 +258,10 @@ impl<B: crate::Backend> EnsuDb<B> {
.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_session_remote_id(&self, uuid: Uuid) -> Result<Option<String>> {
- self.chat.get_session_remote_id(uuid)
- }
-
- pub fn set_session_remote_id(&self, uuid: Uuid, remote_id: &str) -> Result<()> {
- self.chat.set_session_remote_id(uuid, remote_id)
- }
-
- pub fn get_session_uuid_by_remote_id(&self, remote_id: &str) -> Result<Option<Uuid>> {
- self.chat.get_session_uuid_by_remote_id(remote_id)
- }
-
- pub fn mark_message_synced(&self, uuid: Uuid) -> Result<()> {
- self.chat.mark_message_synced(uuid)
- }
-
pub fn set_message_remote_id(&self, uuid: Uuid, remote_id: &str) -> Result<()> {
self.chat.set_message_remote_id(uuid, remote_id)
}
- pub fn get_message_remote_id(&self, uuid: Uuid) -> Result<Option<String>> {
- self.chat.get_message_remote_id(uuid)
- }
-
- pub fn get_message_uuid_by_remote_id(&self, remote_id: &str) -> Result<Option<Uuid>> {
- self.chat.get_message_uuid_by_remote_id(remote_id)
- }
-
- pub fn get_sessions_needing_sync(&self) -> Result<Vec<Session>> {
- self.chat.get_sessions_needing_sync()
- }
-
- pub fn count_needing_sync(&self) -> Result<i64> {
- self.chat.count_needing_sync()
- }
-
- pub fn get_sessions_needing_sync_batch(
- &self,
- limit: i64,
- order_desc: bool,
- ) -> Result<Vec<Session>> {
- self.chat.get_sessions_needing_sync_batch(limit, order_desc)
- }
-
- pub fn set_session_server_updated_at(&self, uuid: Uuid, updated_at: i64) -> Result<()> {
- self.chat.set_session_server_updated_at(uuid, updated_at)
- }
-
- pub fn set_message_server_updated_at(&self, uuid: Uuid, updated_at: i64) -> Result<()> {
- self.chat.set_message_server_updated_at(uuid, updated_at)
- }
-
- pub fn get_pending_deletions(&self) -> Result<Vec<(EntityType, Uuid)>> {
- self.chat.get_pending_deletions()
- }
-
- pub fn get_deleted_sessions(&self) -> Result<Vec<(Uuid, i64)>> {
- self.chat.get_deleted_sessions()
- }
-
- pub fn get_deleted_messages(&self) -> Result<Vec<(Uuid, i64)>> {
- self.chat.get_deleted_messages()
- }
-
- 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,
- remote_id: &str,
- title: &str,
- created_at: i64,
- updated_at: i64,
- ) -> Result<Session> {
- self.chat
- .upsert_session_from_remote(session_uuid, remote_id, 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)
- }
-
#[allow(clippy::too_many_arguments)]
pub fn upsert_message_from_remote(
&self,
@@ -415,24 +325,6 @@ impl<B: crate::Backend> EnsuDb<B> {
pub fn get_attachment_upload_state(&self, attachment_id: &str) -> Result<Option<UploadState>> {
self.attachments.get_upload_state(attachment_id)
}
-
- pub fn mark_all_needs_sync(&self) -> Result<()> {
- self.chat.mark_all_needs_sync()
- }
-
- pub fn clear_all_server_timestamps(&self) -> Result<()> {
- self.chat.clear_all_server_timestamps()
- }
-
- pub fn reset_sync_state(&self) -> Result<()> {
- self.chat.reset_sync_state()?;
- self.attachments.reset_all_upload_state()?;
- Ok(())
- }
-
- pub fn reset_attachment_sync_state(&self) -> Result<()> {
- self.attachments.reset_all_upload_state()
- }
}
#[cfg(feature = "sqlite")]
diff --git a/rust/crates/ensu/db/src/lib.rs b/rust/crates/ensu/db/src/lib.rs
index 445d00e1e8..255c75557c 100644
--- a/rust/crates/ensu/db/src/lib.rs
+++ b/rust/crates/ensu/db/src/lib.rs
@@ -12,8 +12,6 @@ pub mod image;
pub mod migrations;
pub mod models;
pub mod schema;
-pub mod sync_state_db;
-pub mod sync_state_schema;
pub mod traits;
pub use crate::attachments_db::{AttachmentUploadRow, AttachmentsDb, UploadState};
@@ -28,7 +26,6 @@ pub use crate::models::{
Attachment, AttachmentKind, AttachmentMeta, EntityType, Message, Sender, Session,
SessionWithPreview,
};
-pub use crate::sync_state_db::{SyncEntityState, SyncStateDb};
pub use crate::traits::{
AttachmentStore, Clock, FileMetaStore, FsAttachmentStore, MetaStore, RandomUuidGen,
SystemClock, UuidGen,
diff --git a/rust/crates/ensu/db/src/sync_state_db.rs b/rust/crates/ensu/db/src/sync_state_db.rs
deleted file mode 100644
index 6334e54b96..0000000000
--- a/rust/crates/ensu/db/src/sync_state_db.rs
+++ /dev/null
@@ -1,230 +0,0 @@
-use std::path::Path;
-
-use uuid::Uuid;
-
-use crate::Result;
-use crate::backend::{Backend, RowExt, Value};
-use crate::sync_state_schema;
-
-#[derive(Debug, Clone, Default, PartialEq, Eq)]
-pub struct SyncEntityState {
- pub remote_id: Option<String>,
- pub server_updated_at: Option<i64>,
-}
-
-pub struct SyncStateDb<B: Backend> {
- backend: B,
-}
-
-impl<B: Backend> SyncStateDb<B> {
- pub fn new(backend: B) -> Result<Self> {
- backend.execute_batch(sync_state_schema::CREATE_ALL)?;
- Ok(Self { backend })
- }
-
- pub fn get_session_state(&self, uuid: Uuid) -> Result<Option<SyncEntityState>> {
- self.get_entity_state("sync_sessions", uuid)
- }
-
- pub fn get_message_state(&self, uuid: Uuid) -> Result<Option<SyncEntityState>> {
- self.get_entity_state("sync_messages", uuid)
- }
-
- pub fn get_session_remote_id(&self, uuid: Uuid) -> Result<Option<String>> {
- self.get_entity_remote_id("sync_sessions", uuid)
- }
-
- pub fn get_message_remote_id(&self, uuid: Uuid) -> Result<Option<String>> {
- self.get_entity_remote_id("sync_messages", uuid)
- }
-
- pub fn get_session_uuid_by_remote_id(&self, remote_id: &str) -> Result<Option<Uuid>> {
- self.get_uuid_by_remote_id("sync_sessions", remote_id)
- }
-
- pub fn get_message_uuid_by_remote_id(&self, remote_id: &str) -> Result<Option<Uuid>> {
- self.get_uuid_by_remote_id("sync_messages", remote_id)
- }
-
- pub fn set_session_state(
- &self,
- uuid: Uuid,
- remote_id: Option<&str>,
- server_updated_at: Option<i64>,
- ) -> Result<()> {
- self.set_entity_state("sync_sessions", uuid, remote_id, server_updated_at)
- }
-
- pub fn set_message_state(
- &self,
- uuid: Uuid,
- remote_id: Option<&str>,
- server_updated_at: Option<i64>,
- ) -> Result<()> {
- self.set_entity_state("sync_messages", uuid, remote_id, server_updated_at)
- }
-
- pub fn set_session_remote_id(&self, uuid: Uuid, remote_id: Option<&str>) -> Result<()> {
- self.set_entity_remote_id("sync_sessions", uuid, remote_id)
- }
-
- pub fn set_message_remote_id(&self, uuid: Uuid, remote_id: Option<&str>) -> Result<()> {
- self.set_entity_remote_id("sync_messages", uuid, remote_id)
- }
-
- pub fn set_session_server_updated_at(&self, uuid: Uuid, updated_at: i64) -> Result<()> {
- self.set_entity_server_updated_at("sync_sessions", uuid, updated_at)
- }
-
- pub fn set_message_server_updated_at(&self, uuid: Uuid, updated_at: i64) -> Result<()> {
- self.set_entity_server_updated_at("sync_messages", uuid, updated_at)
- }
-
- pub fn delete_session_state(&self, uuid: Uuid) -> Result<()> {
- self.delete_entity_state("sync_sessions", uuid)
- }
-
- pub fn delete_message_state(&self, uuid: Uuid) -> Result<()> {
- self.delete_entity_state("sync_messages", uuid)
- }
-
- pub fn clear_state(&self) -> Result<()> {
- self.backend.execute("DELETE FROM sync_sessions", &[])?;
- self.backend.execute("DELETE FROM sync_messages", &[])?;
- Ok(())
- }
-
- pub fn get_meta(&self, key: &str) -> Result<Option<Vec<u8>>> {
- let row = self.backend.query_row(
- "SELECT value FROM sync_meta WHERE key = ?",
- &[Value::Text(key.to_string())],
- )?;
- row.map(|row| row.get_blob(0)).transpose()
- }
-
- pub fn set_meta(&self, key: &str, value: &[u8]) -> Result<()> {
- self.backend.execute(
- "INSERT INTO sync_meta (key, value) VALUES (?, ?) \n ON CONFLICT(key) DO UPDATE SET value = excluded.value",
- &[Value::Text(key.to_string()), Value::Blob(value.to_vec())],
- )?;
- Ok(())
- }
-
- pub fn delete_meta(&self, key: &str) -> Result<()> {
- self.backend.execute(
- "DELETE FROM sync_meta WHERE key = ?",
- &[Value::Text(key.to_string())],
- )?;
- Ok(())
- }
-
- pub fn clear_meta(&self) -> Result<()> {
- self.backend.execute("DELETE FROM sync_meta", &[])?;
- Ok(())
- }
-
- fn get_entity_state(&self, table: &str, uuid: Uuid) -> Result<Option<SyncEntityState>> {
- let query = format!("SELECT remote_id, server_updated_at FROM {table} WHERE client_id = ?");
- let row = self
- .backend
- .query_row(&query, &[Value::Text(uuid.to_string())])?;
- row.map(|row| {
- Ok(SyncEntityState {
- remote_id: row.get_optional_string(0)?,
- server_updated_at: row.get_optional_i64(1)?,
- })
- })
- .transpose()
- }
-
- fn get_entity_remote_id(&self, table: &str, uuid: Uuid) -> Result<Option<String>> {
- let query = format!("SELECT remote_id FROM {table} WHERE client_id = ?");
- let row = self
- .backend
- .query_row(&query, &[Value::Text(uuid.to_string())])?;
- match row {
- Some(row) => row.get_optional_string(0),
- None => Ok(None),
- }
- }
-
- fn get_uuid_by_remote_id(&self, table: &str, remote_id: &str) -> Result<Option<Uuid>> {
- let query = format!("SELECT client_id FROM {table} WHERE remote_id = ?");
- let row = self
- .backend
- .query_row(&query, &[Value::Text(remote_id.to_string())])?;
- match row {
- Some(row) => Ok(Some(Uuid::parse_str(&row.get_string(0)?)?)),
- None => Ok(None),
- }
- }
-
- fn set_entity_state(
- &self,
- table: &str,
- uuid: Uuid,
- remote_id: Option<&str>,
- server_updated_at: Option<i64>,
- ) -> Result<()> {
- let query = format!(
- "INSERT INTO {table} (client_id, remote_id, server_updated_at) VALUES (?, ?, ?) \n ON CONFLICT(client_id) DO UPDATE SET \n remote_id = COALESCE(excluded.remote_id, {table}.remote_id), \n server_updated_at = COALESCE(excluded.server_updated_at, {table}.server_updated_at)"
- );
- self.backend.execute(
- &query,
- &[
- Value::Text(uuid.to_string()),
- remote_id
- .map(|value| Value::Text(value.to_string()))
- .unwrap_or(Value::Null),
- server_updated_at.map(Value::Integer).unwrap_or(Value::Null),
- ],
- )?;
- Ok(())
- }
-
- fn set_entity_remote_id(&self, table: &str, uuid: Uuid, remote_id: Option<&str>) -> Result<()> {
- let query = format!(
- "INSERT INTO {table} (client_id, remote_id) VALUES (?, ?) \n ON CONFLICT(client_id) DO UPDATE SET remote_id = excluded.remote_id"
- );
- self.backend.execute(
- &query,
- &[
- Value::Text(uuid.to_string()),
- remote_id
- .map(|value| Value::Text(value.to_string()))
- .unwrap_or(Value::Null),
- ],
- )?;
- Ok(())
- }
-
- fn set_entity_server_updated_at(&self, table: &str, uuid: Uuid, updated_at: i64) -> Result<()> {
- let query = format!(
- "INSERT INTO {table} (client_id, server_updated_at) VALUES (?, ?) \n ON CONFLICT(client_id) DO UPDATE SET server_updated_at = excluded.server_updated_at"
- );
- self.backend.execute(
- &query,
- &[Value::Text(uuid.to_string()), Value::Integer(updated_at)],
- )?;
- Ok(())
- }
-
- fn delete_entity_state(&self, table: &str, uuid: Uuid) -> Result<()> {
- let query = format!("DELETE FROM {table} WHERE client_id = ?");
- self.backend
- .execute(&query, &[Value::Text(uuid.to_string())])?;
- Ok(())
- }
-}
-
-#[cfg(feature = "sqlite")]
-impl SyncStateDb<crate::backend::sqlite::SqliteBackend> {
- pub fn open_sqlite(path: impl AsRef<Path>) -> Result<Self> {
- let backend = crate::backend::sqlite::SqliteBackend::open(path)?;
- Self::new(backend)
- }
-
- pub fn open_sqlite_with_defaults(path: impl AsRef<Path>) -> Result<Self> {
- Self::open_sqlite(path)
- }
-}
diff --git a/rust/crates/ensu/db/src/sync_state_schema.rs b/rust/crates/ensu/db/src/sync_state_schema.rs
deleted file mode 100644
index 7f4d311b10..0000000000
--- a/rust/crates/ensu/db/src/sync_state_schema.rs
+++ /dev/null
@@ -1,49 +0,0 @@
-pub const CREATE_SYNC_SESSIONS: &str = "
-CREATE TABLE IF NOT EXISTS sync_sessions (
- client_id TEXT PRIMARY KEY NOT NULL,
- remote_id TEXT,
- server_updated_at INTEGER
-);
-";
-
-pub const CREATE_SYNC_MESSAGES: &str = "
-CREATE TABLE IF NOT EXISTS sync_messages (
- client_id TEXT PRIMARY KEY NOT NULL,
- remote_id TEXT,
- server_updated_at INTEGER
-);
-";
-
-pub const CREATE_SYNC_META: &str = "
-CREATE TABLE IF NOT EXISTS sync_meta (
- key TEXT PRIMARY KEY NOT NULL,
- value BLOB NOT NULL
-);
-";
-
-pub const CREATE_INDEXES: &str = "
-CREATE INDEX IF NOT EXISTS idx_sync_sessions_remote ON sync_sessions(remote_id);
-CREATE INDEX IF NOT EXISTS idx_sync_messages_remote ON sync_messages(remote_id);
-";
-
-pub const CREATE_ALL: &str = "
-CREATE TABLE IF NOT EXISTS sync_sessions (
- client_id TEXT PRIMARY KEY NOT NULL,
- remote_id TEXT,
- server_updated_at INTEGER
-);
-
-CREATE TABLE IF NOT EXISTS sync_messages (
- client_id TEXT PRIMARY KEY NOT NULL,
- remote_id TEXT,
- server_updated_at INTEGER
-);
-
-CREATE TABLE IF NOT EXISTS sync_meta (
- key TEXT PRIMARY KEY NOT NULL,
- value BLOB NOT NULL
-);
-
-CREATE INDEX IF NOT EXISTS idx_sync_sessions_remote ON sync_sessions(remote_id);
-CREATE INDEX IF NOT EXISTS idx_sync_messages_remote ON sync_messages(remote_id);
-";
diff --git a/rust/crates/ensu/packaging.md b/rust/crates/ensu/packaging.md
index 40b1dbe312..db9a1993b9 100644
--- a/rust/crates/ensu/packaging.md
+++ b/rust/crates/ensu/packaging.md
@@ -16,7 +16,6 @@ Core rust crate is in `rust/crates/core`.
Ensu specific Rust crates are in `rust/crates/ensu`
- Local chat database: `rust/crates/ensu/db`
-- Sync engine: `rust/crates/ensu/sync`
- Inference runtime: `rust/crates/ensu/inference`
## Adapter/Binding layers
diff --git a/rust/crates/ensu/sync/Cargo.toml b/rust/crates/ensu/sync/Cargo.toml
deleted file mode 100644
index a788a3f1b8..0000000000
--- a/rust/crates/ensu/sync/Cargo.toml
+++ /dev/null
@@ -1,19 +0,0 @@
-[package]
-name = "ensu-sync"
-edition = "2024"
-
-[dependencies]
-ensu-db.workspace = true
-ente-core.workspace = true
-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.13"
-sha2 = "0.11"
-zeroize = "1"
-
-[dev-dependencies]
-httpmock = "0.7"
-tempfile = "3"
diff --git a/rust/crates/ensu/sync/src/conflict.rs b/rust/crates/ensu/sync/src/conflict.rs
deleted file mode 100644
index 631c6e5bcc..0000000000
--- a/rust/crates/ensu/sync/src/conflict.rs
+++ /dev/null
@@ -1,239 +0,0 @@
-use std::collections::{HashMap, HashSet};
-
-use ensu_db::{AttachmentMeta, Message, Sender};
-use uuid::Uuid;
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum ConflictResolution {
- LocalWins,
- RemoteWins,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub struct LocalSyncState {
- pub uuid: Uuid,
- pub needs_sync: bool,
- pub server_updated_at: Option<i64>,
-}
-
-pub fn resolve_session_conflict(
- local: LocalSyncState,
- remote_updated_at: i64,
- remote_uuid: Uuid,
-) -> ConflictResolution {
- if local.needs_sync && local.server_updated_at.is_none() {
- return ConflictResolution::LocalWins;
- }
-
- let local_ts = local.server_updated_at.unwrap_or(0);
- if local_ts > remote_updated_at {
- ConflictResolution::LocalWins
- } else if local_ts < remote_updated_at {
- ConflictResolution::RemoteWins
- } else if local.uuid > remote_uuid {
- ConflictResolution::LocalWins
- } else {
- ConflictResolution::RemoteWins
- }
-}
-
-pub fn should_accept_remote_session(
- local: LocalSyncState,
- remote_updated_at: i64,
- remote_uuid: Uuid,
-) -> bool {
- resolve_session_conflict(local, remote_updated_at, remote_uuid)
- == ConflictResolution::RemoteWins
-}
-
-pub fn resolve_message_conflict(
- local: LocalSyncState,
- remote_updated_at: i64,
- remote_uuid: Uuid,
-) -> ConflictResolution {
- if local.needs_sync && local.server_updated_at.is_none() {
- return ConflictResolution::LocalWins;
- }
-
- let local_ts = local.server_updated_at.unwrap_or(0);
- if local_ts > remote_updated_at {
- ConflictResolution::LocalWins
- } else if local_ts < remote_updated_at {
- ConflictResolution::RemoteWins
- } else if local.uuid > remote_uuid {
- ConflictResolution::LocalWins
- } else {
- ConflictResolution::RemoteWins
- }
-}
-
-pub fn should_accept_remote_message(
- local: LocalSyncState,
- remote_updated_at: i64,
- remote_uuid: Uuid,
-) -> bool {
- resolve_message_conflict(local, remote_updated_at, remote_uuid)
- == ConflictResolution::RemoteWins
-}
-
-pub fn find_duplicate_message(
- local_messages: &[Message],
- sender: &Sender,
- text: &str,
- attachments: &[AttachmentMeta],
- created_at: i64,
- parent: Option<Uuid>,
-) -> 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 message.parent_message_uuid != parent {
- 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, att.size))
- .collect()
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use ensu_db::{AttachmentKind, AttachmentMeta, Message, Sender};
- use uuid::Uuid;
-
- #[test]
- fn duplicate_message_respects_parent_and_attachment_size() {
- let session_uuid = Uuid::new_v4();
- let parent_uuid = Uuid::new_v4();
- let message_uuid = Uuid::new_v4();
- let attachment = AttachmentMeta {
- id: "att-1".to_string(),
- kind: AttachmentKind::Image,
- size: 512,
- name: "photo.png".to_string(),
- };
-
- let local = Message {
- uuid: message_uuid,
- session_uuid,
- parent_message_uuid: Some(parent_uuid),
- sender: Sender::SelfUser,
- text: "hello".to_string(),
- attachments: vec![attachment.clone()],
- created_at: 10_000,
- remote_id: None,
- server_updated_at: None,
- needs_sync: true,
- deleted_at: None,
- };
-
- let wrong_size = AttachmentMeta {
- size: 256,
- ..attachment.clone()
- };
- assert!(
- find_duplicate_message(
- std::slice::from_ref(&local),
- &Sender::SelfUser,
- "hello",
- &[wrong_size],
- 10_000,
- Some(parent_uuid),
- )
- .is_none()
- );
-
- assert!(
- find_duplicate_message(
- std::slice::from_ref(&local),
- &Sender::SelfUser,
- "hello",
- std::slice::from_ref(&attachment),
- 10_000,
- None,
- )
- .is_none()
- );
-
- assert_eq!(
- find_duplicate_message(
- &[local],
- &Sender::SelfUser,
- "hello",
- &[attachment],
- 10_000,
- Some(parent_uuid),
- ),
- Some(message_uuid)
- );
- }
-}
diff --git a/rust/crates/ensu/sync/src/crypto.rs b/rust/crates/ensu/sync/src/crypto.rs
deleted file mode 100644
index 3413d0398a..0000000000
--- a/rust/crates/ensu/sync/src/crypto.rs
+++ /dev/null
@@ -1,84 +0,0 @@
-use ente_core::crypto::{self, Header, Key, blob};
-use hkdf::Hkdf;
-use serde::{Serialize, de::DeserializeOwned};
-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::try_from_slice(key)?)?;
- Ok(EncryptedPayload {
- encrypted_data: crypto::encode_b64(&encrypted.encrypted_data),
- header: crypto::encode_b64(encrypted.decryption_header.as_bytes()),
- })
-}
-
-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::try_from_slice(&header)?,
- &Key::try_from_slice(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, &Key::try_from_slice(master_key)?)?;
- Ok(EncryptedPayload {
- encrypted_data: crypto::encode_b64(&encrypted.encrypted_data),
- header: crypto::encode_b64(encrypted.decryption_header.as_bytes()),
- })
-}
-
-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::try_from_slice(&header)?,
- &Key::try_from_slice(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(ensu_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(ensu_db::crypto::decrypt_blob(ciphertext, &key)?)
-}
diff --git a/rust/crates/ensu/sync/src/diff_cursor.rs b/rust/crates/ensu/sync/src/diff_cursor.rs
deleted file mode 100644
index 7085c604c7..0000000000
--- a/rust/crates/ensu/sync/src/diff_cursor.rs
+++ /dev/null
@@ -1,36 +0,0 @@
-use serde::{Deserialize, Serialize};
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
-#[serde(rename_all = "camelCase")]
-pub struct SyncCursor {
- #[serde(alias = "base_since_time")]
- pub base_since_time: i64,
- #[serde(alias = "since_time")]
- pub since_time: i64,
- #[serde(alias = "max_time")]
- pub max_time: i64,
- #[serde(alias = "since_type")]
- pub since_type: String,
- #[serde(alias = "since_id")]
- 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/crates/ensu/sync/src/errors.rs b/rust/crates/ensu/sync/src/errors.rs
deleted file mode 100644
index 2e185f718d..0000000000
--- a/rust/crates/ensu/sync/src/errors.rs
+++ /dev/null
@@ -1,54 +0,0 @@
-use thiserror::Error;
-
-#[derive(Debug, Error)]
-pub enum SyncError {
- #[error("not logged in")]
- NotLoggedIn,
- #[error("unauthorized")]
- Unauthorized,
- #[error("db error: {0}")]
- Db(#[from] ensu_db::Error),
- #[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("sync already in progress")]
- SyncInProgress,
- #[error("serde error: {0}")]
- Serde(String),
- #[error("io error: {0}")]
- Io(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/crates/ensu/sync/src/http.rs b/rust/crates/ensu/sync/src/http.rs
deleted file mode 100644
index ffd3e78f73..0000000000
--- a/rust/crates/ensu/sync/src/http.rs
+++ /dev/null
@@ -1,387 +0,0 @@
-use std::time::Duration;
-
-use ente_core::urls::PRODUCTION_API_BASE_URL;
-use reqwest::Url;
-use reqwest::blocking::{Client, Response};
-use reqwest::header::{HeaderMap, HeaderName, HeaderValue, LOCATION};
-use reqwest::redirect::Policy;
-use serde::Serialize;
-use serde::de::DeserializeOwned;
-use uuid::Uuid;
-
-use crate::errors::SyncError;
-
-const DEFAULT_BASE_URL: &str = PRODUCTION_API_BASE_URL;
-
-#[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,
- base_origin: Url,
- 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 base_url = config.base_url.trim_end_matches('/').to_string();
- let base_origin = Url::parse(&base_url)
- .map_err(|_| SyncError::InvalidResponse("invalid base url".to_string()))?;
- let is_http = base_url.starts_with("http://");
- let is_default = base_url.starts_with(DEFAULT_BASE_URL);
- let allow_insecure = is_http || !is_default;
-
- let mut builder = Client::builder().redirect(Policy::none());
- if let Some(timeout) = config.timeout_secs {
- builder = builder.timeout(Duration::from_secs(timeout));
- }
- if allow_insecure {
- 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,
- base_origin,
- 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 = self.parse_url(url)?;
- for _ in 0..5 {
- let headers = self.build_headers_for_url(&current_url);
- let resp = self
- .client
- .get(current_url.clone())
- .headers(headers)
- .send()
- .map_err(map_reqwest_error)?;
- if resp.status().is_redirection()
- && let Some(location) = resp.headers().get(LOCATION)
- {
- current_url = self.resolve_redirect(&current_url, location)?;
- 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 = self.parse_url(url)?;
- for _ in 0..5 {
- let headers = self.build_headers_for_url(&current_url);
- let resp = self
- .client
- .head(current_url.clone())
- .headers(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()
- && let Some(location) = resp.headers().get(LOCATION)
- {
- current_url = self.resolve_redirect(&current_url, location)?;
- 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 = self.parse_url(url)?;
- for _ in 0..5 {
- let resp = self
- .client
- .put(current_url.clone())
- .headers(header_map.clone())
- .body(body.to_vec())
- .send()
- .map_err(map_reqwest_error)?;
-
- if resp.status().is_redirection()
- && let Some(location) = resp.headers().get(LOCATION)
- {
- current_url = self.resolve_redirect(&current_url, location)?;
- continue;
- }
-
- return parse_empty_response(resp);
- }
-
- Err(SyncError::InvalidResponse("too many redirects".to_string()))
- }
-
- fn parse_url(&self, url: &str) -> Result<Url, SyncError> {
- Url::parse(url).map_err(|_| SyncError::InvalidResponse("invalid url".to_string()))
- }
-
- fn resolve_redirect(
- &self,
- current_url: &Url,
- location: &HeaderValue,
- ) -> Result<Url, SyncError> {
- let next = location
- .to_str()
- .map_err(|_| SyncError::InvalidResponse("invalid redirect location".to_string()))?;
- Url::parse(next)
- .or_else(|_| current_url.join(next))
- .map_err(|_| SyncError::InvalidResponse("invalid redirect location".to_string()))
- }
-
- fn is_same_origin(&self, url: &Url) -> bool {
- self.base_origin.scheme() == url.scheme()
- && self.base_origin.host_str() == url.host_str()
- && self.base_origin.port_or_known_default() == url.port_or_known_default()
- }
-
- fn build_headers_for_url(&self, url: &Url) -> HeaderMap {
- if self.is_same_origin(url) {
- self.build_headers()
- } else {
- self.build_public_headers()
- }
- }
-
- fn build_public_headers(&self) -> HeaderMap {
- let mut headers = HeaderMap::new();
- if let Some(agent) = &self.user_agent
- && let Ok(value) = HeaderValue::from_str(agent)
- {
- headers.insert("User-Agent", value);
- }
- headers
- }
-
- fn build_headers(&self) -> HeaderMap {
- let mut headers = HeaderMap::new();
- if let Some(agent) = &self.user_agent
- && let Ok(value) = HeaderValue::from_str(agent)
- {
- headers.insert("User-Agent", value);
- }
- if let Some(pkg) = &self.client_package
- && let Ok(value) = HeaderValue::from_str(pkg)
- {
- headers.insert("X-Client-Package", value);
- }
- if let Some(version) = &self.client_version
- && 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 >= 300 {
- 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 >= 300 {
- 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()
- && 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/crates/ensu/sync/src/lib.rs b/rust/crates/ensu/sync/src/lib.rs
deleted file mode 100644
index ef465fd53c..0000000000
--- a/rust/crates/ensu/sync/src/lib.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-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::{
- MigrationConfig, MigrationPriority, MigrationProgress, MigrationProgressCallback,
- MigrationState, SyncAuth, SyncEngine, SyncResult, SyncStats, fetch_chat_key,
-};
diff --git a/rust/crates/ensu/sync/src/models.rs b/rust/crates/ensu/sync/src/models.rs
deleted file mode 100644
index 91e7f3541c..0000000000
--- a/rust/crates/ensu/sync/src/models.rs
+++ /dev/null
@@ -1,197 +0,0 @@
-use serde::{Deserialize, Serialize};
-
-use crate::diff_cursor::SyncCursor;
-use ensu_db::AttachmentKind;
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct EncryptedPayload {
- #[serde(
- alias = "encrypted_key",
- alias = "encryptedKey",
- alias = "encrypted_data",
- alias = "encryptedData"
- )]
- pub encrypted_data: String,
- pub header: String,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct ChatKeyPayload {
- #[serde(
- rename = "encryptedKey",
- default,
- skip_serializing_if = "Option::is_none",
- alias = "encrypted_key"
- )]
- pub encrypted_key: Option<String>,
- #[serde(
- rename = "encryptedData",
- default,
- skip_serializing_if = "Option::is_none",
- alias = "encrypted_data"
- )]
- 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 = "camelCase")]
-pub struct RemoteSession {
- #[serde(rename = "sessionUUID", alias = "session_uuid")]
- pub session_uuid: String,
- #[serde(rename = "encryptedData", alias = "encrypted_data")]
- pub encrypted_data: String,
- pub header: String,
- #[serde(
- rename = "clientMetadata",
- alias = "client_metadata",
- skip_serializing_if = "Option::is_none"
- )]
- pub client_metadata: Option<String>,
- #[serde(alias = "created_at")]
- pub created_at: i64,
- #[serde(alias = "updated_at")]
- pub updated_at: i64,
- #[serde(alias = "is_deleted")]
- pub is_deleted: Option<bool>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct RemoteMessage {
- #[serde(rename = "messageUUID", alias = "message_uuid")]
- pub message_uuid: String,
- #[serde(rename = "sessionUUID", alias = "session_uuid")]
- pub session_uuid: String,
- #[serde(rename = "parentMessageUUID", alias = "parent_message_uuid")]
- pub parent_message_uuid: Option<String>,
- pub sender: String,
- pub attachments: Vec<RemoteAttachment>,
- #[serde(rename = "encryptedData", alias = "encrypted_data")]
- pub encrypted_data: String,
- pub header: String,
- #[serde(
- rename = "clientMetadata",
- alias = "client_metadata",
- skip_serializing_if = "Option::is_none"
- )]
- pub client_metadata: Option<String>,
- #[serde(alias = "created_at")]
- pub created_at: i64,
- #[serde(alias = "updated_at")]
- pub updated_at: Option<i64>,
- #[serde(alias = "is_deleted")]
- pub is_deleted: Option<bool>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct RemoteAttachment {
- pub id: String,
- pub size: i64,
- #[serde(
- rename = "clientMetadata",
- alias = "client_metadata",
- skip_serializing_if = "Option::is_none"
- )]
- pub client_metadata: Option<String>,
- #[serde(
- rename = "encryptedName",
- alias = "encrypted_name",
- skip_serializing_if = "Option::is_none"
- )]
- pub encrypted_name: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub kind: Option<AttachmentKind>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct SessionTombstone {
- #[serde(rename = "sessionUUID", alias = "session_uuid")]
- pub session_uuid: String,
- #[serde(alias = "deleted_at")]
- pub deleted_at: Option<i64>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct MessageTombstone {
- #[serde(rename = "messageUUID", alias = "message_uuid")]
- pub message_uuid: String,
- #[serde(alias = "deleted_at")]
- pub deleted_at: Option<i64>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-#[serde(rename_all = "camelCase")]
-pub struct DiffTombstones {
- #[serde(default)]
- pub sessions: Vec<SessionTombstone>,
- #[serde(default)]
- pub messages: Vec<MessageTombstone>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-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 = "camelCase")]
-pub struct UploadUrlRequest {
- pub content_length: i64,
- #[serde(
- rename = "contentMD5",
- alias = "content_md5",
- skip_serializing_if = "Option::is_none"
- )]
- pub content_md5: Option<String>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct UploadUrlResponse {
- #[serde(rename = "attachmentId", alias = "attachment_id")]
- pub attachment_id: String,
- #[serde(rename = "objectKey", alias = "object_key")]
- pub object_key: String,
- pub url: String,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct SessionPayload {
- pub title: String,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct MessagePayload {
- pub text: String,
-}
diff --git a/rust/crates/ensu/sync/src/sync.rs b/rust/crates/ensu/sync/src/sync.rs
deleted file mode 100644
index 326f7c3e1a..0000000000
--- a/rust/crates/ensu/sync/src/sync.rs
+++ /dev/null
@@ -1,1955 +0,0 @@
-use std::collections::{HashMap, HashSet};
-use std::path::PathBuf;
-use std::sync::Arc;
-use std::sync::atomic::{AtomicBool, Ordering};
-
-use zeroize::Zeroizing;
-
-use ensu_db::{
- Attachment, AttachmentKind, AttachmentMeta, AttachmentStore, Clock, EnsuDb, EntityType,
- FsAttachmentStore, Message, Sender, Session, SqliteBackend, SyncEntityState, SyncStateDb,
- SystemClock, UploadState,
-};
-use ente_core::crypto::Key;
-use uuid::Uuid;
-
-use crate::conflict::{
- LocalSyncState, find_duplicate_message, order_for_sync, should_accept_remote_message,
- should_accept_remote_session,
-};
-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";
-const OFFLINE_SEED_META_KEY: &str = "llmchat.offline.seeded.v1";
-const ZERO_UUID: &str = "00000000-0000-0000-0000-000000000000";
-
-static SYNC_LOCK: AtomicBool = AtomicBool::new(false);
-
-#[derive(Debug, Clone)]
-pub struct MigrationConfig {
- pub batch_size: i64,
- pub priority: MigrationPriority,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum MigrationPriority {
- RecentFirst,
- OldestFirst,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum MigrationState {
- NotNeeded,
- InProgress,
- Complete,
- Failed,
-}
-
-#[derive(Debug, Clone)]
-pub struct MigrationProgress {
- pub state: MigrationState,
- pub processed: i64,
- pub remaining: i64,
- pub total: i64,
-}
-
-pub trait MigrationProgressCallback: Send + Sync {
- fn on_progress(&self, progress: MigrationProgress);
-}
-
-struct SyncLockGuard;
-
-impl Drop for SyncLockGuard {
- fn drop(&mut self) {
- SYNC_LOCK.store(false, Ordering::SeqCst);
- }
-}
-
-#[derive(Debug, Clone)]
-pub struct SyncAuth {
- pub base_url: String,
- pub auth_token: String,
- pub master_key: Zeroizing<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,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum ChatKeyStatus {
- Cached,
- Remote,
- Created,
-}
-
-pub struct SyncEngine {
- db: EnsuDb<SqliteBackend>,
- sync_state: SyncStateDb<SqliteBackend>,
- attachment_store: FsAttachmentStore,
- plaintext_dir: Option<PathBuf>,
- diff_limit: i64,
- offline_db: std::sync::Mutex<Option<OfflineDbConfig>>,
-}
-
-#[derive(Clone)]
-struct OfflineDbConfig {
- path: String,
- key: Vec<u8>,
-}
-
-impl SyncEngine {
- pub fn new(
- main_db_path: String,
- sync_db_path: String,
- db_key: Vec<u8>,
- attachments_dir: String,
- _meta_dir: String,
- plaintext_dir: Option<String>,
- ) -> Result<Self, SyncError> {
- ensu_db::traits::ensure_directory(&attachments_dir)?;
- if let Some(ref dir) = plaintext_dir {
- let _ = ensu_db::traits::ensure_directory(dir);
- }
-
- let db = EnsuDb::open_sqlite_with_defaults(main_db_path, sync_db_path.clone(), db_key)?;
- let sync_state = SyncStateDb::open_sqlite_with_defaults(sync_db_path)?;
- let attachment_store = FsAttachmentStore::new(attachments_dir);
- Ok(Self {
- db,
- sync_state,
- attachment_store,
- plaintext_dir: plaintext_dir.map(PathBuf::from),
- diff_limit: 500,
- offline_db: std::sync::Mutex::new(None),
- })
- }
-
- pub fn sync(&self, auth: SyncAuth) -> Result<SyncResult, SyncError> {
- if SYNC_LOCK
- .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
- .is_err()
- {
- return Err(SyncError::SyncInProgress);
- }
- let _guard = SyncLockGuard;
-
- if auth.auth_token.trim().is_empty() {
- return Err(SyncError::NotLoggedIn);
- }
- if auth.master_key.len() != ensu_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, key_status) = self.get_or_create_chat_key(&http, &master_key)?;
- let mut result = SyncResult::default();
-
- if key_status == ChatKeyStatus::Created {
- self.prepare_for_new_chat_key()?;
- } else {
- self.pull(&http, &chat_key, &mut result)?;
- }
- self.push(&http, &chat_key, &mut result)?;
-
- Ok(result)
- }
-
- pub fn sync_with_progress(
- &self,
- auth: SyncAuth,
- config: MigrationConfig,
- callback: &dyn MigrationProgressCallback,
- ) -> Result<SyncResult, SyncError> {
- if SYNC_LOCK
- .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
- .is_err()
- {
- return Err(SyncError::SyncInProgress);
- }
- let _guard = SyncLockGuard;
-
- if auth.auth_token.trim().is_empty() {
- return Err(SyncError::NotLoggedIn);
- }
- if auth.master_key.len() != ensu_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, key_status) = self.get_or_create_chat_key(&http, &master_key)?;
- let mut result = SyncResult::default();
-
- if key_status == ChatKeyStatus::Created {
- self.prepare_for_new_chat_key()?;
- } else {
- self.pull(&http, &chat_key, &mut result)?;
- }
-
- let total = self.db.count_needing_sync()?;
- let mut processed = 0;
- callback.on_progress(MigrationProgress {
- state: MigrationState::InProgress,
- processed,
- remaining: total,
- total,
- });
-
- let batch_size = if config.batch_size <= 0 {
- 1
- } else {
- config.batch_size
- };
- let order_desc = matches!(config.priority, MigrationPriority::RecentFirst);
-
- let sync_result = (|| -> Result<(), SyncError> {
- loop {
- let batch = self
- .db
- .get_sessions_needing_sync_batch(batch_size, order_desc)?;
- if batch.is_empty() {
- break;
- }
-
- for session in batch {
- self.push_session_with_messages(&http, &chat_key, &session, &mut result)?;
- processed += 1;
- let remaining = total.saturating_sub(processed);
- callback.on_progress(MigrationProgress {
- state: MigrationState::InProgress,
- processed,
- remaining,
- total,
- });
- }
- }
- Ok(())
- })();
-
- if let Err(err) = sync_result {
- let remaining = total.saturating_sub(processed);
- callback.on_progress(MigrationProgress {
- state: MigrationState::Failed,
- processed,
- remaining,
- total,
- });
- return Err(err);
- }
-
- callback.on_progress(MigrationProgress {
- state: MigrationState::Complete,
- processed,
- remaining: 0,
- total,
- });
-
- Ok(result)
- }
-
- pub fn sync_in_background(
- self: Arc<Self>,
- auth: SyncAuth,
- ) -> std::thread::JoinHandle<Result<SyncResult, SyncError>> {
- std::thread::spawn(move || self.sync(auth))
- }
-
- pub fn check_migration_status_local(&self) -> Result<Option<MigrationState>, SyncError> {
- let pending = self.db.count_needing_sync()?;
- if pending > 0 {
- return Ok(Some(MigrationState::InProgress));
- }
- Ok(None)
- }
-
- pub fn reset_sync_state(&self) -> Result<(), SyncError> {
- let _ = self.sync_state.delete_meta(CURSOR_META_KEY);
- let _ = self.sync_state.delete_meta(CHAT_KEY_META_KEY);
- let _ = self.sync_state.delete_meta(OFFLINE_SEED_META_KEY);
- let _ = self.sync_state.clear_state();
- let _ = self.sync_state.clear_meta();
- self.db.reset_attachment_sync_state()?;
- let _ = self.attachment_store.clear_all();
- if let Ok(mut offline) = self.offline_db.lock() {
- *offline = None;
- }
- Ok(())
- }
-
- pub fn seed_from_offline(
- &self,
- offline_db_path: String,
- offline_db_key: Vec<u8>,
- ) -> Result<(), SyncError> {
- if let Ok(mut offline) = self.offline_db.lock() {
- *offline = Some(OfflineDbConfig {
- path: offline_db_path.clone(),
- key: offline_db_key.clone(),
- });
- }
- if self.sync_state.get_meta(OFFLINE_SEED_META_KEY)?.is_some() {
- return Ok(());
- }
-
- let offline_db = ensu_db::ChatDb::open_sqlite_with_defaults(
- offline_db_path.clone(),
- offline_db_key.clone(),
- )?;
- let sessions = offline_db.list_sessions()?;
-
- for session in sessions {
- let _ = self.db.upsert_session(
- session.uuid,
- &session.title,
- session.created_at,
- session.updated_at,
- None,
- true,
- session.deleted_at,
- )?;
- let messages = offline_db.get_messages(session.uuid)?;
- for message in messages {
- let attachments: Vec<Attachment> = message
- .attachments
- .clone()
- .into_iter()
- .map(Attachment::from)
- .collect();
- let _ = self.db.insert_message_with_uuid_and_state(
- message.uuid,
- session.uuid,
- message.sender.as_str(),
- &message.text,
- message.parent_message_uuid,
- attachments,
- message.created_at,
- message.deleted_at,
- true,
- )?;
- }
- }
-
- self.sync_state.set_meta(OFFLINE_SEED_META_KEY, b"1")?;
- Ok(())
- }
-
- pub fn check_migration_status(&self, auth: SyncAuth) -> Result<MigrationState, SyncError> {
- if let Some(local) = self.check_migration_status_local()? {
- return Ok(local);
- }
- if auth.auth_token.trim().is_empty() {
- return Err(SyncError::NotLoggedIn);
- }
- if auth.master_key.len() != ensu_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,
- })?;
-
- if self.load_chat_key_from_meta(&master_key)?.is_some() {
- return Ok(MigrationState::NotNeeded);
- }
-
- let remote = http.get_json_optional::<ChatKeyPayload>("/llmchat/chat/key", &[]);
- match remote {
- Ok(Some(_)) => Ok(MigrationState::InProgress),
- Ok(None) => Ok(MigrationState::InProgress),
- Err(SyncError::Http {
- status: 404,
- code: Some(code),
- ..
- }) if code == "NOT_FOUND" || code == "AuthKeyNotCreated" => {
- Ok(MigrationState::InProgress)
- }
- Err(err) => Err(err),
- }
- }
-
- fn prepare_for_new_chat_key(&self) -> Result<(), SyncError> {
- self.reset_cursor_to_now()?;
- let _ = self.sync_state.clear_state();
- self.db.mark_all_needs_sync()?;
- self.db.clear_all_server_timestamps()?;
- self.db.reset_attachment_sync_state()?;
- self.attachment_store.clear_all()?;
- Ok(())
- }
-
- fn reset_cursor_to_now(&self) -> Result<(), SyncError> {
- let clock = SystemClock;
- let now = clock.now_us();
- let cursor = SyncCursor {
- base_since_time: now,
- since_time: now,
- max_time: now,
- since_type: "sessions".to_string(),
- since_id: "00000000-0000-0000-0000-000000000000".to_string(),
- };
- self.save_cursor(&cursor)?;
- Ok(())
- }
-
- 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() != ensu_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 mut remote_id = match self.db.get_attachment_remote_id(&attachment_id)? {
- Some(remote_id) => remote_id,
- None => {
- let fallback = attachment_id.clone();
- self.db
- .set_attachment_remote_id(&attachment_id, Some(&fallback))?;
- fallback
- }
- };
- let mut url = format!("{}/llmchat/chat/attachment/{}", base_url, remote_id);
- let bytes = match http.get_bytes(&url) {
- Ok(bytes) => bytes,
- Err(SyncError::Http { status: 404, .. }) => {
- self.force_upload_attachment(&http, &chat_key, session_uuid, &attachment_id)?;
- if let Some(updated) = self.db.get_attachment_remote_id(&attachment_id)? {
- remote_id = updated;
- url = format!("{}/llmchat/chat/attachment/{}", base_url, remote_id);
- }
- 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)
- }
-
- pub fn download_attachment_in_background(
- self: Arc<Self>,
- auth: SyncAuth,
- attachment_id: String,
- session_uuid: String,
- ) -> std::thread::JoinHandle<Result<bool, SyncError>> {
- std::thread::spawn(move || self.download_attachment(auth, attachment_id, session_uuid))
- }
-
- fn pull(
- &self,
- http: &HttpClient,
- chat_key: &[u8],
- result: &mut SyncResult,
- ) -> Result<(), SyncError> {
- let mut cursor = self.load_cursor()?;
- let mut seen_cursors: HashSet<SyncCursor> = HashSet::new();
-
- 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 !seen_cursors.insert(next_cursor.clone()) {
- break;
- }
-
- cursor = next_cursor;
- self.save_cursor(&cursor)?;
-
- if cursor.is_complete_cycle() {
- break;
- }
- }
-
- 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();
- let mut remote_session_map: HashMap<Uuid, Uuid> = HashMap::new();
- let mut remote_message_map: HashMap<Uuid, Uuid> = 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 remote_uuid = Uuid::parse_str(&session.session_uuid)
- .map_err(|e| SyncError::InvalidResponse(e.to_string()))?;
- let mut local_uuid = session
- .client_metadata
- .as_deref()
- .and_then(decode_client_id)
- .and_then(|value| Uuid::parse_str(&value).ok())
- .unwrap_or(remote_uuid);
- let remote_uuid_str = remote_uuid.to_string();
- let mut local = self.db.get_session(local_uuid).ok().flatten();
- let mut local_state = self.sync_state.get_session_state(local_uuid).ok().flatten();
- if let Some(state) = local_state.as_ref()
- && let Some(existing_remote) = state.remote_id.as_deref()
- && existing_remote != remote_uuid_str.as_str()
- {
- local_uuid = remote_uuid;
- local = self.db.get_session(local_uuid).ok().flatten();
- local_state = self.sync_state.get_session_state(local_uuid).ok().flatten();
- }
- remote_session_map.insert(remote_uuid, local_uuid);
- if let Some(local_session) = local.as_ref() {
- let local_sync = LocalSyncState {
- uuid: local_session.uuid,
- needs_sync: local_session.needs_sync,
- server_updated_at: local_state
- .as_ref()
- .and_then(|state| state.server_updated_at),
- };
- if !should_accept_remote_session(local_sync, session.updated_at, remote_uuid) {
- if local_state
- .as_ref()
- .and_then(|state| state.remote_id.as_deref())
- .is_none()
- {
- let _ = self
- .sync_state
- .set_session_remote_id(local_uuid, Some(&remote_uuid_str));
- }
- continue;
- }
- }
- 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(&remote_uuid)
- && 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 created_at = session
- .client_metadata
- .as_deref()
- .and_then(|metadata| decode_client_created_at(metadata, chat_key))
- .unwrap_or(session.created_at);
-
- let _ = self.db.upsert_session_from_remote(
- local_uuid,
- &remote_uuid.to_string(),
- &payload.title,
- created_at,
- effective_updated_at,
- )?;
- self.sync_state.set_session_state(
- local_uuid,
- Some(&remote_uuid_str),
- Some(session.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 remote_message_uuid = Uuid::parse_str(&message.message_uuid)
- .map_err(|e| SyncError::InvalidResponse(e.to_string()))?;
- let remote_session_uuid = Uuid::parse_str(&message.session_uuid)
- .map_err(|e| SyncError::InvalidResponse(e.to_string()))?;
- let session_uuid = remote_session_map
- .get(&remote_session_uuid)
- .cloned()
- .or_else(|| {
- self.sync_state
- .get_session_uuid_by_remote_id(&remote_session_uuid.to_string())
- .ok()
- .flatten()
- })
- .unwrap_or(remote_session_uuid);
- let remote_message_uuid_str = remote_message_uuid.to_string();
- let mut message_uuid = message
- .client_metadata
- .as_deref()
- .and_then(decode_client_id)
- .and_then(|value| Uuid::parse_str(&value).ok())
- .unwrap_or(remote_message_uuid);
- let remote_updated_at = message.updated_at.unwrap_or(message.created_at);
-
- let sender: Sender = message
- .sender
- .parse::<Sender>()
- .map_err(|e| SyncError::InvalidResponse(e.to_string()))?;
- let (attachments, attachment_remote_ids) =
- 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());
- let mut local_message = local_messages
- .iter()
- .find(|local| local.uuid == message_uuid);
- let mut local_state = self
- .sync_state
- .get_message_state(message_uuid)
- .ok()
- .flatten();
- if let Some(state) = local_state.as_ref()
- && let Some(existing_remote) = state.remote_id.as_deref()
- && existing_remote != remote_message_uuid_str.as_str()
- {
- message_uuid = remote_message_uuid;
- local_message = local_messages
- .iter()
- .find(|local| local.uuid == message_uuid);
- local_state = self
- .sync_state
- .get_message_state(message_uuid)
- .ok()
- .flatten();
- }
- remote_message_map.insert(remote_message_uuid, message_uuid);
- if let Some(local_message) = local_message {
- let local_sync = LocalSyncState {
- uuid: local_message.uuid,
- needs_sync: local_message.needs_sync,
- server_updated_at: local_state
- .as_ref()
- .and_then(|state| state.server_updated_at),
- };
- if !should_accept_remote_message(local_sync, remote_updated_at, remote_message_uuid)
- {
- if local_state
- .as_ref()
- .and_then(|state| state.remote_id.as_deref())
- .is_none()
- {
- let _ = self
- .sync_state
- .set_message_remote_id(message_uuid, Some(&remote_message_uuid_str));
- }
- 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_else(|| remote_message_map.get(&parent).cloned())
- .or_else(|| {
- self.sync_state
- .get_message_uuid_by_remote_id(&parent.to_string())
- .ok()
- .flatten()
- })
- });
-
- let created_at = message
- .client_metadata
- .as_deref()
- .and_then(|metadata| decode_client_created_at(metadata, chat_key))
- .unwrap_or(message.created_at);
-
- if let Some(dup_uuid) = find_duplicate_message(
- local_messages,
- &sender,
- &payload.text,
- &attachments,
- created_at,
- parent_uuid,
- ) {
- duplicate_map.insert(remote_message_uuid, dup_uuid);
- remote_message_map.insert(remote_message_uuid, dup_uuid);
- continue;
- }
-
- let inserted = self.db.upsert_message_from_remote(
- message_uuid,
- session_uuid,
- &remote_message_uuid.to_string(),
- sender.as_str(),
- &payload.text,
- parent_uuid,
- attachments.clone(),
- created_at,
- )?;
- self.sync_state.set_message_state(
- message_uuid,
- Some(&remote_message_uuid_str),
- Some(remote_updated_at),
- )?;
-
- for attachment in &attachments {
- let remote_id = attachment_remote_ids
- .get(&attachment.id)
- .map(String::as_str);
- let _ = self.db.upsert_attachment_with_state(
- &attachment.id,
- session_uuid,
- message_uuid,
- attachment.size,
- remote_id,
- UploadState::Uploaded,
- );
- }
-
- local_messages.push(inserted);
- result.pulled.messages += 1;
- }
-
- let clock = SystemClock;
- let now = clock.now_us();
- let offline_db = self.open_offline_db()?;
- for tombstone in &response.tombstones.sessions {
- let remote_uuid = Uuid::parse_str(&tombstone.session_uuid)
- .map_err(|e| SyncError::InvalidResponse(e.to_string()))?;
- let local_uuid = remote_session_map.get(&remote_uuid).cloned().or_else(|| {
- self.sync_state
- .get_session_uuid_by_remote_id(&remote_uuid.to_string())
- .ok()
- .flatten()
- });
- let Some(local_uuid) = local_uuid else {
- continue;
- };
- let deleted_at = tombstone.deleted_at.or(response.timestamp).unwrap_or(now);
- let local = self.db.get_session(local_uuid).ok().flatten();
- let local_state = self.sync_state.get_session_state(local_uuid).ok().flatten();
- self.apply_session_tombstone(local, local_state, local_uuid, deleted_at)?;
- if let Some(offline_db) = offline_db.as_ref()
- && offline_db.get_session(local_uuid).ok().flatten().is_some()
- {
- let _ = offline_db.apply_session_tombstone(local_uuid, deleted_at);
- }
- }
-
- for tombstone in &response.tombstones.messages {
- let remote_uuid = Uuid::parse_str(&tombstone.message_uuid)
- .map_err(|e| SyncError::InvalidResponse(e.to_string()))?;
- let local_uuid = remote_message_map.get(&remote_uuid).cloned().or_else(|| {
- self.sync_state
- .get_message_uuid_by_remote_id(&remote_uuid.to_string())
- .ok()
- .flatten()
- });
- let Some(local_uuid) = local_uuid else {
- continue;
- };
- let deleted_at = tombstone.deleted_at.or(response.timestamp).unwrap_or(now);
- let _ = self.db.apply_message_tombstone(local_uuid, deleted_at);
- let _ = self.sync_state.delete_message_state(local_uuid);
- if let Some(offline_db) = offline_db.as_ref() {
- let _ = offline_db.apply_message_tombstone(local_uuid, deleted_at);
- }
- }
-
- Ok(())
- }
-
- fn open_offline_db(&self) -> Result<Option<ensu_db::ChatDb<SqliteBackend>>, SyncError> {
- let config = match self.offline_db.lock() {
- Ok(guard) => guard.clone(),
- Err(_) => None,
- };
- let Some(config) = config else {
- return Ok(None);
- };
- if config.path.trim().is_empty() {
- return Ok(None);
- }
- let db = ensu_db::ChatDb::open_sqlite_with_defaults(config.path, config.key)?;
- Ok(Some(db))
- }
-
- fn apply_session_tombstone(
- &self,
- local: Option<Session>,
- local_state: Option<SyncEntityState>,
- session_uuid: Uuid,
- deleted_at: i64,
- ) -> Result<(), SyncError> {
- let Some(local) = local else {
- return Ok(());
- };
-
- let server_updated_at = local_state.and_then(|state| state.server_updated_at);
-
- if local.needs_sync && server_updated_at.is_none() {
- self.db.apply_session_tombstone(session_uuid, deleted_at)?;
- let _ = self.sync_state.delete_session_state(session_uuid);
- return Ok(());
- }
-
- if local.needs_sync && server_updated_at.is_some() && local.updated_at > deleted_at {
- return Ok(());
- }
-
- self.db.apply_session_tombstone(session_uuid, deleted_at)?;
- let _ = self.sync_state.delete_session_state(session_uuid);
- Ok(())
- }
-
- fn push(
- &self,
- http: &HttpClient,
- chat_key: &[u8],
- result: &mut SyncResult,
- ) -> Result<(), SyncError> {
- let deleted_sessions = self.db.get_deleted_sessions()?;
- for (uuid, _deleted_at) in deleted_sessions {
- if let Some(remote_id) = self.sync_state.get_session_remote_id(uuid)? {
- http.delete("/llmchat/chat/session", &[("id", remote_id)])?;
- let _ = self.sync_state.delete_session_state(uuid);
- }
- let _ = self.db.delete_attachment_tracking_for_session(uuid);
- let _ = self.db.hard_delete(EntityType::Session, uuid);
- }
-
- let deleted_messages = self.db.get_deleted_messages()?;
- for (uuid, _deleted_at) in deleted_messages {
- if let Some(remote_id) = self.sync_state.get_message_remote_id(uuid)? {
- http.delete("/llmchat/chat/message", &[("id", remote_id)])?;
- let _ = self.sync_state.delete_message_state(uuid);
- }
- let _ = self.db.delete_attachment_tracking_for_message(uuid);
- let _ = self.db.hard_delete(EntityType::Message, uuid);
- }
-
- let sessions = self.db.list_sessions()?;
- for session in sessions {
- self.push_session_with_messages(http, chat_key, &session, result)?;
- }
-
- Ok(())
- }
-
- fn push_session_with_messages(
- &self,
- http: &HttpClient,
- chat_key: &[u8],
- session: &Session,
- result: &mut SyncResult,
- ) -> Result<(), SyncError> {
- let session_uuid = session.uuid;
- let messages = self.collect_messages_for_sync(session_uuid)?;
- let session_state = self.sync_state.get_session_state(session_uuid)?;
- let should_upsert_session = session.needs_sync
- || session_state
- .as_ref()
- .and_then(|state| state.remote_id.as_deref())
- .is_none();
- let mut session_remote_id = session_state.and_then(|state| state.remote_id);
-
- if !messages.is_empty() {
- 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();
-
- if should_upsert_session {
- session_remote_id = Some(self.push_session(http, chat_key, session)?);
- result.pushed.sessions += 1;
- }
-
- for message in filtered.iter() {
- self.push_message_with_retry(http, chat_key, message, result)?;
- let _ = self.db.mark_message_synced(message.uuid);
- }
-
- if blocked.is_empty()
- && filtered.len() == messages.len()
- && let Some(remote_id) = session_remote_id.clone().or_else(|| {
- self.sync_state
- .get_session_remote_id(session_uuid)
- .ok()
- .flatten()
- })
- {
- let _ = self.db.mark_session_synced(session_uuid, &remote_id);
- }
- } else if should_upsert_session {
- session_remote_id = Some(self.push_session(http, chat_key, session)?);
- result.pushed.sessions += 1;
- if let Some(remote_id) = session_remote_id.clone().or_else(|| {
- self.sync_state
- .get_session_remote_id(session_uuid)
- .ok()
- .flatten()
- }) {
- let _ = self.db.mark_session_synced(session_uuid, &remote_id);
- }
- }
-
- Ok(())
- }
-
- fn push_session(
- &self,
- http: &HttpClient,
- chat_key: &[u8],
- session: &Session,
- ) -> Result<String, SyncError> {
- let session_payload = SessionPayload {
- title: session.title.clone(),
- };
- let encrypted = encrypt_payload(&session_payload, chat_key)?;
- let client_metadata =
- encode_client_metadata(&session.uuid.to_string(), session.created_at, chat_key)?;
- let session_uuid =
- normalize_remote_uuid(self.sync_state.get_session_remote_id(session.uuid)?);
- let session_request = UpsertSessionRequest {
- session_uuid: session_uuid.clone(),
- encrypted_data: encrypted.encrypted_data,
- header: encrypted.header,
- client_metadata: Some(client_metadata),
- };
- let response: UpsertSessionResponse =
- http.post_json("/llmchat/chat/session", &session_request)?;
- let remote_id = response.session_uuid;
- self.sync_state
- .set_session_state(session.uuid, Some(&remote_id), response.updated_at)?;
- Ok(remote_id)
- }
-
- 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.uuid,
- &message.attachments,
- chat_key,
- )?;
-
- let session_remote_id = normalize_remote_uuid(
- self.sync_state
- .get_session_remote_id(message.session_uuid)?,
- )
- .ok_or_else(|| SyncError::InvalidResponse("missing session remote id".to_string()))?;
- let message_uuid =
- normalize_remote_uuid(self.sync_state.get_message_remote_id(message.uuid)?);
- let parent_message_uuid = message.parent_message_uuid.and_then(|parent| {
- normalize_remote_uuid(self.sync_state.get_message_remote_id(parent).ok().flatten())
- });
- let client_metadata =
- encode_client_metadata(&message.uuid.to_string(), message.created_at, chat_key)?;
- let message_request = UpsertMessageRequest {
- message_uuid,
- session_uuid: session_remote_id,
- parent_message_uuid,
- sender: message.sender.as_str().to_string(),
- attachments,
- encrypted_data: encrypted.encrypted_data,
- header: encrypted.header,
- client_metadata: Some(client_metadata),
- };
- let response: UpsertMessageResponse =
- http.post_json("/llmchat/chat/message", &message_request)?;
- self.sync_state.set_message_state(
- message.uuid,
- Some(&response.message_uuid),
- response.updated_at,
- )?;
- 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);
- let _ = self.db.set_attachment_remote_id(&attachment.id, None);
- }
- 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,
- message_uuid: Uuid,
- attachments: &[AttachmentMeta],
- chat_key: &[u8],
- ) -> Result<Vec<RemoteAttachment>, SyncError> {
- attachments
- .iter()
- .map(|attachment| {
- let encrypted_size =
- self.encrypted_attachment_size(&attachment.id, session_uuid, chat_key)?;
- let remote_id = match self.db.get_attachment_remote_id(&attachment.id)? {
- Some(remote_id) => remote_id,
- None => {
- let fallback = attachment.id.clone();
- self.db
- .set_attachment_remote_id(&attachment.id, Some(&fallback))?;
- fallback
- }
- };
- let client_metadata =
- encode_attachment_metadata(attachment, message_uuid, chat_key)?;
- Ok(RemoteAttachment {
- id: remote_id,
- size: encrypted_size,
- client_metadata: Some(client_metadata),
- encrypted_name: None,
- kind: None,
- })
- })
- .collect()
- }
-
- fn decrypt_remote_attachments(
- &self,
- attachments: &[RemoteAttachment],
- chat_key: &[u8],
- ) -> Result<(Vec<AttachmentMeta>, HashMap<String, String>), SyncError> {
- let mut metas = Vec::with_capacity(attachments.len());
- let mut remote_ids = HashMap::new();
- for attachment in attachments {
- let (meta, client_id) = decode_attachment_metadata(attachment, chat_key)?;
- remote_ids.insert(client_id.clone(), attachment.id.clone());
- metas.push(meta);
- }
- Ok((metas, remote_ids))
- }
-
- fn collect_messages_for_sync(&self, session_uuid: Uuid) -> Result<Vec<Message>, SyncError> {
- let messages = self.db.get_messages(session_uuid)?;
- let mut pending = Vec::new();
-
- for message in messages {
- let state = self.sync_state.get_message_state(message.uuid)?;
- let missing_remote = state
- .as_ref()
- .and_then(|entry| entry.remote_id.as_deref())
- .is_none();
- let missing_server_ts = state
- .as_ref()
- .and_then(|entry| entry.server_updated_at)
- .is_none();
- if message.needs_sync || missing_remote || missing_server_ts {
- pending.push(message);
- }
- }
-
- Ok(pending)
- }
-
- 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 remote_id = match self.db.get_attachment_remote_id(&attachment.id)? {
- Some(remote_id) => remote_id,
- None => {
- let fallback = attachment.id.clone();
- self.db
- .set_attachment_remote_id(&attachment.id, Some(&fallback))?;
- fallback
- }
- };
-
- let status =
- match http.head_status(&format!("/llmchat/chat/attachment/{}", remote_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, content_length) =
- self.encrypted_attachment_bytes(attachment_id, session_uuid, chat_key)?;
- let request = UploadUrlRequest {
- content_length,
- content_md5: None,
- };
- let upload_url = http.post_json::<UploadUrlResponse, _>(
- "/llmchat/chat/attachment/upload-url?force=true",
- &request,
- )?;
- self.db
- .set_attachment_remote_id(attachment_id, Some(&upload_url.attachment_id))?;
- 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, content_length) =
- match self.encrypted_attachment_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,
- content_md5: None,
- };
-
- let upload_path = if force_uploads.contains(&row.attachment_id) {
- "/llmchat/chat/attachment/upload-url?force=true".to_string()
- } else {
- "/llmchat/chat/attachment/upload-url".to_string()
- };
-
- 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 {
- self.db.set_attachment_remote_id(
- &row.attachment_id,
- Some(&upload_url.attachment_id),
- )?;
- 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_bytes(
- &self,
- attachment_id: &str,
- session_uuid: Uuid,
- chat_key: &[u8],
- ) -> Result<(Vec<u8>, i64), SyncError> {
- let bytes = self.ensure_encrypted_bytes(attachment_id, session_uuid, chat_key)?;
- let size = bytes.len() as i64;
- Ok((bytes, size))
- }
-
- 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 (_bytes, size) =
- self.encrypted_attachment_bytes(attachment_id, session_uuid, chat_key)?;
- Ok(size)
- }
-
- 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.sync_state.get_meta(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.sync_state.set_meta(CURSOR_META_KEY, &data)?;
- Ok(())
- }
-
- fn load_chat_key_from_meta(&self, master_key: &[u8]) -> Result<Option<Vec<u8>>, SyncError> {
- load_chat_key_from_meta(&self.sync_state, master_key)
- }
-
- fn get_or_create_chat_key(
- &self,
- http: &HttpClient,
- master_key: &[u8],
- ) -> Result<(Vec<u8>, ChatKeyStatus), SyncError> {
- get_or_create_chat_key_with_state(&self.sync_state, http, master_key)
- }
-}
-
-pub fn fetch_chat_key(auth: SyncAuth, sync_db_path: String) -> Result<Vec<u8>, SyncError> {
- if auth.auth_token.trim().is_empty() {
- return Err(SyncError::NotLoggedIn);
- }
- if auth.master_key.len() != ensu_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 sync_state = SyncStateDb::open_sqlite_with_defaults(sync_db_path)?;
- let (chat_key, _) = get_or_create_chat_key_with_state(&sync_state, &http, &master_key)?;
- Ok(chat_key)
-}
-
-fn load_chat_key_from_meta(
- sync_state: &SyncStateDb<SqliteBackend>,
- master_key: &[u8],
-) -> Result<Option<Vec<u8>>, SyncError> {
- let data = match sync_state.get_meta(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(
- sync_state: &SyncStateDb<SqliteBackend>,
- payload: &ChatKeyPayload,
-) -> Result<(), SyncError> {
- let data = serde_json::to_vec(payload)?;
- sync_state.set_meta(CHAT_KEY_META_KEY, &data)?;
- Ok(())
-}
-
-fn get_or_create_chat_key_with_state(
- sync_state: &SyncStateDb<SqliteBackend>,
- http: &HttpClient,
- master_key: &[u8],
-) -> Result<(Vec<u8>, ChatKeyStatus), SyncError> {
- if let Some(key) = load_chat_key_from_meta(sync_state, master_key)? {
- return Ok((key, ChatKeyStatus::Cached));
- }
-
- 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)?;
- save_chat_key_to_meta(sync_state, &payload)?;
- return Ok((key, ChatKeyStatus::Remote));
- }
-
- let chat_key = Key::generate().as_bytes().to_vec();
- let encrypted = encrypt_chat_key(&chat_key, master_key)?;
- let payload = ChatKeyPayload::from_encrypted(&encrypted);
-
- match http.post_empty("/llmchat/chat/key", &payload) {
- Ok(()) => {
- save_chat_key_to_meta(sync_state, &payload)?;
- Ok((chat_key, ChatKeyStatus::Created))
- }
- Err(SyncError::Http { status: 409, .. }) => {
- let existing = http.get_json_optional::<ChatKeyPayload>("/llmchat/chat/key", &[])?;
- let payload = existing
- .ok_or_else(|| SyncError::InvalidResponse("chat key already exists".to_string()))?;
- 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)?;
- save_chat_key_to_meta(sync_state, &payload)?;
- Ok((key, ChatKeyStatus::Remote))
- }
- Err(err) => Err(err),
- }
-}
-
-#[derive(Debug, serde::Serialize, serde::Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct ClientMetadataPayload {
- #[serde(rename = "clientId")]
- client_id: String,
- #[serde(default)]
- created_at: Option<serde_json::Value>,
-}
-
-fn encode_client_metadata(
- client_id: &str,
- created_at: i64,
- chat_key: &[u8],
-) -> Result<String, SyncError> {
- let created_at_value = if created_at > 0 {
- let encrypted = ensu_db::crypto::encrypt_json_field(&created_at.to_string(), chat_key)
- .map_err(|err| SyncError::Crypto(err.to_string()))?;
- Some(serde_json::Value::String(encrypted))
- } else {
- None
- };
-
- let payload = ClientMetadataPayload {
- client_id: client_id.to_string(),
- created_at: created_at_value,
- };
- Ok(serde_json::to_string(&payload)?)
-}
-
-fn decode_client_id(value: &str) -> Option<String> {
- serde_json::from_str::<ClientMetadataPayload>(value)
- .ok()
- .map(|payload| payload.client_id)
- .filter(|client_id| !client_id.trim().is_empty())
-}
-
-fn decode_client_created_at(value: &str, chat_key: &[u8]) -> Option<i64> {
- if let Ok(payload) = serde_json::from_str::<ClientMetadataPayload>(value) {
- let created_at_value = payload.created_at?;
- let parsed = match created_at_value {
- serde_json::Value::Number(number) => number.as_i64(),
- serde_json::Value::String(raw) => {
- let decrypted = ensu_db::crypto::decrypt_json_field(&raw, chat_key).unwrap_or(raw);
- decrypted.parse::<i64>().ok()
- }
- _ => None,
- };
- return parsed.filter(|created_at| *created_at > 0);
- }
-
- let decrypted =
- ensu_db::crypto::decrypt_json_field(value, chat_key).unwrap_or_else(|_| value.to_string());
- decrypted
- .parse::<i64>()
- .ok()
- .filter(|created_at| *created_at > 0)
-}
-
-#[derive(Debug, serde::Serialize, serde::Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct AttachmentClientMetadata {
- #[serde(rename = "clientId")]
- client_id: String,
- #[serde(rename = "localId", default)]
- local_id: Option<String>,
- #[serde(default)]
- encrypted_name: Option<String>,
- #[serde(default)]
- kind: Option<AttachmentKind>,
-}
-
-fn encode_attachment_metadata(
- attachment: &AttachmentMeta,
- message_uuid: Uuid,
- chat_key: &[u8],
-) -> Result<String, SyncError> {
- let encrypted_name = ensu_db::crypto::encrypt_json_field(&attachment.name, chat_key)
- .map_err(|err| SyncError::Crypto(err.to_string()))?;
- let payload = AttachmentClientMetadata {
- client_id: format!("{}:{}", message_uuid, attachment.id),
- local_id: Some(attachment.id.clone()),
- encrypted_name: Some(encrypted_name),
- kind: Some(attachment.kind),
- };
- Ok(serde_json::to_string(&payload)?)
-}
-
-fn decode_attachment_metadata(
- attachment: &RemoteAttachment,
- chat_key: &[u8],
-) -> Result<(AttachmentMeta, String), SyncError> {
- if let Some(metadata) = &attachment.client_metadata {
- let payload = serde_json::from_str::<AttachmentClientMetadata>(metadata).map_err(|_| {
- SyncError::InvalidResponse("invalid attachment clientMetadata".to_string())
- })?;
- let encrypted_name = payload.encrypted_name.ok_or_else(|| {
- SyncError::InvalidResponse("missing attachment encryptedName".to_string())
- })?;
- let name = ensu_db::crypto::decrypt_json_field(&encrypted_name, chat_key)
- .map_err(|err| SyncError::Crypto(err.to_string()))?;
- let kind = payload.kind.unwrap_or_else(|| infer_kind(&name));
- let local_id = payload
- .local_id
- .clone()
- .filter(|value| !value.trim().is_empty())
- .unwrap_or(payload.client_id.clone());
- return Ok((
- AttachmentMeta {
- id: local_id.clone(),
- kind,
- size: attachment.size,
- name,
- },
- local_id,
- ));
- }
-
- let encrypted_name = attachment
- .encrypted_name
- .as_ref()
- .ok_or_else(|| SyncError::InvalidResponse("missing attachment metadata".to_string()))?;
- let name = ensu_db::crypto::decrypt_json_field(encrypted_name, chat_key)
- .map_err(|err| SyncError::Crypto(err.to_string()))?;
- let kind = attachment.kind.unwrap_or_else(|| infer_kind(&name));
- let client_id = attachment.id.clone();
- Ok((
- AttachmentMeta {
- id: client_id.clone(),
- kind,
- size: attachment.size,
- name,
- },
- client_id,
- ))
-}
-
-#[derive(Debug, serde::Serialize)]
-#[serde(rename_all = "camelCase")]
-struct UpsertSessionRequest {
- #[serde(
- rename = "sessionUUID",
- alias = "session_uuid",
- skip_serializing_if = "Option::is_none"
- )]
- session_uuid: Option<String>,
- #[serde(rename = "encryptedData", alias = "encrypted_data")]
- encrypted_data: String,
- header: String,
- #[serde(
- rename = "clientMetadata",
- alias = "client_metadata",
- skip_serializing_if = "Option::is_none"
- )]
- client_metadata: Option<String>,
-}
-
-#[derive(Debug, serde::Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct UpsertSessionResponse {
- #[serde(rename = "sessionUUID", alias = "session_uuid")]
- session_uuid: String,
- #[serde(alias = "updated_at")]
- updated_at: Option<i64>,
-}
-
-#[derive(Debug, serde::Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct UpsertMessageResponse {
- #[serde(rename = "messageUUID", alias = "message_uuid")]
- message_uuid: String,
- #[serde(alias = "updated_at")]
- updated_at: Option<i64>,
-}
-
-#[derive(Debug, serde::Serialize)]
-#[serde(rename_all = "camelCase")]
-struct UpsertMessageRequest {
- #[serde(
- rename = "messageUUID",
- alias = "message_uuid",
- skip_serializing_if = "Option::is_none"
- )]
- message_uuid: Option<String>,
- #[serde(rename = "sessionUUID", alias = "session_uuid")]
- session_uuid: String,
- #[serde(rename = "parentMessageUUID", alias = "parent_message_uuid")]
- parent_message_uuid: Option<String>,
- sender: String,
- attachments: Vec<RemoteAttachment>,
- #[serde(rename = "encryptedData", alias = "encrypted_data")]
- encrypted_data: String,
- header: String,
- #[serde(
- rename = "clientMetadata",
- alias = "client_metadata",
- skip_serializing_if = "Option::is_none"
- )]
- client_metadata: Option<String>,
-}
-
-fn normalize_remote_uuid(value: Option<String>) -> Option<String> {
- value.and_then(|value| {
- let trimmed = value.trim();
- if trimmed.is_empty() || trimmed == ZERO_UUID {
- None
- } else {
- Some(trimmed.to_string())
- }
- })
-}
-
-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
- }
-}
diff --git a/rust/crates/ensu/sync/tests/sync_integration.rs b/rust/crates/ensu/sync/tests/sync_integration.rs
deleted file mode 100644
index 19ff191f83..0000000000
--- a/rust/crates/ensu/sync/tests/sync_integration.rs
+++ /dev/null
@@ -1,334 +0,0 @@
-use ensu_db::EnsuDb;
-use ensu_db::SyncStateDb;
-use ensu_db::crypto::KEY_BYTES;
-use ensu_sync::SyncAuth;
-use ensu_sync::SyncEngine;
-use ensu_sync::crypto::{encrypt_chat_key, encrypt_payload};
-use ensu_sync::models::{
- ChatKeyPayload, DiffResponse, DiffTombstones, MessagePayload, MessageTombstone, RemoteMessage,
- RemoteSession, SessionPayload,
-};
-use httpmock::Method::{DELETE, GET, POST};
-use httpmock::MockServer;
-use std::sync::{Mutex, MutexGuard, OnceLock};
-use tempfile::TempDir;
-use uuid::Uuid;
-use zeroize::Zeroizing;
-
-struct TestEnv {
- _dir: TempDir,
- main_db_path: String,
- attachments_db_path: String,
- attachments_dir: String,
- meta_dir: String,
- plaintext_dir: Option<String>,
-}
-
-impl TestEnv {
- fn new() -> Self {
- let dir = TempDir::new().expect("temp dir");
- let main_db_path = dir.path().join("main.db");
- let attachments_db_path = dir.path().join("attachments.db");
- let attachments_dir = dir.path().join("attachments");
- let meta_dir = dir.path().join("meta");
- Self {
- _dir: dir,
- main_db_path: main_db_path.to_string_lossy().to_string(),
- attachments_db_path: attachments_db_path.to_string_lossy().to_string(),
- attachments_dir: attachments_dir.to_string_lossy().to_string(),
- meta_dir: meta_dir.to_string_lossy().to_string(),
- plaintext_dir: None,
- }
- }
-}
-
-fn sync_test_lock() -> MutexGuard<'static, ()> {
- static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
- LOCK.get_or_init(|| Mutex::new(()))
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
-}
-
-fn make_auth(server: &MockServer, master_key: Vec<u8>) -> SyncAuth {
- SyncAuth {
- base_url: server.base_url(),
- auth_token: "token".to_string(),
- master_key: Zeroizing::new(master_key),
- user_agent: None,
- client_package: None,
- client_version: None,
- }
-}
-
-fn mock_chat_key(server: &MockServer, master_key: &[u8], chat_key: &[u8]) {
- let encrypted = encrypt_chat_key(chat_key, master_key).expect("encrypt chat key");
- let payload = ChatKeyPayload::from_encrypted(&encrypted);
- server.mock(|when, then| {
- when.method(GET).path("/llmchat/chat/key");
- then.status(200).json_body_obj(&payload);
- });
-}
-
-fn mock_empty_diff(server: &MockServer, timestamp: i64) {
- let diff = DiffResponse {
- sessions: Vec::new(),
- messages: Vec::new(),
- tombstones: DiffTombstones::default(),
- cursor: None,
- timestamp: Some(timestamp),
- };
- server.mock(|when, then| {
- when.method(GET).path("/llmchat/chat/diff");
- then.status(200).json_body_obj(&diff);
- });
-}
-
-#[test]
-fn pull_applies_remote_sessions_and_messages() {
- let _guard = sync_test_lock();
- let env = TestEnv::new();
- let db_key = vec![42u8; KEY_BYTES];
- let engine = SyncEngine::new(
- env.main_db_path.clone(),
- env.attachments_db_path.clone(),
- db_key.clone(),
- env.attachments_dir.clone(),
- env.meta_dir.clone(),
- env.plaintext_dir.clone(),
- )
- .expect("sync engine");
-
- let master_key = vec![9u8; KEY_BYTES];
- let chat_key = ente_core::crypto::Key::generate().as_bytes().to_vec();
-
- let server = MockServer::start();
- mock_chat_key(&server, &master_key, &chat_key);
-
- let session_uuid = Uuid::new_v4();
- let message_uuid = Uuid::new_v4();
-
- let session_payload = SessionPayload {
- title: "Remote Session".to_string(),
- };
- let encrypted_session = encrypt_payload(&session_payload, &chat_key).expect("encrypt session");
-
- let message_payload = MessagePayload {
- text: "hello".to_string(),
- };
- let encrypted_message = encrypt_payload(&message_payload, &chat_key).expect("encrypt message");
-
- let diff = DiffResponse {
- sessions: vec![RemoteSession {
- session_uuid: session_uuid.to_string(),
- encrypted_data: encrypted_session.encrypted_data,
- header: encrypted_session.header,
- client_metadata: None,
- created_at: 10,
- updated_at: 11,
- is_deleted: None,
- }],
- messages: vec![RemoteMessage {
- message_uuid: message_uuid.to_string(),
- session_uuid: session_uuid.to_string(),
- parent_message_uuid: None,
- sender: "self".to_string(),
- attachments: Vec::new(),
- encrypted_data: encrypted_message.encrypted_data,
- header: encrypted_message.header,
- client_metadata: None,
- created_at: 12,
- updated_at: None,
- is_deleted: None,
- }],
- tombstones: DiffTombstones::default(),
- cursor: None,
- timestamp: Some(12),
- };
-
- server.mock(|when, then| {
- when.method(GET).path("/llmchat/chat/diff");
- then.status(200).json_body_obj(&diff);
- });
-
- let auth = make_auth(&server, master_key);
- engine.sync(auth).expect("sync");
-
- let db = EnsuDb::open_sqlite_with_defaults(
- env.main_db_path.clone(),
- env.attachments_db_path.clone(),
- db_key,
- )
- .expect("db");
-
- let sessions = db.list_sessions().expect("sessions");
- assert_eq!(sessions.len(), 1);
- assert_eq!(sessions[0].uuid, session_uuid);
- assert_eq!(sessions[0].title, "Remote Session");
-
- let messages = db.get_messages(session_uuid).expect("messages");
- assert_eq!(messages.len(), 1);
- assert_eq!(messages[0].uuid, message_uuid);
- assert_eq!(messages[0].text, "hello");
- assert!(!messages[0].needs_sync);
-}
-
-#[test]
-fn push_only_needs_sync_messages() {
- let _guard = sync_test_lock();
- let env = TestEnv::new();
- let db_key = vec![11u8; KEY_BYTES];
- let engine = SyncEngine::new(
- env.main_db_path.clone(),
- env.attachments_db_path.clone(),
- db_key.clone(),
- env.attachments_dir.clone(),
- env.meta_dir.clone(),
- env.plaintext_dir.clone(),
- )
- .expect("sync engine");
-
- let db = EnsuDb::open_sqlite_with_defaults(
- env.main_db_path.clone(),
- env.attachments_db_path.clone(),
- db_key.clone(),
- )
- .expect("db");
-
- let session = db.create_session("Local Session").expect("session");
- let message_one = db
- .insert_message(session.uuid, "self", "one", None, Vec::new())
- .expect("message one");
- let _message_two = db
- .insert_message(session.uuid, "self", "two", None, Vec::new())
- .expect("message two");
- db.mark_message_synced(message_one.uuid)
- .expect("mark synced");
- let sync_state = SyncStateDb::open_sqlite_with_defaults(env.attachments_db_path.clone())
- .expect("sync state");
- sync_state
- .set_message_state(message_one.uuid, Some("remote-message-one"), Some(9))
- .expect("message sync state");
-
- let master_key = vec![7u8; KEY_BYTES];
- let chat_key = ente_core::crypto::Key::generate().as_bytes().to_vec();
- let server = MockServer::start();
- mock_chat_key(&server, &master_key, &chat_key);
- mock_empty_diff(&server, 10);
-
- let session_mock = server.mock(|when, then| {
- when.method(POST).path("/llmchat/chat/session");
- then.status(200).json_body_obj(&serde_json::json!({
- "sessionUUID": Uuid::new_v4().to_string(),
- "updatedAt": 20,
- }));
- });
-
- let message_mock = server.mock(|when, then| {
- when.method(POST).path("/llmchat/chat/message");
- then.status(200).json_body_obj(&serde_json::json!({
- "messageUUID": Uuid::new_v4().to_string(),
- "updatedAt": 21,
- }));
- });
-
- let auth = make_auth(&server, master_key);
- engine.sync(auth).expect("sync");
-
- assert_eq!(session_mock.hits(), 1);
- assert_eq!(message_mock.hits(), 1);
-
- let messages = db.get_messages(session.uuid).expect("messages");
- assert!(messages.iter().all(|message| !message.needs_sync));
-}
-
-#[test]
-fn tombstone_removes_messages() {
- let _guard = sync_test_lock();
- let env = TestEnv::new();
- let db_key = vec![3u8; KEY_BYTES];
- let engine = SyncEngine::new(
- env.main_db_path.clone(),
- env.attachments_db_path.clone(),
- db_key.clone(),
- env.attachments_dir.clone(),
- env.meta_dir.clone(),
- env.plaintext_dir.clone(),
- )
- .expect("sync engine");
-
- let master_key = vec![12u8; KEY_BYTES];
- let chat_key = ente_core::crypto::Key::generate().as_bytes().to_vec();
-
- let server = MockServer::start();
- mock_chat_key(&server, &master_key, &chat_key);
-
- let session_uuid = Uuid::new_v4();
- let message_uuid = Uuid::new_v4();
-
- let session_payload = SessionPayload {
- title: "Remote Session".to_string(),
- };
- let encrypted_session = encrypt_payload(&session_payload, &chat_key).expect("encrypt session");
-
- let message_payload = MessagePayload {
- text: "to delete".to_string(),
- };
- let encrypted_message = encrypt_payload(&message_payload, &chat_key).expect("encrypt message");
-
- let diff = DiffResponse {
- sessions: vec![RemoteSession {
- session_uuid: session_uuid.to_string(),
- encrypted_data: encrypted_session.encrypted_data,
- header: encrypted_session.header,
- client_metadata: None,
- created_at: 10,
- updated_at: 11,
- is_deleted: None,
- }],
- messages: vec![RemoteMessage {
- message_uuid: message_uuid.to_string(),
- session_uuid: session_uuid.to_string(),
- parent_message_uuid: None,
- sender: "self".to_string(),
- attachments: Vec::new(),
- encrypted_data: encrypted_message.encrypted_data,
- header: encrypted_message.header,
- client_metadata: None,
- created_at: 12,
- updated_at: None,
- is_deleted: None,
- }],
- tombstones: DiffTombstones {
- sessions: Vec::new(),
- messages: vec![MessageTombstone {
- message_uuid: message_uuid.to_string(),
- deleted_at: Some(15),
- }],
- },
- cursor: None,
- timestamp: Some(15),
- };
-
- server.mock(|when, then| {
- when.method(GET).path("/llmchat/chat/diff");
- then.status(200).json_body_obj(&diff);
- });
-
- server.mock(|when, then| {
- when.method(DELETE).path("/llmchat/chat/message");
- then.status(200).json_body_obj(&serde_json::json!({}));
- });
-
- let auth = make_auth(&server, master_key);
- engine.sync(auth).expect("sync");
-
- let db = EnsuDb::open_sqlite_with_defaults(
- env.main_db_path.clone(),
- env.attachments_db_path.clone(),
- db_key,
- )
- .expect("db");
-
- let messages = db.get_messages(session_uuid).expect("messages");
- assert!(messages.is_empty());
-}
diff --git a/web/apps/ensu/src/components/chat/ChatDialogs.tsx b/web/apps/ensu/src/components/chat/ChatDialogs.tsx
index 8c6aec460d..d8bc8e936c 100644
--- a/web/apps/ensu/src/components/chat/ChatDialogs.tsx
+++ b/web/apps/ensu/src/components/chat/ChatDialogs.tsx
@@ -110,9 +110,9 @@ export interface ChatDialogsProps {
systemPrompt: string;
handleSaveSystemPrompt: (promptText: string) => void;
handleUseDefaultSystemPrompt: () => void;
- syncNotificationOpen: boolean;
- setSyncNotificationOpen: React.Dispatch<React.SetStateAction<boolean>>;
- syncNotification?: NotificationAttributes;
+ chatNotificationOpen: boolean;
+ setChatNotificationOpen: React.Dispatch<React.SetStateAction<boolean>>;
+ chatNotification?: NotificationAttributes;
modelGateStatus: ModelGateStatus;
imagePreview: { url: string; name: string } | null;
closeImagePreview: () => void;
@@ -167,9 +167,9 @@ export const ChatDialogs = memo(
systemPrompt,
handleSaveSystemPrompt,
handleUseDefaultSystemPrompt,
- syncNotificationOpen,
- setSyncNotificationOpen,
- syncNotification,
+ chatNotificationOpen,
+ setChatNotificationOpen,
+ chatNotification,
modelGateStatus,
imagePreview,
closeImagePreview,
@@ -1090,9 +1090,9 @@ export const ChatDialogs = memo(
</Dialog>
<Notification
- open={syncNotificationOpen}
- onClose={() => setSyncNotificationOpen(false)}
- attributes={syncNotification}
+ open={chatNotificationOpen}
+ onClose={() => setChatNotificationOpen(false)}
+ attributes={chatNotification}
horizontal={isSmall ? "left" : "right"}
vertical="bottom"
sx={{
diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsx
index 11b2c24cd6..7dd49b46b9 100644
--- a/web/apps/ensu/src/pages/chat.tsx
+++ b/web/apps/ensu/src/pages/chat.tsx
@@ -34,11 +34,6 @@ import {
type ChatMessage,
type ChatSession,
} from "@/services/chat/store";
-import {
- ChatSyncLimitError,
- downloadAttachment,
- syncChat,
-} from "@/services/chat/sync";
import {
DESKTOP_IMAGE_ATTACHMENTS_ENABLED,
SIGN_IN_ENABLED,
@@ -635,10 +630,10 @@ const Page: React.FC = () => {
const [pendingImages, setPendingImages] = useState<ImageAttachment[]>([]);
const [attachmentAnchor, setAttachmentAnchor] =
useState<HTMLElement | null>(null);
- const [syncNotification, setSyncNotification] = useState<
+ const [chatNotification, setChatNotification] = useState<
NotificationAttributes | undefined
>(undefined);
- const [syncNotificationOpen, setSyncNotificationOpen] = useState(false);
+ const [chatNotificationOpen, setChatNotificationOpen] = useState(false);
const [isGenerating, setIsGenerating] = useState(false);
const [isStreamingOutro, setIsStreamingOutro] = useState(false);
const [loadingPhrase, setLoadingPhrase] = useState<string | null>(null);
@@ -824,7 +819,7 @@ const Page: React.FC = () => {
} catch (error) {
log.error("Failed to load remote chat key", error);
showMiniDialog({
- title: "Sync unavailable",
+ title: "Chat key unavailable",
message:
"We could not load your chat encryption key. Please try again.",
});
@@ -1411,123 +1406,38 @@ const Page: React.FC = () => {
attributes: NotificationAttributes & { autoHideDuration?: number },
) => {
const { autoHideDuration, ...rest } = attributes;
- setSyncNotification(rest);
- setSyncNotificationOpen(true);
+ setChatNotification(rest);
+ setChatNotificationOpen(true);
if (toastTimeoutRef.current) {
window.clearTimeout(toastTimeoutRef.current);
toastTimeoutRef.current = null;
}
if (autoHideDuration && typeof window !== "undefined") {
toastTimeoutRef.current = window.setTimeout(() => {
- setSyncNotificationOpen(false);
+ setChatNotificationOpen(false);
}, autoHideDuration);
}
},
- [setSyncNotification, setSyncNotificationOpen],
- );
-
- const syncNow = useCallback(
- async ({
- showToast: shouldShowToast = false,
- }: { showToast?: boolean } = {}) => {
- if (!chatKey) return;
- let activeChatKey = chatKey;
- let remoteKey = cachedChatKey();
- let canSync =
- isLoggedIn && !!remoteKey && remoteKey === activeChatKey;
-
- if (!canSync && isLoggedIn) {
- await refreshAuthState();
- remoteKey = cachedChatKey();
- if (remoteKey) {
- activeChatKey = remoteKey;
- if (remoteKey !== chatKey) {
- setChatKey(remoteKey);
- }
- canSync = true;
- }
- }
-
- if (canSync) {
- try {
- await syncChat(activeChatKey);
- if (shouldShowToast) {
- showToast({
- title: "Sync complete",
- caption: "Your chats are up to date.",
- color: "accent",
- autoHideDuration: 3000,
- });
- }
- } catch (error) {
- log.error("Chat sync failed", error);
- if (shouldShowToast) {
- showToast({
- title: "Sync failed",
- caption:
- error instanceof ChatSyncLimitError
- ? error.message
- : "We could not sync right now.",
- color: "critical",
- autoHideDuration: 4000,
- });
- }
- if (error instanceof ChatSyncLimitError) {
- showMiniDialog({
- title: "Sync limit reached",
- message: error.message,
- });
- }
- }
- } else if (shouldShowToast) {
- showToast({
- title: "Sync unavailable",
- caption: "Encryption is still initializing.",
- color: "critical",
- autoHideDuration: 3000,
- });
- }
-
- await refreshSessions();
- await refreshMessages();
- },
- [
- chatKey,
- isLoggedIn,
- refreshAuthState,
- refreshMessages,
- refreshSessions,
- showMiniDialog,
- showToast,
- ],
+ [setChatNotification, setChatNotificationOpen],
);
- useEffect(() => {
- if (typeof window === "undefined") return;
- if (!chatKey || !isLoggedIn) return;
- const intervalId = window.setInterval(() => {
- void syncNow();
- }, 60_000);
- return () => {
- window.clearInterval(intervalId);
- };
- }, [chatKey, isLoggedIn, syncNow]);
-
useEffect(() => {
if (typeof window === "undefined") return;
const handleFocus = () => {
void refreshAuthState();
- if (chatKey && isLoggedIn) {
- void syncNow();
+ if (chatKey) {
+ void refreshSessions();
+ void refreshMessages();
}
};
const handleVisibility = () => {
if (!document.hidden) {
void refreshAuthState();
- if (chatKey && isLoggedIn) {
- void syncNow();
+ if (chatKey) {
+ void refreshSessions();
+ void refreshMessages();
}
}
};
@@ -1539,7 +1449,7 @@ const Page: React.FC = () => {
window.removeEventListener("focus", handleFocus);
document.removeEventListener("visibilitychange", handleVisibility);
};
- }, [chatKey, isLoggedIn, refreshAuthState, syncNow]);
+ }, [chatKey, refreshAuthState, refreshMessages, refreshSessions]);
const deleteSessionTarget = useMemo(
() =>
@@ -1561,12 +1471,8 @@ const Page: React.FC = () => {
useEffect(() => {
if (!chatKey || !isChatStoreBridgeReady) return;
- if (isLoggedIn) {
- void syncNow();
- return;
- }
void refreshSessions();
- }, [chatKey, isChatStoreBridgeReady, isLoggedIn, refreshSessions, syncNow]);
+ }, [chatKey, isChatStoreBridgeReady, refreshSessions]);
useEffect(() => {
currentSessionIdRef.current = currentSessionId;
@@ -1640,7 +1546,6 @@ const Page: React.FC = () => {
const task = (async () => {
try {
- await downloadAttachment(attachment.id);
const bytes = await readDecryptedAttachmentBytes(
attachment.id,
chatKey,
@@ -2539,7 +2444,6 @@ const Page: React.FC = () => {
await deleteSession(sessionId, chatKey);
removeSessionFromState(sessionId);
- void syncChat(chatKey);
},
[chatKey, removeSessionFromState],
);
@@ -2587,7 +2491,6 @@ const Page: React.FC = () => {
try {
const images = await Promise.all(
imageAttachments.map(async (attachment) => {
- await downloadAttachment(attachment.id);
const bytes = await readDecryptedAttachmentBytes(
attachment.id,
chatKey,
@@ -2662,7 +2565,6 @@ const Page: React.FC = () => {
if (!chatKey) return;
try {
- await downloadAttachment(attachment.id);
const bytes = await readDecryptedAttachmentBytes(
attachment.id,
chatKey,
@@ -2809,7 +2711,6 @@ const Page: React.FC = () => {
);
appendMessageToState(assistantMessage);
updateSessionAfterMessage(assistantMessage);
- void syncChat(chatKey);
void maybeGenerateSessionTitle({
sessionUuid: activeSessionId,
assistantMessageUuid: assistantMessage.messageUuid,
@@ -3090,7 +2991,6 @@ const Page: React.FC = () => {
appendMessageToState(assistantMessage);
updateSessionAfterMessage(assistantMessage);
- void syncChat(chatKey);
void maybeGenerateSessionTitle({
sessionUuid: activeSessionId,
assistantMessageUuid: assistantMessage.messageUuid,
@@ -4089,8 +3989,6 @@ const Page: React.FC = () => {
setPendingDocuments([]);
setPendingImages([]);
- void syncChat(chatKey);
-
await startGeneration({
promptText,
parentMessageUuid: newUserMessage.messageUuid,
@@ -4125,8 +4023,6 @@ const Page: React.FC = () => {
setPendingDocuments([]);
setPendingImages([]);
- void syncChat(chatKey);
-
await startGeneration({
promptText,
parentMessageUuid: userMessage.messageUuid,
@@ -4524,9 +4420,9 @@ const Page: React.FC = () => {
systemPrompt={systemPrompt}
handleSaveSystemPrompt={handleSaveSystemPrompt}
handleUseDefaultSystemPrompt={handleUseDefaultSystemPrompt}
- syncNotificationOpen={syncNotificationOpen}
- setSyncNotificationOpen={setSyncNotificationOpen}
- syncNotification={syncNotification}
+ chatNotificationOpen={chatNotificationOpen}
+ setChatNotificationOpen={setChatNotificationOpen}
+ chatNotification={chatNotification}
modelGateStatus={modelGateStatus}
imagePreview={imagePreview}
closeImagePreview={closeImagePreview}
diff --git a/web/apps/ensu/src/services/chat/store.ts b/web/apps/ensu/src/services/chat/store.ts
index 3cab9142b1..a3d2e2b323 100644
--- a/web/apps/ensu/src/services/chat/store.ts
+++ b/web/apps/ensu/src/services/chat/store.ts
@@ -123,7 +123,6 @@ interface ChatDbLike {
name: K,
value: ChatDbSchema[K],
) => Promise<void>;
- delete: (name: ChatStoreName, key: string) => Promise<void>;
transaction: (names: ChatStoreName[], mode: "readwrite") => ChatTransaction;
close: () => void;
}
@@ -149,34 +148,6 @@ export interface ChatMessage {
isSynthetic?: boolean;
}
-export interface LocalSessionRecord {
- sessionUuid: string;
- title: string;
- createdAt: number;
- updatedAt: number;
- remoteId?: string | null;
- needsSync: boolean;
- deletedAt?: number | null;
-}
-
-export interface LocalMessageRecord {
- messageUuid: string;
- sessionUuid: string;
- parentMessageUuid?: string | null;
- sender: "self" | "assistant";
- text: string;
- createdAt: number;
- attachments?: ChatAttachment[];
- remoteId?: string | null;
- deletedAt?: number | null;
-}
-
-export type SyncDeletion = {
- type: "session" | "message";
- uuid: string;
- remoteId?: string | null;
-};
-
interface NativeSession {
sessionUuid: string;
title: string;
@@ -395,9 +366,6 @@ const createIndexedDbChatDb = (
put: async (name, value) => {
await db.put(name, cloneStoreEntry(name, value));
},
- delete: async (name, key) => {
- await db.delete(name, key);
- },
transaction: (names, mode) => {
const tx = db.transaction(names, mode);
return {
@@ -1549,549 +1517,3 @@ export const attachmentBytesExists = async (id: string): Promise<boolean> => {
const entry = await db.get("attachmentBytes", id);
return !!entry;
};
-
-export const deleteAttachmentBytes = async (id: string) => {
- if (isTauriRuntime()) {
- const { remove } = await import("@tauri-apps/plugin-fs");
- const path = await attachmentPath(id);
- try {
- await remove(path);
- } catch {
- // ignore missing files
- }
- return;
- }
-
- const db = await chatDb();
- await db.delete("attachmentBytes", id);
-};
-
-export const getSessionRecord = async (
- sessionUuid: string,
- chatKey: string,
-): Promise<LocalSessionRecord | null> => {
- if (isTauriRuntime()) {
- return withNativeDbRecovery("loading session", async () => {
- const session = await invokeChat<NativeSession | null>(
- "chat_db_get_session",
- { keyB64: chatKey, sessionUuid },
- );
- if (!session) return null;
- return {
- sessionUuid: session.sessionUuid,
- title: session.title,
- createdAt: session.createdAt,
- updatedAt: session.updatedAt,
- remoteId: session.remoteId ?? null,
- needsSync: session.needsSync ?? false,
- deletedAt: session.deletedAt ?? null,
- };
- });
- }
-
- const db = await chatDb();
- const session = await db.get("sessions", sessionUuid);
- if (!session) return null;
-
- return {
- sessionUuid: session.sessionUuid,
- title: await decryptSessionTitle(session, chatKey),
- createdAt: session.createdAt,
- updatedAt: session.updatedAt,
- remoteId: session.remoteId ?? null,
- needsSync: session.needsSync ?? false,
- deletedAt: session.deletedAt ?? null,
- };
-};
-
-export const listSessionRemoteMap = async (): Promise<Map<string, string>> => {
- if (isTauriRuntime()) {
- return new Map();
- }
- const db = await chatDb();
- const sessions = await db.getAll("sessions");
- const map = new Map<string, string>();
- for (const session of sessions) {
- if (session.remoteId) {
- map.set(session.remoteId, session.sessionUuid);
- }
- }
- return map;
-};
-
-export const listMessageRemoteMap = async (): Promise<Map<string, string>> => {
- if (isTauriRuntime()) {
- return new Map();
- }
- const db = await chatDb();
- const messages = await db.getAll("messages");
- const map = new Map<string, string>();
- for (const message of messages) {
- if (message.remoteId) {
- map.set(message.remoteId, message.messageUuid);
- }
- }
- return map;
-};
-
-export const listSessionsForSync = async (
- chatKey: string,
-): Promise<LocalSessionRecord[]> => {
- if (isTauriRuntime()) {
- return withNativeDbRecovery("listing sessions for sync", async () => {
- const sessions = await invokeChat<NativeSession[]>(
- "chat_db_list_sessions_for_sync",
- { keyB64: chatKey },
- );
- return sessions
- .filter((session) => !session.deletedAt)
- .map((session) => ({
- sessionUuid: session.sessionUuid,
- title: session.title,
- createdAt: session.createdAt,
- updatedAt: session.updatedAt,
- remoteId: session.remoteId ?? null,
- needsSync: session.needsSync ?? false,
- deletedAt: session.deletedAt ?? null,
- }));
- });
- }
-
- const db = await chatDb();
- const sessions = await db.getAll("sessions");
- const active = sessions.filter(
- (session) => session.needsSync && !session.deletedAt,
- );
-
- return Promise.all(
- active.map(async (session) => ({
- sessionUuid: session.sessionUuid,
- title: await decryptSessionTitle(session, chatKey),
- createdAt: session.createdAt,
- updatedAt: session.updatedAt,
- remoteId: session.remoteId ?? null,
- needsSync: session.needsSync ?? false,
- deletedAt: session.deletedAt ?? null,
- })),
- );
-};
-
-export const listMessagesForSessionSync = async (
- sessionUuid: string,
- chatKey: string,
- options: { includeDeleted?: boolean } = {},
-): Promise<LocalMessageRecord[]> => {
- const includeDeleted = options.includeDeleted ?? false;
-
- if (isTauriRuntime()) {
- return withNativeDbRecovery("listing messages for sync", async () => {
- const messages = await invokeChat<NativeMessage[]>(
- "chat_db_get_messages_for_sync",
- { keyB64: chatKey, sessionUuid, includeDeleted },
- );
- return messages
- .filter((message) => includeDeleted || !message.deletedAt)
- .map((message) => ({
- messageUuid: message.messageUuid,
- sessionUuid: message.sessionUuid,
- parentMessageUuid: message.parentMessageUuid ?? null,
- sender: message.sender,
- text: message.text,
- createdAt: message.createdAt,
- deletedAt: message.deletedAt ?? null,
- attachments: message.attachments?.map((attachment) => ({
- id: attachment.id,
- kind: attachment.kind,
- name: attachment.name,
- size: attachment.size,
- uploadedAt: attachment.uploadedAt ?? undefined,
- })),
- remoteId: message.remoteId ?? null,
- }));
- });
- }
-
- const db = await chatDb();
- const messages = await db.getAll("messages");
- const scoped = messages
- .filter((message) => message.sessionUuid === sessionUuid)
- .filter((message) => includeDeleted || !message.deletedAt);
-
- return Promise.all(
- scoped.map(async (message) => ({
- messageUuid: message.messageUuid,
- sessionUuid: message.sessionUuid,
- parentMessageUuid: message.parentMessageUuid ?? null,
- sender: message.sender,
- text: await decryptMessageText(message, chatKey),
- createdAt: message.createdAt,
- deletedAt: message.deletedAt ?? null,
- attachments: await deserializeAttachments(
- message.attachments,
- chatKey,
- ),
- remoteId: message.remoteId ?? null,
- })),
- );
-};
-
-export const upsertSessionRecord = async (
- input: LocalSessionRecord,
- chatKey: string,
-) => {
- if (isTauriRuntime()) {
- await invokeChat("chat_db_upsert_session", {
- keyB64: chatKey,
- input: {
- sessionUuid: input.sessionUuid,
- title: input.title,
- createdAt: input.createdAt,
- updatedAt: input.updatedAt,
- remoteId: input.remoteId ?? null,
- needsSync: input.needsSync,
- deletedAt: input.deletedAt ?? null,
- },
- });
- return;
- }
-
- const db = await chatDb();
- const encrypted = await encryptChatPayload({ title: input.title }, chatKey);
-
- const session: StoredSession = {
- sessionUuid: input.sessionUuid,
- createdAt: input.createdAt,
- updatedAt: input.updatedAt,
- encryptedData: encrypted.encryptedData,
- header: encrypted.header,
- remoteId: input.remoteId ?? null,
- needsSync: input.needsSync,
- deletedAt: input.deletedAt ?? null,
- };
-
- await db.put("sessions", session);
-};
-
-export const insertMessageFromRemote = async (
- input: LocalMessageRecord,
- chatKey: string,
-) => {
- if (isTauriRuntime()) {
- await invokeChat("chat_db_insert_message_with_uuid", {
- keyB64: chatKey,
- input: {
- messageUuid: input.messageUuid,
- sessionUuid: input.sessionUuid,
- parentMessageUuid: input.parentMessageUuid ?? null,
- sender: input.sender,
- text: input.text,
- createdAt: input.createdAt,
- remoteId: input.remoteId ?? null,
- deletedAt: input.deletedAt ?? null,
- attachments: input.attachments?.map((attachment) => ({
- id: attachment.id,
- kind: attachment.kind,
- name: attachment.name,
- size: attachment.size,
- uploadedAt: attachment.uploadedAt ?? null,
- })),
- },
- });
- return;
- }
-
- const db = await chatDb();
- const existing = await db.get("messages", input.messageUuid);
- if (existing) return;
-
- const encrypted = await encryptChatPayload({ text: input.text }, chatKey);
- const storedAttachments = await serializeAttachments(
- input.attachments ?? [],
- chatKey,
- );
-
- const message: StoredMessage = {
- messageUuid: input.messageUuid,
- sessionUuid: input.sessionUuid,
- parentMessageUuid: input.parentMessageUuid ?? undefined,
- sender: input.sender,
- createdAt: input.createdAt,
- encryptedData: encrypted.encryptedData,
- header: encrypted.header,
- attachments: storedAttachments,
- remoteId: input.remoteId ?? null,
- deletedAt: input.deletedAt ?? null,
- };
-
- await db.put("messages", message);
-};
-
-export const markSessionSynced = async (
- sessionUuid: string,
- remoteId: string,
- chatKey: string,
-) => {
- if (isTauriRuntime()) {
- await invokeChat("chat_db_mark_session_synced", {
- keyB64: chatKey,
- sessionUuid,
- remoteId,
- });
- return;
- }
-
- const db = await chatDb();
- const session = await db.get("sessions", sessionUuid);
- if (!session) return;
- session.remoteId = remoteId;
- session.needsSync = false;
- await db.put("sessions", session);
-};
-
-export const markMessageSynced = async (
- messageUuid: string,
- remoteId: string,
-) => {
- if (isTauriRuntime()) {
- return;
- }
-
- const db = await chatDb();
- const message = await db.get("messages", messageUuid);
- if (!message) return;
- message.remoteId = remoteId;
- await db.put("messages", message);
-};
-
-export const markSessionDeletedAt = async (
- sessionUuid: string,
- deletedAt: number,
- chatKey: string,
-) => {
- if (isTauriRuntime()) {
- await invokeChat("chat_db_mark_session_deleted", {
- keyB64: chatKey,
- sessionUuid,
- deletedAt,
- });
- await deleteBranchSelections(sessionUuid);
- return;
- }
-
- const db = await chatDb();
- const tx = db.transaction(["sessions", "messages"], "readwrite");
- const sessionStore = tx.objectStore("sessions");
- const session = await sessionStore.get(sessionUuid);
- if (session) {
- session.deletedAt = deletedAt;
- session.needsSync = false;
- await sessionStore.put(session);
- }
-
- const messageStore = tx.objectStore("messages");
- const messages = await messageStore.getAll();
- await Promise.all(
- messages
- .filter((message) => message.sessionUuid === sessionUuid)
- .map((message) => {
- message.deletedAt = deletedAt;
- return messageStore.put(message);
- }),
- );
-
- await tx.done;
- await deleteBranchSelections(sessionUuid);
-};
-
-export const markMessageDeletedAt = async (
- messageUuid: string,
- deletedAt: number,
- chatKey: string,
-) => {
- if (isTauriRuntime()) {
- await invokeChat("chat_db_mark_message_deleted", {
- keyB64: chatKey,
- messageUuid,
- deletedAt,
- });
- return;
- }
-
- const db = await chatDb();
- const message = await db.get("messages", messageUuid);
- if (!message) return;
- message.deletedAt = deletedAt;
- await db.put("messages", message);
-};
-
-export const markAttachmentUploaded = async (
- messageUuid: string,
- attachmentId: string,
- chatKey: string,
-) => {
- if (isTauriRuntime()) {
- await invokeChat("chat_db_mark_attachment_uploaded", {
- keyB64: chatKey,
- messageUuid,
- attachmentId,
- });
- return;
- }
-
- const db = await chatDb();
- const message = await db.get("messages", messageUuid);
- if (!message?.attachments) return;
-
- let updated = false;
- const updatedAttachments = message.attachments.map((attachment) => {
- if (attachment.id === attachmentId) {
- if (!attachment.uploadedAt) {
- attachment.uploadedAt = nowMicros();
- }
- updated = true;
- }
- return attachment;
- });
-
- if (updated) {
- message.attachments = updatedAttachments;
- await db.put("messages", message);
- }
-};
-
-export const getPendingDeletions = async (
- chatKey: string,
-): Promise<SyncDeletion[]> => {
- if (isTauriRuntime()) {
- const deletions = await invokeChat<
- { entityType: string; uuid: string }[]
- >("chat_db_get_pending_deletions", { keyB64: chatKey });
- return deletions.map((deletion) => ({
- type: deletion.entityType === "message" ? "message" : "session",
- uuid: deletion.uuid,
- }));
- }
-
- const db = await chatDb();
- const [sessions, messages] = await Promise.all([
- db.getAll("sessions"),
- db.getAll("messages"),
- ]);
-
- const sessionsById = new Map(
- sessions.map((session) => [session.sessionUuid, session]),
- );
-
- const deletions: SyncDeletion[] = [];
- for (const session of sessions) {
- if (session.deletedAt && session.needsSync) {
- deletions.push({
- type: "session",
- uuid: session.sessionUuid,
- remoteId: session.remoteId ?? null,
- });
- }
- }
-
- for (const message of messages) {
- if (!message.deletedAt) continue;
- const session = sessionsById.get(message.sessionUuid);
- if (!session?.needsSync) continue;
- deletions.push({
- type: "message",
- uuid: message.messageUuid,
- remoteId: message.remoteId ?? null,
- });
- }
-
- return deletions;
-};
-
-export const hardDeleteEntity = async (
- deletion: SyncDeletion,
- chatKey: string,
-) => {
- if (isTauriRuntime()) {
- try {
- if (deletion.type === "session") {
- const messages = await invokeChat<NativeMessage[]>(
- "chat_db_get_messages_for_sync",
- {
- keyB64: chatKey,
- sessionUuid: deletion.uuid,
- includeDeleted: true,
- },
- );
- await Promise.all(
- messages.flatMap((message) =>
- (message.attachments ?? []).map((attachment) =>
- deleteAttachmentBytes(attachment.id),
- ),
- ),
- );
- } else {
- const message = await invokeChat<NativeMessage | null>(
- "chat_db_get_message",
- { keyB64: chatKey, messageUuid: deletion.uuid },
- );
- if (message?.attachments?.length) {
- await Promise.all(
- message.attachments.map((attachment) =>
- deleteAttachmentBytes(attachment.id),
- ),
- );
- }
- }
- } catch (error) {
- log.error("Failed to clean up attachment bytes", error);
- }
-
- await invokeChat("chat_db_hard_delete", {
- keyB64: chatKey,
- entityType: deletion.type,
- uuid: deletion.uuid,
- });
- if (deletion.type === "session") {
- await deleteBranchSelections(deletion.uuid);
- }
- return;
- }
-
- const db = await chatDb();
- if (deletion.type === "session") {
- const tx = db.transaction(["sessions", "messages"], "readwrite");
- await tx.objectStore("sessions").delete(deletion.uuid);
- const messageStore = tx.objectStore("messages");
- const messages = await messageStore.getAll();
- const sessionMessages = messages.filter(
- (message) => message.sessionUuid === deletion.uuid,
- );
- await Promise.all(
- sessionMessages.map((message) =>
- messageStore.delete(message.messageUuid),
- ),
- );
- await tx.done;
-
- await Promise.all(
- sessionMessages.flatMap((message) =>
- (message.attachments ?? []).map((attachment) =>
- deleteAttachmentBytes(attachment.id),
- ),
- ),
- );
-
- await deleteBranchSelections(deletion.uuid);
- return;
- }
-
- const message = await db.get("messages", deletion.uuid);
- if (message?.attachments?.length) {
- await Promise.all(
- message.attachments.map((attachment) =>
- deleteAttachmentBytes(attachment.id),
- ),
- );
- }
- await db.delete("messages", deletion.uuid);
-};
diff --git a/web/apps/ensu/src/services/chat/sync.ts b/web/apps/ensu/src/services/chat/sync.ts
deleted file mode 100644
index dd08f44eaa..0000000000
--- a/web/apps/ensu/src/services/chat/sync.ts
+++ /dev/null
@@ -1,1272 +0,0 @@
-import { isTauriRuntime } from "@/services/tauri-runtime";
-import { savedLocalUser } from "ente-accounts/services/accounts-db";
-import {
- authenticatedRequestHeaders,
- ensureOk,
- HTTPError,
-} from "ente-base/http";
-import { getKV, setKV } from "ente-base/kv";
-import log from "ente-base/log";
-import { apiOrigin, apiURL } from "ente-base/origins";
-import { savedAuthToken } from "ente-base/token";
-import { masterKeyFromSession } from "../session";
-import { decryptAttachmentBytes, encryptAttachmentBytes } from "./attachments";
-import { cachedLocalChatKey } from "./chatKey";
-import {
- decryptChatField,
- decryptChatPayload,
- encryptChatField,
- encryptChatPayload,
-} from "./crypto";
-import { computeMd5Base64 } from "./md5";
-import {
- attachmentBytesExists,
- getPendingDeletions,
- getSessionRecord,
- hardDeleteEntity,
- insertMessageFromRemote,
- listMessageRemoteMap,
- listMessagesForSessionSync,
- listSessionRemoteMap,
- listSessionsForSync,
- markAttachmentUploaded,
- markMessageDeletedAt,
- markMessageSynced,
- markSessionDeletedAt,
- markSessionSynced,
- readAttachmentBytes,
- upsertSessionRecord,
- writeAttachmentBytes,
- type ChatAttachment,
- type LocalMessageRecord,
- type LocalSessionRecord,
-} from "./store";
-
-type DiffCursor = {
- base_since_time: number;
- since_time: number;
- max_time: number;
- since_type: string;
- since_id: string;
-};
-
-const DEFAULT_CURSOR: DiffCursor = {
- base_since_time: 0,
- since_time: 0,
- max_time: 0,
- since_type: "sessions",
- since_id: "00000000-0000-0000-0000-000000000000",
-};
-
-const ZERO_UUID = "00000000-0000-0000-0000-000000000000";
-
-const DEDUPE_WINDOW_US = 2_000_000;
-const DIFF_PAGE_LIMIT = 500;
-const RETRY_DELAYS_MS = [2000, 5000, 10000];
-
-export class ChatSyncLimitError extends Error {
- code: string;
-
- constructor(code: string, message: string) {
- super(message);
- this.code = code;
- this.name = "ChatSyncLimitError";
- }
-}
-
-const sleep = (ms: number) =>
- new Promise<void>((resolve) => {
- setTimeout(resolve, ms);
- });
-
-const extractErrorCode = (error: unknown) => {
- if (!error || typeof error !== "object") return undefined;
- const code = (error as { code?: unknown }).code;
- return typeof code === "string" ? code : undefined;
-};
-
-const normalizeUuid = (value?: string | null) => {
- if (!value) return undefined;
- const trimmed = value.trim();
- if (!trimmed || trimmed === ZERO_UUID) return undefined;
- return trimmed;
-};
-
-const decodeClientId = (metadata?: string | null) => {
- if (!metadata) return undefined;
- try {
- const parsed = JSON.parse(metadata) as { clientId?: unknown };
- if (typeof parsed.clientId === "string" && parsed.clientId.trim()) {
- return parsed.clientId;
- }
- } catch {
- return undefined;
- }
- return undefined;
-};
-
-const encodeClientMetadata = async (
- clientId: string,
- createdAt: number,
- chatKey: string,
-) => {
- const payload: { clientId: string; createdAt?: string } = { clientId };
- if (createdAt > 0) {
- payload.createdAt = await encryptChatField(String(createdAt), chatKey);
- }
- return JSON.stringify(payload);
-};
-
-const extractErrorMessage = (error: unknown) => {
- if (!error || typeof error !== "object") return undefined;
- const message = (error as { message?: unknown }).message;
- return typeof message === "string" ? message : undefined;
-};
-
-const isRetryableError = (error: unknown) => {
- if (error instanceof ChatSyncLimitError) {
- return (
- error.code === "LLMCHAT_RATE_LIMIT_REACHED" ||
- error.code === "LLMCHAT_TEMPORARY_LIMIT"
- );
- }
- if (error instanceof HTTPError) {
- return error.res.status === 429 || error.res.status >= 500;
- }
- return error instanceof TypeError;
-};
-
-const withRetry = async (fn: () => Promise<void>) => {
- let attempt = 0;
- while (true) {
- try {
- await fn();
- return;
- } catch (error) {
- if (!isRetryableError(error) || attempt >= RETRY_DELAYS_MS.length) {
- throw error;
- }
- const delay = RETRY_DELAYS_MS[attempt] ?? 0;
- attempt += 1;
- await sleep(delay);
- }
- }
-};
-
-let syncPromise: Promise<void> | null = null;
-
-const syncChatNative = async (chatKey: string, token: string) => {
- const masterKey = await masterKeyFromSession();
- if (!masterKey) return;
-
- const { invoke } = await import("@tauri-apps/api/core");
- const { getName, getVersion } = await import("@tauri-apps/api/app");
-
- const [baseUrl, clientPackage, clientVersion] = await Promise.all([
- apiOrigin(),
- getName(),
- getVersion(),
- ]);
-
- try {
- await invoke("chat_sync", {
- keyB64: chatKey,
- baseUrl,
- authToken: token,
- masterKeyB64: masterKey,
- userAgent: "EnteTauri",
- clientPackage,
- clientVersion,
- });
- } catch (error) {
- const code = extractErrorCode(error);
- if (
- code === "LLMCHAT_RATE_LIMIT_REACHED" ||
- code === "LLMCHAT_TEMPORARY_LIMIT"
- ) {
- throw new ChatSyncLimitError(
- code,
- extractErrorMessage(error) ?? "Sync limit reached",
- );
- }
- throw error;
- }
-};
-
-export const syncChat = async (chatKey: string) => {
- if (!chatKey) return;
- const token = await savedAuthToken();
- if (!token) return;
-
- if (syncPromise) {
- return syncPromise;
- }
-
- syncPromise = (async () => {
- try {
- if (isTauriRuntime()) {
- await withRetry(() => syncChatNative(chatKey, token));
- return;
- }
-
- await withRetry(async () => {
- await pullChat(chatKey);
- await pushChat(chatKey);
- });
- } finally {
- syncPromise = null;
- }
- })();
-
- return syncPromise;
-};
-
-export const downloadAttachment = async (attachmentId: string) => {
- if (!isTauriRuntime()) return;
-
- const token = await savedAuthToken();
- if (!token) return;
-
- if (await attachmentBytesExists(attachmentId)) return;
-
- const res = await fetch(
- await apiURL(`/llmchat/chat/attachment/${attachmentId}`),
- { headers: await authenticatedRequestHeaders(), redirect: "follow" },
- );
- ensureOk(res);
- const buffer = await res.arrayBuffer();
- await writeAttachmentBytes(attachmentId, new Uint8Array(buffer));
-};
-
-const cursorStorageKey = () => {
- const userId = savedLocalUser()?.id ?? "anon";
- return `ensu.chat.sync.cursor.${userId}`;
-};
-
-const loadCursor = async (): Promise<DiffCursor> => {
- const raw = await getKV(cursorStorageKey());
- if (!raw || typeof raw !== "object") return { ...DEFAULT_CURSOR };
- try {
- const parsed = raw as Partial<DiffCursor>;
- return { ...DEFAULT_CURSOR, ...parsed };
- } catch (error) {
- log.error("Failed to parse chat sync cursor", error);
- return { ...DEFAULT_CURSOR };
- }
-};
-
-const saveCursor = (cursor: DiffCursor) => setKV(cursorStorageKey(), cursor);
-
-const pullChat = async (chatKey: string) => {
- let cursor = await loadCursor();
- let previousCursor = "";
- let iterations = 0;
-
- while (iterations < 200) {
- const response = await fetchDiff(cursor);
- await applyDiff(response, chatKey);
-
- const nextCursor = normalizeCursor(response);
- await saveCursor(nextCursor);
- const serialized = JSON.stringify(nextCursor);
- if (serialized === previousCursor) {
- log.warn("Chat sync cursor stalled; stopping pull loop");
- break;
- }
-
- const completed =
- nextCursor.since_type === "sessions" &&
- nextCursor.since_time === nextCursor.base_since_time &&
- nextCursor.since_time === nextCursor.max_time;
- if (completed) break;
-
- previousCursor = serialized;
- cursor = nextCursor;
- iterations += 1;
- }
-};
-
-const pushChat = async (chatKey: string) => {
- await pushDeletions(chatKey);
-
- const sessions = await listSessionsForSync(chatKey);
- for (const session of sessions) {
- if (session.deletedAt) continue;
-
- try {
- const messages = await listMessagesForSessionSync(
- session.sessionUuid,
- chatKey,
- );
-
- await reencryptPendingAttachments(messages, chatKey);
- try {
- await uploadPendingAttachments(messages, chatKey);
- } catch (error) {
- if (error instanceof ChatSyncLimitError) {
- log.warn(
- `Attachment limit reached for session ${session.sessionUuid}; some messages might be blocked`,
- );
- } else {
- throw error;
- }
- }
-
- const refreshedMessages = await listMessagesForSessionSync(
- session.sessionUuid,
- chatKey,
- );
-
- const blocked = buildBlockedMessages(refreshedMessages);
- const ordered = orderMessagesForSync(refreshedMessages).filter(
- (message) =>
- !message.deletedAt && !blocked.has(message.messageUuid),
- );
-
- const sessionRemoteId = await upsertRemoteSession(session, chatKey);
- const remoteIdsByLocal = new Map<string, string>();
- for (const message of refreshedMessages) {
- if (message.remoteId) {
- remoteIdsByLocal.set(message.messageUuid, message.remoteId);
- }
- }
-
- let sessionError: Error | null = null;
- for (const message of ordered) {
- try {
- const parentRemoteId = message.parentMessageUuid
- ? remoteIdsByLocal.get(message.parentMessageUuid)
- : undefined;
- if (message.parentMessageUuid && !parentRemoteId) {
- sessionError = new Error(
- `Missing parent remote id for ${message.messageUuid}`,
- );
- break;
- }
- const messageRemoteId = await upsertRemoteMessage(
- message,
- sessionRemoteId,
- parentRemoteId,
- chatKey,
- );
- if (messageRemoteId) {
- remoteIdsByLocal.set(
- message.messageUuid,
- messageRemoteId,
- );
- await markMessageSynced(
- message.messageUuid,
- messageRemoteId,
- );
- }
- } catch (error) {
- if (error instanceof ChatSyncLimitError) {
- log.error(
- `Message-specific limit reached for ${message.messageUuid}`,
- error,
- );
- sessionError = error;
- // For limit errors, we stop pushing further messages in this session
- // to maintain causal consistency on the server.
- break;
- }
- throw error;
- }
- }
-
- if (blocked.size === 0 && !sessionError) {
- await markSessionSynced(
- session.sessionUuid,
- sessionRemoteId,
- chatKey,
- );
- } else {
- const existing = await getSessionRecord(
- session.sessionUuid,
- chatKey,
- );
- if (existing) {
- await upsertSessionRecord(
- {
- ...existing,
- remoteId: existing.remoteId ?? sessionRemoteId,
- needsSync: true,
- },
- chatKey,
- );
- }
- }
- } catch (error) {
- log.error(`Failed to push session ${session.sessionUuid}`, error);
- // If it's a transient limit, we stop the whole push to respect backoff
- if (
- error instanceof ChatSyncLimitError &&
- isRetryableError(error)
- ) {
- throw error;
- }
- // Otherwise we continue with other sessions
- }
- }
-};
-
-const pushDeletions = async (chatKey: string) => {
- const deletions = await getPendingDeletions(chatKey);
- for (const deletion of deletions) {
- const remoteId = normalizeUuid(deletion.remoteId);
- if (!remoteId) {
- await hardDeleteEntity(deletion, chatKey);
- continue;
- }
- const endpoint =
- deletion.type === "session"
- ? `/llmchat/chat/session?id=${encodeURIComponent(remoteId)}`
- : `/llmchat/chat/message?id=${encodeURIComponent(remoteId)}`;
- const res = await fetch(await apiURL(endpoint), {
- method: "DELETE",
- headers: await authenticatedRequestHeaders(),
- });
- if (res.ok || res.status === 404) {
- await hardDeleteEntity(deletion, chatKey);
- continue;
- }
- ensureOk(res);
- }
-};
-
-const fetchDiff = async (cursor: DiffCursor) => {
- const query = new URLSearchParams({
- sinceTime: String(cursor.since_time),
- sinceType: cursor.since_type,
- sinceId: cursor.since_id,
- limit: String(DIFF_PAGE_LIMIT),
- });
- const res = await fetch(
- await apiURL(`/llmchat/chat/diff?${query.toString()}`),
- { headers: await authenticatedRequestHeaders() },
- );
- await handleChatLimitError(res);
- ensureOk(res);
- return (await res.json()) as DiffResponse;
-};
-
-const normalizeCursor = (response: DiffResponse): DiffCursor => {
- if (response.cursor) {
- const baseSinceTime =
- response.cursor.base_since_time ??
- (response.cursor as { baseSinceTime?: number }).baseSinceTime ??
- 0;
- const sinceTime =
- response.cursor.since_time ??
- (response.cursor as { sinceTime?: number }).sinceTime ??
- baseSinceTime;
- const maxTime =
- response.cursor.max_time ??
- (response.cursor as { maxTime?: number }).maxTime ??
- sinceTime;
- const sinceType =
- response.cursor.since_type ??
- (response.cursor as { sinceType?: string }).sinceType ??
- "sessions";
- const sinceId =
- response.cursor.since_id ??
- (response.cursor as { sinceId?: string }).sinceId ??
- "00000000-0000-0000-0000-000000000000";
- return {
- base_since_time: baseSinceTime,
- since_time: sinceTime,
- max_time: maxTime,
- since_type: sinceType,
- since_id: sinceId,
- };
- }
-
- const timestamp = response.timestamp ?? 0;
- return {
- base_since_time: timestamp,
- since_time: timestamp,
- max_time: timestamp,
- since_type: "sessions",
- since_id: "00000000-0000-0000-0000-000000000000",
- };
-};
-
-const handleChatLimitError = async (res: Response) => {
- if (res.ok) return;
- try {
- const payload = (await res.clone().json()) as {
- code?: string;
- message?: string;
- };
- const code = payload.code;
- if (code && code.startsWith("LLMCHAT_")) {
- throw new ChatSyncLimitError(
- code,
- chatLimitMessage(code, payload.message),
- );
- }
- } catch (error) {
- if (error instanceof ChatSyncLimitError) {
- throw error;
- }
- }
-};
-
-const chatLimitMessage = (code: string, fallback?: string) => {
- switch (code) {
- case "LLMCHAT_MESSAGE_LIMIT_REACHED":
- return "Message limit reached. Please shorten the message.";
- case "LLMCHAT_ATTACHMENT_LIMIT_REACHED":
- return "Attachment limit reached. Please remove some attachments.";
- case "LLMCHAT_PAYLOAD_TOO_LARGE":
- return "Payload too large. Please reduce message or attachment size.";
- case "LLMCHAT_RATE_LIMIT_REACHED":
- return "Rate limit reached. Please try again later.";
- default:
- return fallback ?? "Sync failed due to server limits.";
- }
-};
-
-const applyDiff = async (response: DiffResponse, chatKey: string) => {
- const sessionRemoteMap = await listSessionRemoteMap();
-
- const sessions = response.sessions ?? [];
- for (const session of sessions) {
- const remoteSessionId = normalizeUuid(
- session.session_uuid ?? session.sessionUuid,
- );
- if (!remoteSessionId) continue;
-
- const clientId = decodeClientId(
- session.client_metadata ?? session.clientMetadata,
- );
- const existingByClient = clientId
- ? await getSessionRecord(clientId, chatKey)
- : null;
- const localSessionId =
- existingByClient?.sessionUuid ??
- sessionRemoteMap.get(remoteSessionId) ??
- remoteSessionId;
-
- if (session.is_deleted) {
- const deletedAt =
- session.updated_at ?? session.created_at ?? Date.now() * 1000;
- await markSessionDeletedAt(localSessionId, deletedAt, chatKey);
- sessionRemoteMap.set(remoteSessionId, localSessionId);
- continue;
- }
-
- let decrypted: { title?: string };
- try {
- decrypted = (await decryptChatPayload(
- {
- encryptedData:
- session.encrypted_data ?? session.encryptedData ?? "",
- header: session.header,
- },
- chatKey,
- )) as { title?: string };
- } catch (error) {
- log.error(
- `Failed to decrypt session ${remoteSessionId}; skipping`,
- error,
- );
- continue;
- }
-
- const existing = await getSessionRecord(localSessionId, chatKey);
- const needsSync = existing?.needsSync ?? false;
- const createdAt = Math.min(
- existing?.createdAt ?? session.created_at ?? 0,
- session.created_at ?? existing?.createdAt ?? 0,
- );
- const updatedAt = Math.max(
- existing?.updatedAt ?? session.updated_at ?? 0,
- session.updated_at ?? existing?.updatedAt ?? 0,
- );
- const remoteTitle = decrypted.title ?? "New chat";
- const title = needsSync
- ? (existing?.title ?? remoteTitle)
- : remoteTitle;
-
- await upsertSessionRecord(
- {
- sessionUuid: localSessionId,
- title,
- createdAt,
- updatedAt,
- remoteId: remoteSessionId,
- needsSync,
- deletedAt: existing?.deletedAt ?? null,
- },
- chatKey,
- );
- sessionRemoteMap.set(remoteSessionId, localSessionId);
- }
-
- const messages = response.messages ?? [];
- const grouped = new Map<string, RemoteMessage[]>();
- for (const message of messages) {
- const remoteSessionId = normalizeUuid(
- message.session_uuid ?? message.sessionUuid,
- );
- if (!remoteSessionId) continue;
- const list = grouped.get(remoteSessionId) ?? [];
- list.push(message);
- grouped.set(remoteSessionId, list);
- }
-
- for (const [remoteSessionId, remoteMessages] of grouped.entries()) {
- const localSessionId =
- sessionRemoteMap.get(remoteSessionId) ?? remoteSessionId;
- const localMessages = await listMessagesForSessionSync(
- localSessionId,
- chatKey,
- { includeDeleted: true },
- );
- const localById = new Map(
- localMessages.map((msg) => [msg.messageUuid, msg]),
- );
- const localByRemoteId = new Map(
- localMessages
- .filter((msg) => msg.remoteId)
- .map((msg) => [msg.remoteId as string, msg]),
- );
- const remoteToLocal = new Map<string, string>();
- for (const msg of localMessages) {
- if (msg.remoteId) {
- remoteToLocal.set(msg.remoteId, msg.messageUuid);
- } else {
- remoteToLocal.set(msg.messageUuid, msg.messageUuid);
- }
- }
- const signatureMap = buildSignatureMap(localMessages);
-
- for (const remote of remoteMessages) {
- const remoteMessageId = normalizeUuid(
- remote.message_uuid ?? remote.messageUuid,
- );
- if (!remoteMessageId) continue;
-
- const clientId = decodeClientId(
- remote.client_metadata ?? remote.clientMetadata,
- );
- const existingByClient = clientId ? localById.get(clientId) : null;
- const existingByRemote =
- localByRemoteId.get(remoteMessageId) ?? null;
- const localMessageId =
- existingByClient?.messageUuid ??
- existingByRemote?.messageUuid ??
- remoteMessageId;
-
- const parentRemoteId = normalizeUuid(
- remote.parent_message_uuid ?? remote.parentMessageUuid,
- );
- const parentLocalId = parentRemoteId
- ? (remoteToLocal.get(parentRemoteId) ?? parentRemoteId)
- : null;
-
- if (remote.is_deleted) {
- const deletedAt =
- remote.updated_at ?? remote.created_at ?? Date.now() * 1000;
- await markMessageDeletedAt(localMessageId, deletedAt, chatKey);
- continue;
- }
-
- const existing = localById.get(localMessageId);
- if (existing) {
- if (remoteMessageId && existing.remoteId !== remoteMessageId) {
- await markMessageSynced(localMessageId, remoteMessageId);
- existing.remoteId = remoteMessageId;
- localByRemoteId.set(remoteMessageId, existing);
- remoteToLocal.set(remoteMessageId, localMessageId);
- }
- for (const attachment of remote.attachments ?? []) {
- try {
- await markAttachmentUploaded(
- localMessageId,
- attachment.id,
- chatKey,
- );
- } catch (error) {
- log.error(
- "Failed to reconcile attachment state",
- error,
- );
- }
- }
- continue;
- }
-
- const payload = (await decryptChatPayload(
- {
- encryptedData:
- remote.encrypted_data ?? remote.encryptedData ?? "",
- header: remote.header,
- },
- chatKey,
- )) as { text?: string };
- const text = payload.text ?? "";
-
- const attachments = await normalizeRemoteAttachments(
- remote.attachments ?? [],
- chatKey,
- remote.created_at ?? 0,
- );
-
- const sender = normalizeSender(remote.sender);
- const signature = buildSignature(sender, text, attachments);
- const possible = signatureMap.get(signature) ?? [];
- const isDuplicate = possible.some(
- (candidate) =>
- Math.abs(candidate.createdAt - (remote.created_at ?? 0)) <=
- DEDUPE_WINDOW_US,
- );
-
- if (isDuplicate) continue;
-
- const localMessage: LocalMessageRecord = {
- messageUuid: localMessageId,
- sessionUuid: localSessionId,
- parentMessageUuid: parentLocalId,
- sender,
- text,
- createdAt: remote.created_at ?? 0,
- attachments,
- remoteId: remoteMessageId,
- deletedAt: null,
- };
-
- await insertMessageFromRemote(localMessage, chatKey);
- const updatedList = signatureMap.get(signature) ?? [];
- updatedList.push(localMessage);
- signatureMap.set(signature, updatedList);
-
- localById.set(localMessageId, localMessage);
- localByRemoteId.set(remoteMessageId, localMessage);
- remoteToLocal.set(remoteMessageId, localMessageId);
- }
- }
-
- const tombstones = response.tombstones;
- if (tombstones) {
- for (const session of tombstones.sessions ?? []) {
- const remoteSessionId = normalizeUuid(
- session.session_uuid ?? session.sessionUuid,
- );
- if (!remoteSessionId) continue;
- const deletedAt = session.deleted_at ?? session.deletedAt ?? 0;
- const localSessionId =
- sessionRemoteMap.get(remoteSessionId) ?? remoteSessionId;
- await markSessionDeletedAt(localSessionId, deletedAt, chatKey);
- }
-
- const messageTombstones = tombstones.messages ?? [];
- if (messageTombstones.length) {
- const messageRemoteMap = await listMessageRemoteMap();
- for (const message of messageTombstones) {
- const remoteMessageId = normalizeUuid(
- message.message_uuid ?? message.messageUuid,
- );
- if (!remoteMessageId) continue;
- const deletedAt = message.deleted_at ?? message.deletedAt ?? 0;
- const localMessageId =
- messageRemoteMap.get(remoteMessageId) ?? remoteMessageId;
- await markMessageDeletedAt(localMessageId, deletedAt, chatKey);
- }
- }
- }
-};
-
-const normalizeRemoteAttachments = async (
- attachments: RemoteAttachment[],
- chatKey: string,
- uploadedAt: number,
-): Promise<ChatAttachment[]> => {
- if (!attachments.length || !isTauriRuntime()) return [];
- return Promise.all(
- attachments.map(async (attachment) => {
- const encryptedName =
- attachment.encrypted_name ?? attachment.encryptedName ?? "";
- let name = "Attachment";
- if (encryptedName) {
- try {
- name = await decryptChatField(encryptedName, chatKey);
- } catch (error) {
- log.error("Failed to decrypt attachment name", error);
- }
- }
- return {
- id: attachment.id,
- kind: "document",
- name,
- size: attachment.size,
- encryptedName,
- uploadedAt,
- } satisfies ChatAttachment;
- }),
- );
-};
-
-const reencryptPendingAttachments = async (
- messages: LocalMessageRecord[],
- chatKey: string,
-) => {
- const localKey = cachedLocalChatKey();
- if (!localKey || localKey === chatKey) return;
-
- const seen = new Set<string>();
- for (const message of messages) {
- for (const attachment of message.attachments ?? []) {
- if (seen.has(attachment.id)) continue;
- seen.add(attachment.id);
-
- try {
- const bytes = await readAttachmentBytes(attachment.id);
- try {
- await decryptAttachmentBytes(
- bytes,
- chatKey,
- message.sessionUuid,
- );
- continue;
- } catch {
- // fall through to local key
- }
-
- const plaintext = await decryptAttachmentBytes(
- bytes,
- localKey,
- message.sessionUuid,
- );
- const reencrypted = await encryptAttachmentBytes(
- plaintext,
- chatKey,
- message.sessionUuid,
- );
- await writeAttachmentBytes(attachment.id, reencrypted);
- } catch (error) {
- log.error("Failed to re-encrypt attachment", error);
- }
- }
- }
-};
-
-const uploadPendingAttachments = async (
- messages: LocalMessageRecord[],
- chatKey: string,
-) => {
- const pending = new Map<
- string,
- {
- sessionUuid: string;
- attachment: ChatAttachment;
- messageUuids: Set<string>;
- }
- >();
-
- for (const message of messages) {
- if (message.deletedAt) continue;
- for (const attachment of message.attachments ?? []) {
- if (attachment.uploadedAt) continue;
- const existing = pending.get(attachment.id);
- if (existing) {
- existing.messageUuids.add(message.messageUuid);
- continue;
- }
- pending.set(attachment.id, {
- sessionUuid: message.sessionUuid,
- attachment,
- messageUuids: new Set([message.messageUuid]),
- });
- }
- }
-
- for (const pendingItem of pending.values()) {
- const { attachment, sessionUuid, messageUuids } = pendingItem;
- const markUploaded = async () => {
- await Promise.all(
- [...messageUuids].map((messageUuid) =>
- markAttachmentUploaded(messageUuid, attachment.id, chatKey),
- ),
- );
- };
-
- try {
- const bytes = await ensureAttachmentEncryptedForUpload(
- attachment.id,
- sessionUuid,
- chatKey,
- );
- const contentMd5 = computeMd5Base64(bytes);
- const res = await fetch(
- await apiURL(
- `/llmchat/chat/attachment/${attachment.id}/upload-url`,
- ),
- {
- method: "POST",
- headers: {
- ...(await authenticatedRequestHeaders()),
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- content_length: bytes.length,
- content_md5: contentMd5,
- }),
- },
- );
-
- if (res.status === 409) {
- await markUploaded();
- continue;
- }
-
- if (res.status === 501 || res.status === 404) {
- log.warn("Attachment API unavailable; skipping upload");
- continue;
- }
-
- await handleChatLimitError(res);
- ensureOk(res);
- const { url } = (await res.json()) as { url?: string };
- if (!url) {
- throw new Error("Invalid attachment upload response");
- }
-
- const uploadRes = await fetch(url, {
- method: "PUT",
- headers: {
- "Content-Length": String(bytes.length),
- "Content-MD5": contentMd5,
- },
- body: bytes,
- });
- ensureOk(uploadRes);
-
- await markUploaded();
- } catch (error) {
- if (error instanceof ChatSyncLimitError) {
- throw error;
- }
- log.error("Attachment upload failed", error);
- }
- }
-};
-
-const ensureAttachmentEncryptedForUpload = async (
- attachmentId: string,
- sessionUuid: string,
- chatKey: string,
-): Promise<Uint8Array<ArrayBuffer>> => {
- const bytes = await readAttachmentBytes(attachmentId);
-
- try {
- await decryptAttachmentBytes(bytes, chatKey, sessionUuid);
- return bytes;
- } catch (error) {
- const localKey = cachedLocalChatKey();
- if (!localKey || localKey === chatKey) {
- throw error;
- }
-
- const plaintext = await decryptAttachmentBytes(
- bytes,
- localKey,
- sessionUuid,
- );
- const reencrypted = await encryptAttachmentBytes(
- plaintext,
- chatKey,
- sessionUuid,
- );
- await writeAttachmentBytes(attachmentId, reencrypted);
- return reencrypted;
- }
-};
-
-const upsertRemoteSession = async (
- session: LocalSessionRecord,
- chatKey: string,
-): Promise<string> => {
- const encrypted = await encryptChatPayload(
- { title: session.title },
- chatKey,
- );
- const clientMetadata = await encodeClientMetadata(
- session.sessionUuid,
- session.createdAt,
- chatKey,
- );
- const sessionUuid = normalizeUuid(session.remoteId) ?? "";
- const res = await fetch(await apiURL("/llmchat/chat/session"), {
- method: "POST",
- headers: {
- ...(await authenticatedRequestHeaders()),
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- session_uuid: sessionUuid,
- encrypted_data: encrypted.encryptedData,
- header: encrypted.header,
- client_metadata: clientMetadata,
- }),
- });
- await handleChatLimitError(res);
- ensureOk(res);
- const payload = (await res.json()) as {
- session_uuid?: string;
- sessionUuid?: string;
- };
- return (
- normalizeUuid(payload.session_uuid ?? payload.sessionUuid) ??
- sessionUuid
- );
-};
-
-const upsertRemoteMessage = async (
- message: LocalMessageRecord,
- sessionRemoteId: string,
- parentRemoteId: string | undefined,
- chatKey: string,
-): Promise<string> => {
- const sanitizedText = message.attachments?.length
- ? stripDocumentBlocks(message.text)
- : message.text;
- const encrypted = await encryptChatPayload(
- { text: sanitizedText },
- chatKey,
- );
- const attachments = await Promise.all(
- (message.attachments ?? []).map(async (attachment) => ({
- id: attachment.id,
- size: attachment.size,
- encrypted_name:
- attachment.encryptedName ??
- (await encryptChatField(attachment.name, chatKey)),
- })),
- );
-
- const clientMetadata = await encodeClientMetadata(
- message.messageUuid,
- message.createdAt,
- chatKey,
- );
- const messageUuid = normalizeUuid(message.remoteId) ?? "";
- const parentMessageUuid = normalizeUuid(parentRemoteId);
-
- const res = await fetch(await apiURL("/llmchat/chat/message"), {
- method: "POST",
- headers: {
- ...(await authenticatedRequestHeaders()),
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- message_uuid: messageUuid,
- session_uuid: sessionRemoteId,
- parent_message_uuid: parentMessageUuid ?? null,
- sender: message.sender === "assistant" ? "other" : "self",
- attachments,
- encrypted_data: encrypted.encryptedData,
- header: encrypted.header,
- client_metadata: clientMetadata,
- }),
- });
- await handleChatLimitError(res);
- ensureOk(res);
- const payload = (await res.json()) as {
- message_uuid?: string;
- messageUuid?: string;
- };
- return (
- normalizeUuid(payload.message_uuid ?? payload.messageUuid) ??
- messageUuid
- );
-};
-
-const stripDocumentBlocks = (text: string) =>
- text
- .replace(
- /----- BEGIN DOCUMENT: ([^\n]+) -----\n([\s\S]*?)\n----- END DOCUMENT: \1 -----/g,
- "",
- )
- .replace(/\n{3,}/g, "\n\n")
- .trim();
-
-const buildBlockedMessages = (messages: LocalMessageRecord[]) => {
- const blocked = new Set<string>();
- for (const message of messages) {
- if (message.deletedAt) continue;
- const pending = (message.attachments ?? []).some(
- (attachment) => !attachment.uploadedAt,
- );
- if (pending) {
- blocked.add(message.messageUuid);
- }
- }
-
- if (blocked.size === 0) return blocked;
-
- const children = new Map<string | null, LocalMessageRecord[]>();
- for (const message of messages) {
- const parent = message.parentMessageUuid ?? null;
- const list = children.get(parent) ?? [];
- list.push(message);
- children.set(parent, list);
- }
-
- const queue = Array.from(blocked);
- while (queue.length) {
- const current = queue.shift();
- if (!current) continue;
- const kids = children.get(current) ?? [];
- for (const kid of kids) {
- if (!blocked.has(kid.messageUuid)) {
- blocked.add(kid.messageUuid);
- queue.push(kid.messageUuid);
- }
- }
- }
-
- return blocked;
-};
-
-const orderMessagesForSync = (messages: LocalMessageRecord[]) => {
- const children = new Map<string | null, LocalMessageRecord[]>();
- for (const message of messages) {
- const parent = message.parentMessageUuid ?? null;
- const list = children.get(parent) ?? [];
- list.push(message);
- children.set(parent, list);
- }
-
- for (const list of children.values()) {
- list.sort((a, b) => {
- if (a.createdAt !== b.createdAt) {
- return a.createdAt - b.createdAt;
- }
- return a.messageUuid.localeCompare(b.messageUuid);
- });
- }
-
- const ordered: LocalMessageRecord[] = [];
- const visited = new Set<string>();
- const visit = (message: LocalMessageRecord) => {
- if (visited.has(message.messageUuid)) return;
- visited.add(message.messageUuid);
- ordered.push(message);
- const kids = children.get(message.messageUuid) ?? [];
- for (const kid of kids) {
- visit(kid);
- }
- };
-
- const roots = children.get(null) ?? [];
- for (const root of roots) {
- visit(root);
- }
-
- for (const message of messages) {
- if (!visited.has(message.messageUuid)) {
- visit(message);
- }
- }
-
- return ordered;
-};
-
-const buildSignatureMap = (messages: LocalMessageRecord[]) => {
- const map = new Map<string, LocalMessageRecord[]>();
- for (const message of messages) {
- if (message.deletedAt) continue;
- const signature = buildSignature(
- message.sender,
- message.text,
- message.attachments ?? [],
- );
- const list = map.get(signature) ?? [];
- list.push(message);
- map.set(signature, list);
- }
- return map;
-};
-
-const buildSignature = (
- sender: string,
- text: string,
- attachments: ChatAttachment[],
-) => {
- const attachmentKey = [...attachments]
- .sort((a, b) => a.id.localeCompare(b.id))
- .map((attachment) =>
- [attachment.id, attachment.size, attachment.name].join(":"),
- )
- .join("|");
- return `${sender}:${text}:${attachmentKey}`;
-};
-
-const normalizeSender = (sender?: string) => {
- if (sender === "other" || sender === "assistant") return "assistant";
- return "self";
-};
-
-type DiffResponse = {
- sessions?: RemoteSession[];
- messages?: RemoteMessage[];
- tombstones?: { sessions?: RemoteTombstone[]; messages?: RemoteTombstone[] };
- cursor?: {
- base_since_time?: number;
- since_time?: number;
- max_time?: number;
- since_type?: string;
- since_id?: string;
- };
- timestamp?: number;
-};
-
-type RemoteSession = {
- session_uuid?: string;
- sessionUuid?: string;
- encrypted_data?: string;
- encryptedData?: string;
- client_metadata?: string;
- clientMetadata?: string;
- header: string;
- created_at?: number;
- updated_at?: number;
- is_deleted?: boolean;
-};
-
-type RemoteMessage = {
- message_uuid?: string;
- messageUuid?: string;
- session_uuid?: string;
- sessionUuid?: string;
- parent_message_uuid?: string | null;
- parentMessageUuid?: string | null;
- sender?: string;
- attachments?: RemoteAttachment[];
- encrypted_data?: string;
- encryptedData?: string;
- client_metadata?: string;
- clientMetadata?: string;
- header: string;
- created_at?: number;
- updated_at?: number;
- is_deleted?: boolean;
-};
-
-type RemoteAttachment = {
- id: string;
- size: number;
- encrypted_name?: string;
- encryptedName?: string;
-};
-
-type RemoteTombstone = {
- session_uuid?: string;
- sessionUuid?: string;
- message_uuid?: string;
- messageUuid?: string;
- deleted_at?: number;
- deletedAt?: number;
-};