Skip to content

armgit / ente

Public Imported from GitHub
0

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

update chat sync handling

Prateek Sunal661b660767ca
diff --git a/.github/workflows/ensu-internal-release.yml b/.github/workflows/ensu-internal-release.yml
new file mode 100644
index 0000000000..df311f68a1
--- /dev/null
+++ b/.github/workflows/ensu-internal-release.yml
@@ -0,0 +1,88 @@
+name: "Internal release (ensu mobile)"
+
+on:
+ workflow_dispatch: # Allow manually running the action
+
+env:
+ RUST_VERSION: "1.83"
+ NDK_VERSION: "27.0.12077973"
+
+permissions:
+ contents: write
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+
+ defaults:
+ run:
+ working-directory: mobile/native/android/apps/ensu
+
+ steps:
+ - name: Checkout code and submodules
+ uses: actions/checkout@v4
+ with:
+ submodules: recursive
+
+ - name: Setup JDK 17
+ uses: actions/setup-java@v4
+ with:
+ distribution: 'temurin'
+ java-version: '17'
+
+ - name: Setup Android SDK
+ uses: android-actions/setup-android@v3
+
+ - name: Install NDK
+ run: |
+ echo "y" | sdkmanager --install "ndk;${{ env.NDK_VERSION }}"
+ echo "ANDROID_NDK_HOME=$ANDROID_HOME/ndk/${{ env.NDK_VERSION }}" >> $GITHUB_ENV
+
+ - name: Setup Rust
+ uses: dtolnay/rust-toolchain@stable
+ with:
+ toolchain: ${{ env.RUST_VERSION }}
+ targets: aarch64-linux-android,armv7-linux-androideabi,x86_64-linux-android,i686-linux-android
+
+ - name: Install cargo-ndk
+ run: cargo install cargo-ndk
+
+ - name: Build Rust libraries
+ run: |
+ cd ../../../packages/rust/tool
+ ./build_android.sh
+ env:
+ ANDROID_HOME: ${{ env.ANDROID_HOME }}
+ NDK_VERSION: ${{ env.NDK_VERSION }}
+
+ - name: Setup signing keys
+ run: |
+ echo "${{ secrets.SIGNING_KEY_ENSU }}" | base64 -d > ensu-release.keystore
+ cat > key.properties << EOF
+ storeFile=ensu-release.keystore
+ storePassword=${{ secrets.SIGNING_STORE_PASSWORD_ENSU }}
+ keyAlias=${{ secrets.SIGNING_KEY_ALIAS_ENSU }}
+ keyPassword=${{ secrets.SIGNING_KEY_PASSWORD_ENSU }}
+ EOF
+
+ - name: Build PlayStore AAB
+ run: ./gradlew :app-ui:bundleRelease
+
+ - name: Upload AAB to PlayStore
+ uses: r0adkll/upload-google-play@v1
+ with:
+ serviceAccountJsonPlainText: ${{ secrets.SERVICE_ACCOUNT_JSON }}
+ packageName: io.ente.ensu
+ releaseFiles: mobile/native/android/apps/ensu/app-ui/build/outputs/bundle/release/app-ui-release.aab
+ track: internal
+ status: draft
+
+ - name: Notify Discord
+ if: success()
+ uses: sarisia/actions-status-discord@v1
+ with:
+ webhook: ${{ secrets.DISCORD_INTERNAL_RELEASE_WEBHOOK }}
+ nodetail: true
+ title: "πŸ€– Internal draft release available for Ensu"
+ description: "Draft release uploaded to Play Store internal track"
+ color: 0x4CAF50
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 950877d54f..78c8923372 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
@@ -47,6 +47,8 @@ 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 53c379110c..ad37b5affe 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
@@ -55,6 +55,7 @@ import io.ente.ensu.chat.SessionDrawer
import io.ente.ensu.components.NativeChoiceDialog
import io.ente.ensu.data.auth.EnsuAuthService
import io.ente.ensu.data.logging.FileLogRepository
+import io.ente.ensu.data.storage.FilePathManager
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.designsystem.EnsuTypography
@@ -452,13 +453,15 @@ fun HomeView(
if (isShowingSignOutDialog) {
NativeChoiceDialog(
title = "Sign Out",
- body = "This will stop syncing your sessions.",
+ body = "Signing out will remove your online chats from this device. Offline chats stay available.",
firstButtonLabel = "Sign Out",
secondButtonLabel = "Cancel",
onFirst = {
- authService.clearCredentials()
- store.signOut()
- isShowingSignOutDialog = false
+ scope.launch {
+ authService.clearCredentials()
+ store.signOut()
+ isShowingSignOutDialog = false
+ }
},
onSecond = { isShowingSignOutDialog = false },
onDismiss = { isShowingSignOutDialog = false }
@@ -507,10 +510,7 @@ private fun buildAttachmentFromUri(
}
val safeName = rawName.replace("/", "_")
- val attachmentsDir = File(context.filesDir, "attachments")
- if (!attachmentsDir.exists()) {
- attachmentsDir.mkdirs()
- }
+ val attachmentsDir = FilePathManager(context).attachmentsDir
val attachmentId = UUID.randomUUID().toString()
val destination = File(attachmentsDir, attachmentId)
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthSteps.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthSteps.kt
index 2a5e887f2f..a3574026db 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthSteps.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthSteps.kt
@@ -68,7 +68,13 @@ internal fun EmailEntryView(
isLoading = authState.isLoading,
isEnabled = isEmailValid && !authState.isLoading
) {
- authState.launch(onError = { "Failed to get account info: ${it.message}" }) {
+ authState.launch(onError = { error ->
+ when (error) {
+ is io.ente.ensu.data.auth.AccountNotFoundException ->
+ "No account found for this email."
+ else -> "Failed to get account info: ${error.message}"
+ }
+ }) {
val trimmed = email.trim()
val srpAttrs = authService.getSrpAttributes(trimmed)
if (srpAttrs.isEmailMfaEnabled) {
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatMessages.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatMessages.kt
index affe37bbdf..213f8ef955 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatMessages.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatMessages.kt
@@ -460,7 +460,7 @@ private fun UserMessageBubble(
text = message.text,
style = EnsuTypography.message,
color = EnsuColor.userMessageText(),
- textAlign = TextAlign.Right
+ textAlign = TextAlign.Start
)
}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/DeveloperSettingsScreen.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/DeveloperSettingsScreen.kt
index cd6edeeafb..678e2bb6f2 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/DeveloperSettingsScreen.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/DeveloperSettingsScreen.kt
@@ -32,6 +32,7 @@ import io.ente.ensu.designsystem.EnsuCornerRadius
import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.designsystem.EnsuTypography
import io.ente.ensu.designsystem.HugeIcons
+import io.ente.ensu.utils.EnsuFeatureFlags
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
@@ -55,13 +56,15 @@ fun DeveloperSettingsScreen(
.fillMaxSize()
.padding(EnsuSpacing.pageHorizontal.dp)
) {
- DeveloperSettingsRow(
- title = "Model settings",
- subtitle = "Model URL, mmproj, context length, max output",
- onClick = onOpenModelSettings
- )
+ if (EnsuFeatureFlags.enableModelSettings) {
+ DeveloperSettingsRow(
+ title = "Model settings",
+ subtitle = "Model URL, mmproj, context length, max output",
+ onClick = onOpenModelSettings
+ )
- Spacer(modifier = Modifier.height(EnsuSpacing.xxl.dp))
+ Spacer(modifier = Modifier.height(EnsuSpacing.xxl.dp))
+ }
Text(text = "Endpoint configuration", style = EnsuTypography.h3Bold, color = EnsuColor.textPrimary())
Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/utils/FeatureFlags.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/utils/FeatureFlags.kt
index 3ed1437d7f..0df2984034 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/utils/FeatureFlags.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/utils/FeatureFlags.kt
@@ -3,4 +3,5 @@ package io.ente.ensu.utils
object EnsuFeatureFlags {
const val enableSignIn = true
const val enableImageUploads = true
+ const val enableModelSettings = false
}
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 4edc52ec2c..ca90f88655 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,6 +14,8 @@ 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
@@ -30,6 +32,8 @@ 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)
@@ -107,7 +111,14 @@ class EnsuAuthService(
}
suspend fun getSrpAttributes(email: String): SrpAttributes {
- val response = networkFactory.authentication.getSrpAttributes(email)
+ val response = try {
+ networkFactory.authentication.getSrpAttributes(email)
+ } catch (error: ApiException) {
+ if (error.code == 404) {
+ throw AccountNotFoundException()
+ }
+ throw error
+ }
return SrpAttributes(
srpUserId = response.attributes.srpUserId,
srpSalt = response.attributes.srpSalt,
@@ -230,8 +241,10 @@ class EnsuAuthService(
logRepository.log(LogLevel.Info, "Login after challenge success", tag = "Auth")
}
- fun clearCredentials() {
+ suspend fun clearCredentials() {
credentialStore.clear()
+ chatRepository.exitOnlineMode()
+ chatSyncRepository.resetSyncState()
}
private suspend fun pingEndpoint(endpoint: HttpUrl) {
@@ -251,14 +264,31 @@ class EnsuAuthService(
}
}
- private fun storeSecrets(email: String, userId: Long, secrets: AuthSecrets) {
+ private suspend fun storeSecrets(email: String, userId: Long, secrets: AuthSecrets) {
val masterKey = secrets.masterKey.toUByteArray().toByteArray()
val secretKey = secrets.secretKey.toUByteArray().toByteArray()
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)
@@ -276,6 +306,7 @@ class EnsuAuthService(
class PasskeySessionNotVerifiedException : Exception()
class PasskeySessionExpiredException : Exception()
+class AccountNotFoundException : Exception()
private fun SrpAttributes.toCrypto(): CryptoSrpAttributes {
return CryptoSrpAttributes(
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/ChatRecovery.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/ChatRecovery.kt
index cb1eb05bd4..c8d2a56102 100644
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/ChatRecovery.kt
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/ChatRecovery.kt
@@ -1,7 +1,11 @@
package io.ente.ensu.data.chat
internal object ChatRecovery {
- private val resetSignals = listOf("stream pull failed", "invalid blob", "invalid encrypted")
+ private val resetSignals = listOf(
+ "stream pull failed",
+ "invalid blob",
+ "invalid encrypted"
+ )
fun shouldResetFromMessage(message: String): Boolean {
val lower = message.lowercase()
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 cc173ddb05..8b5b9a2727 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
@@ -18,15 +18,18 @@ import java.io.File
class RustChatRepository(
context: Context,
- credentialStore: CredentialStore
+ private val credentialStore: CredentialStore
) : ChatRepository {
private val filePaths = FilePathManager(context)
private val attachmentsDir = filePaths.attachmentsDir
- private val mainDbFile = filePaths.mainDbFile
- private val attachmentsDbFile = filePaths.attachmentsDbFile
- private val dbKey = credentialStore.getOrCreateChatDbKey()
- private var db: LlmChatDb = openDb()
+ 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: LlmChatDb = openDb(offlineDbFile, offlineDbKey)
override fun listSessions(): List<ChatSession> = withDbRecovery {
val sessions = db.listSessions()
@@ -134,27 +137,75 @@ class RustChatRepository(
db.updateSessionTitle(sessionId, title)
}
- private fun openDb(): LlmChatDb {
+ 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()
+ 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)
+ }
+
+ private fun openDb(dbFile: File, key: ByteArray): LlmChatDb {
return LlmChatDb.open(
- mainDbFile.absolutePath,
- attachmentsDbFile.absolutePath,
- dbKey
+ dbFile.absolutePath,
+ syncDbFile.absolutePath,
+ key
)
}
private fun <T> withDbRecovery(block: () -> T): T {
+ val targetDbFile = if (usingOnlineDb) onlineDbFile else offlineDbFile
+ if (!syncDbFile.exists() || !targetDbFile.exists()) {
+ reopenDb(targetDbFile)
+ }
return try {
block()
} catch (error: DbException) {
+ if (isReadonlyDbError(error)) {
+ reopenDb(targetDbFile)
+ return block()
+ }
if (shouldResetDb(error)) {
resetDb()
- block()
- } else {
- throw error
+ return block()
}
+ throw error
}
}
+ private fun reopenDb(targetDbFile: File) {
+ targetDbFile.parentFile?.mkdirs()
+ syncDbFile.parentFile?.mkdirs()
+ targetDbFile.setWritable(true)
+ syncDbFile.setWritable(true)
+ db = openDb(targetDbFile, currentDbKey())
+ }
+
private fun shouldResetDb(error: DbException): Boolean {
val message = when (error) {
is DbException.Message -> error.v1
@@ -163,9 +214,26 @@ class RustChatRepository(
return ChatRecovery.shouldResetFromMessage(message)
}
+ private fun isReadonlyDbError(error: DbException): Boolean {
+ val message = when (error) {
+ is DbException.Message -> error.v1
+ else -> error.message.orEmpty()
+ }
+ 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() {
- mainDbFile.delete()
- attachmentsDbFile.delete()
- db = openDb()
+ val targetDbFile = if (usingOnlineDb) onlineDbFile else offlineDbFile
+ targetDbFile.delete()
+ syncDbFile.delete()
+ db = openDb(targetDbFile, currentDbKey())
}
}
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
index b92f60b158..a7ae73616d 100644
--- 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
@@ -6,7 +6,16 @@ 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.llmchat_sync.LlmChatSync
+import io.ente.labs.llmchat_sync.MigrationConfig as RustMigrationConfig
+import io.ente.labs.llmchat_sync.MigrationPriority as RustMigrationPriority
+import io.ente.labs.llmchat_sync.MigrationProgress as RustMigrationProgress
+import io.ente.labs.llmchat_sync.MigrationProgressCallback
+import io.ente.labs.llmchat_sync.MigrationState as RustMigrationState
import io.ente.labs.llmchat_sync.SyncAuth
import io.ente.labs.llmchat_sync.SyncException
import kotlinx.coroutines.Dispatchers
@@ -21,16 +30,17 @@ class RustChatSyncRepository(
private val filePaths = FilePathManager(context)
private var syncEngine: LlmChatSync? = null
+ private var chatKey: ByteArray? = null
override suspend fun sync() {
withContext(Dispatchers.IO) {
try {
- syncEngine().sync(buildAuth())
+ ensureSyncEngine().sync(buildAuth())
} catch (err: Throwable) {
if (shouldResetSync(err)) {
- resetSyncState()
+ resetSyncStateInternal()
try {
- syncEngine().sync(buildAuth())
+ ensureSyncEngine().sync(buildAuth())
return@withContext
} catch (retryErr: Throwable) {
throw IllegalStateException(syncErrorMessage(retryErr), retryErr)
@@ -41,21 +51,70 @@ class RustChatSyncRepository(
}
}
+ 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) {
- syncEngine().downloadAttachment(attachmentId, sessionId, buildAuth())
+ ensureSyncEngine().downloadAttachment(attachmentId, sessionId, buildAuth())
+ }
+ }
+
+ override suspend fun prepareOnlineDb(): ByteArray {
+ return withContext(Dispatchers.IO) {
+ resetSyncStateInternal()
+ val auth = buildAuth()
+ val key = io.ente.labs.llmchat_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
}
}
- private fun syncEngine(): LlmChatSync {
- return syncEngine ?: buildSyncEngine().also { syncEngine = it }
+ override suspend fun resetSyncState() {
+ withContext(Dispatchers.IO) {
+ resetSyncStateInternal()
+ }
+ }
+
+ private suspend fun ensureSyncEngine(): LlmChatSync {
+ return syncEngine ?: run {
+ val key = chatKey ?: prepareOnlineDb()
+ buildSyncEngine(key).also { syncEngine = it }
+ }
}
- private fun buildSyncEngine(): LlmChatSync {
- val dbKey = credentialStore.getOrCreateChatDbKey()
+ private fun buildSyncEngine(dbKey: ByteArray): LlmChatSync {
return LlmChatSync.open(
- mainDbPath = filePaths.mainDbFile.absolutePath,
- attachmentsDbPath = filePaths.attachmentsDbFile.absolutePath,
+ mainDbPath = filePaths.onlineDbFile.absolutePath,
+ attachmentsDbPath = filePaths.syncDbFile.absolutePath,
dbKey = dbKey,
attachmentsDir = filePaths.encryptedAttachmentsDir.absolutePath,
metaDir = filePaths.syncMetaDir.absolutePath,
@@ -95,10 +154,16 @@ class RustChatSyncRepository(
return ChatRecovery.shouldResetFromMessage(message)
}
- private fun resetSyncState() {
- runCatching { filePaths.syncMetaDir.deleteRecursively() }
- runCatching { filePaths.syncMetaDir.mkdirs() }
+ 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 {
@@ -109,7 +174,42 @@ class RustChatSyncRepository(
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/CredentialStore.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/storage/CredentialStore.kt
index 41801e0e84..878400e0d4 100644
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/storage/CredentialStore.kt
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/storage/CredentialStore.kt
@@ -29,7 +29,26 @@ class CredentialStore(context: Context) {
}
fun clear() {
+ val chatDbKey = prefs.getString(KEY_CHAT_DB_KEY, null)
+ val userId = getUserId()
prefs.edit().clear().apply()
+ val editor = prefs.edit()
+ if (chatDbKey != null) {
+ editor.putString(KEY_CHAT_DB_KEY, chatDbKey)
+ }
+ if (userId != null) {
+ editor.putLong(KEY_LAST_USER_ID, userId)
+ }
+ editor.apply()
+ }
+
+ fun clearAll() {
+ prefs.edit().clear().apply()
+ }
+
+ fun isSameUser(newUserId: Long): Boolean {
+ val lastId = prefs.getLong(KEY_LAST_USER_ID, -1L)
+ return lastId == -1L || lastId == newUserId
}
fun getEmail(): String? = prefs.getString(KEY_EMAIL, null)
@@ -89,5 +108,6 @@ class CredentialStore(context: Context) {
private const val KEY_SECRET_KEY = "secret_key"
private const val KEY_TOKEN = "token"
private const val KEY_CHAT_DB_KEY = "chat_db_key"
+ private const val KEY_LAST_USER_ID = "last_user_id"
}
}
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 9d77e7ac5b..3285396804 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
@@ -4,10 +4,12 @@ import android.content.Context
import java.io.File
class FilePathManager(context: Context) {
- val attachmentsDir: File = ensureDir(File(context.filesDir, "attachments"))
- val mainDbFile: File = File(context.filesDir, "llmchat.db")
- val attachmentsDbFile: File = File(context.filesDir, "llmchat_attachments.db")
- val syncBaseDir: File = ensureDir(File(context.filesDir, "llmchat"))
+ 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
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 7f883e06d8..f5afc42e7c 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,4 +22,7 @@ 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
index 374a888750..831fdc5d3f 100644
--- 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
@@ -1,6 +1,15 @@
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
new file mode 100644
index 0000000000..0f8f56bba6
--- /dev/null
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/MigrationModels.kt
@@ -0,0 +1,25 @@
+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 33b7af9159..a991b89f8e 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,5 +7,6 @@ data class AppState(
val auth: AuthState = AuthState(),
val chat: ChatState = ChatState(),
val developerSettings: DeveloperSettingsState = DeveloperSettingsState(),
- val modelSettings: ModelSettingsState = ModelSettingsState()
+ val modelSettings: ModelSettingsState = ModelSettingsState(),
+ val sync: SyncState = SyncState.Idle
)
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
new file mode 100644
index 0000000000..089b1141b8
--- /dev/null
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/SyncState.kt
@@ -0,0 +1,8 @@
+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 60ad9ec2b7..78d7013104 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
@@ -43,7 +43,7 @@ class AppStore(
modelSettingsActions = modelSettingsActions
)
private val authActions = AuthStoreActions(_state, logRepository) {
- syncActions.syncNow()
+ syncActions.syncAfterLogin()
}
init {
@@ -111,7 +111,10 @@ class AppStore(
fun signIn(email: String) = authActions.signIn(email)
- fun signOut() = authActions.signOut()
+ fun signOut() {
+ authActions.signOut()
+ chatActions.handleLogout()
+ }
fun syncNow(
onSuccess: (() -> Unit)? = null,
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 a915b0a165..d362b6b71f 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
@@ -53,7 +53,7 @@ internal class ChatStoreActions(
private var overflowBypassMessageId: String? = null
private val sessionSummarySystemPrompt =
- "You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words, no markdown characters, no quotes, no emojis, no trailing punctuation, and output only the title."
+ "You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words. Don't use markdown characters in the title. No quotes, no emojis, no trailing punctuation, and output only the title."
private val sessionSummaryMaxWords = 7
fun setScope(scope: CoroutineScope) {
@@ -373,6 +373,37 @@ internal class ChatStoreActions(
resetGenerationState()
}
+ fun handleLogout() {
+ resetGenerationState()
+ pendingOverflow = null
+ overflowBypassMessageId = null
+ streamingParentId = null
+ messageStore.clear()
+ branchSelections.clear()
+ sessionAccessTimes.clear()
+
+ state.update { appState ->
+ appState.copy(
+ chat = appState.chat.copy(
+ sessions = emptyList(),
+ currentSessionId = null,
+ messages = emptyList(),
+ branchSelections = emptyMap(),
+ messageText = "",
+ attachments = emptyList(),
+ editingMessageId = null,
+ isProcessingAttachments = false,
+ attachmentDownloads = emptyList(),
+ attachmentDownloadProgress = null,
+ isAttachmentDownloadBlocked = false
+ )
+ )
+ }
+
+ attachmentActions.refreshAttachmentDownloadState()
+ loadSessionsFromDb()
+ }
+
fun loadSessionsFromDb() {
val scope = scope ?: return
scope.launch(Dispatchers.IO) {
@@ -731,7 +762,9 @@ internal class ChatStoreActions(
}
val raw = sanitizeTitleText(buffer.toString())
- if (raw.isBlank()) return null
+ if (raw.isBlank()) {
+ return sessionTitleFromText(fallback, fallback = fallback)
+ }
val words = raw.split(" ")
.map { word -> word.trim { ch -> !ch.isLetterOrDigit() } }
.filter { it.isNotBlank() }
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
index b98d6ffe25..93f05c0b7b 100644
--- 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
@@ -3,10 +3,16 @@ 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
@@ -20,6 +26,10 @@ internal class SyncStoreActions(
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
@@ -36,6 +46,47 @@ internal class SyncStoreActions(
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
@@ -86,33 +137,83 @@ internal class SyncStoreActions(
) {
val scope = scope ?: return
scope.launch {
- try {
- logRepository.log(LogLevel.Info, "Sync started", tag = "Sync")
- withContext(Dispatchers.IO) {
- chatSyncRepository?.sync()
+ 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()
}
- reloadSessions?.invoke()
- logRepository.log(LogLevel.Info, "Sync success", tag = "Sync")
- 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))
}
- } catch (err: Throwable) {
- val message = syncErrorMessage(err)
- logRepository.log(
- LogLevel.Error,
- "Sync failed",
- details = message,
- tag = "Sync",
- throwable = err
- )
- if (onError != null) {
- withContext(Dispatchers.Main) {
- onError("Sync failed: $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)) }
}
}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Auth/EmailEntryView.swift b/mobile/native/darwin/Apps/ensu/ensu/Auth/EmailEntryView.swift
index cd2475417a..8ebcb81acb 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Auth/EmailEntryView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Auth/EmailEntryView.swift
@@ -47,7 +47,10 @@ struct EmailEntryView: View {
@MainActor
private func continueTapped() async {
await actionState.run(onError: { error in
- "Failed to get account info: \(error.localizedDescription)"
+ if error is AccountNotFoundError {
+ return "No account found for this email."
+ }
+ return "Failed to get account info: \(error.localizedDescription)"
}) {
let trimmedEmail = email.trimmingCharacters(in: .whitespacesAndNewlines)
let srpAttrs = try await EnsuAuthService.shared.getSrpAttributes(email: trimmedEmail)
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatDataCleaner.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatDataCleaner.swift
new file mode 100644
index 0000000000..ee78075c2f
--- /dev/null
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatDataCleaner.swift
@@ -0,0 +1,41 @@
+import Foundation
+
+enum ChatDataCleaner {
+ static func deleteAllData() {
+ let baseDir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
+ ?? FileManager.default.temporaryDirectory
+ 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 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: 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/ChatViewModel.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift
index 0521ef7569..90ee91b199 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift
@@ -14,6 +14,35 @@ struct SyncAuth {
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 {
@@ -286,14 +315,66 @@ final class LlmChatSync {
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)
+ }
+}
+
@MainActor
final class ChatViewModel: ObservableObject {
private static let defaultTemperature: Float = 0.5
@@ -303,7 +384,7 @@ final class ChatViewModel: ObservableObject {
private static let sessionTitleMaxLength = 40
private static let sessionSummaryMaxWords = 7
private static let sessionSummaryStoreKey = "ensu.session_summaries"
- private static let sessionSummarySystemPrompt = "You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words, no markdown characters, no quotes, no emojis, no trailing punctuation, and output only the title."
+ private static let sessionSummarySystemPrompt = "You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words. Don't use markdown characters in the title. No quotes, no emojis, no trailing punctuation, and output only the title."
private let logger = EnsuLogging.shared.logger("ChatViewModel")
@@ -343,16 +424,33 @@ final class ChatViewModel: ObservableObject {
@Published var hasRequestedModelDownload: 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?
private let provider: InferenceRsProvider
- private let chatDb: LlmChatDb
- private let syncEngine: LlmChatSync
+ private var chatDb: LlmChatDb
+ private var syncEngine: LlmChatSync
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 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]]] = [:]
@@ -393,13 +491,14 @@ final class ChatViewModel: ObservableObject {
let attachmentsDir = dbDir.appendingPathComponent("chat_attachments", isDirectory: true)
try? FileManager.default.createDirectory(at: attachmentsDir, withIntermediateDirectories: true, attributes: nil)
- let key = CredentialStore.shared.getOrCreateChatDbKey()
- let mainDbPath = dbDir.appendingPathComponent("llmchat.db").path
- let attachmentsDbPath = dbDir.appendingPathComponent("llmchat_attachments.db").path
+ 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 chatDb: LlmChatDb
do {
- chatDb = try LlmChatDb.open(mainDbPath: mainDbPath, attachmentsDbPath: attachmentsDbPath, key: key)
+ chatDb = try LlmChatDb.open(mainDbPath: offlineDbPath, attachmentsDbPath: syncDbPath, key: offlineKey)
} catch {
fatalError("Failed to open chat DB: \(error)")
}
@@ -412,9 +511,9 @@ final class ChatViewModel: ObservableObject {
let syncEngine: LlmChatSync
do {
syncEngine = try LlmChatSync.open(
- mainDbPath: mainDbPath,
- attachmentsDbPath: attachmentsDbPath,
- dbKey: key,
+ mainDbPath: offlineDbPath,
+ attachmentsDbPath: syncDbPath,
+ dbKey: offlineKey,
attachmentsDir: encryptedAttachmentsDir.path,
metaDir: syncMetaDir.path,
plaintextDir: attachmentsDir.path
@@ -432,6 +531,12 @@ final class ChatViewModel: ObservableObject {
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.sessionSummaries = summaries
self.sessions = sessions
@@ -452,6 +557,96 @@ final class ChatViewModel: ObservableObject {
refreshModelDownloadInfo()
}
+ 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")
+ 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,
+ attributes: nil
+ )
+
+ chatDb = try LlmChatDb.open(
+ mainDbPath: activeDbPath,
+ attachmentsDbPath: syncDbPath,
+ key: key
+ )
+ syncEngine = try LlmChatSync.open(
+ mainDbPath: activeDbPath,
+ attachmentsDbPath: syncDbPath,
+ dbKey: key,
+ attachmentsDir: encryptedAttachmentsDir.path,
+ metaDir: syncMetaDir.path,
+ plaintextDir: attachmentsDir.path
+ )
+ } catch {
+ logger.error("Failed to reopen sync stores: \(error)")
+ }
+ }
+
+ private func resetOnlineStores() {
+ if FileManager.default.fileExists(atPath: syncDbPath) {
+ try? syncEngine.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
+ )
+ }
+
+ private func prepareOnlineStores(auth: SyncAuth) throws {
+ resetOnlineStores()
+ let chatKey = try fetchChatKey(auth: auth, syncDbPath: syncDbPath)
+ onlineDbKey = chatKey
+ isOnlineMode = true
+ reopenSyncStoresIfNeeded(force: true)
+ try syncEngine.seedFromOffline(offlineDbPath: offlineDbPath, offlineDbKey: offlineDbKey)
+ }
+
+ 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 }
@@ -585,23 +780,81 @@ final class ChatViewModel: ObservableObject {
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 self.prepareOnlineStores(auth: auth)
+ } catch {
+ await MainActor.run {
+ self.syncState = .error("Failed to prepare online chats")
+ }
+ return
+ }
+
+ await MainActor.run {
+ self.reloadFromDb()
+ }
+
+ let syncEngine = 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) {
- let log = logger
+ 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 self.syncEngine.sync(auth: auth)
+ _ = try syncEngine.sync(auth: auth)
log.info("Sync success")
await MainActor.run {
+ self.syncState = .idle
self.reloadFromDb()
if showSuccess {
self.syncSuccessMessage = "Sync complete"
@@ -615,14 +868,55 @@ final class ChatViewModel: ObservableObject {
: message
log.error("Sync failed", error, details: message)
await MainActor.run {
+ self.syncState = .error(userMessage)
if showErrors {
- self.syncErrorMessage = "Sync failed: \(userMessage)"
+ self.syncErrorMessage = formatSyncErrorMessage(userMessage)
}
}
}
}
}
+ private func performBatchedSync(auth: SyncAuth) async {
+ let config = MigrationConfig(batchSize: 25, priority: .recentFirst)
+ await MainActor.run {
+ self.syncState = .migrating(processed: 0, total: 0)
+ }
+
+ do {
+ let handler = MigrationProgressHandler { [weak self] progress in
+ Task { @MainActor in
+ self?.syncState = .migrating(processed: progress.processed, total: progress.total)
+ }
+ }
+ _ = try syncEngine.syncWithProgress(auth: auth, config: config, callback: handler)
+ await MainActor.run {
+ self.syncState = .idle
+ self.reloadFromDb()
+ }
+ } catch {
+ let message = syncErrorMessage(from: error)
+ await MainActor.run {
+ self.syncState = .error(message)
+ self.syncErrorMessage = formatSyncErrorMessage(message)
+ }
+ }
+ }
+
+ func deleteAllData() async {
+ await Task.detached { ChatDataCleaner.deleteAllData() }.value
+ sessions = []
+ messages = []
+ currentSessionId = nil
+ messageStore.removeAll()
+ branchSelections.removeAll()
+ childrenByParentCache.removeAll()
+ attachmentDownloads = []
+ currentSessionMissingAttachments = []
+ syncState = .idle
+ refreshAttachmentDownloadState()
+ }
+
func beginEditing(message: ChatMessage) {
guard message.role == .user else { return }
editingMessageId = message.id
@@ -1260,6 +1554,8 @@ final class ChatViewModel: ObservableObject {
switch syncError {
case let .Message(message):
return message
+ case .SyncInProgress:
+ return "Sync already in progress"
}
}
let description = error.localizedDescription
@@ -1269,6 +1565,14 @@ final class ChatViewModel: ObservableObject {
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]
@@ -1356,9 +1660,11 @@ 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 }
@@ -1372,7 +1678,7 @@ final class ChatViewModel: ObservableObject {
let task = Task.detached { [weak self] in
guard let self else { return }
do {
- _ = try self.syncEngine.downloadAttachment(
+ _ = try syncEngine.downloadAttachment(
attachmentId: id,
sessionUuid: sessionId.uuidString,
auth: auth
@@ -1474,6 +1780,7 @@ final class ChatViewModel: ObservableObject {
}
private func reloadFromDb() {
+ reopenSyncStoresIfNeeded()
let loaded = (try? chatDb.listSessions()) ?? []
let refreshed = Self.buildSessions(from: loaded, chatDb: chatDb, summaries: sessionSummaries)
@@ -1502,6 +1809,7 @@ final class ChatViewModel: ObservableObject {
}
private func loadMessagesFromDb(for sessionId: UUID) {
+ reopenSyncStoresIfNeeded()
if messageStore[sessionId] == nil {
messageStore[sessionId] = []
branchSelections[sessionId] = [:]
@@ -1834,7 +2142,7 @@ final class ChatViewModel: ObservableObject {
}
let raw = sanitizeTitleText(buffer)
- guard !raw.isEmpty else { return nil }
+ guard !raw.isEmpty else { return sessionTitle(from: fallback, fallback: fallback) }
let words = raw.split(separator: " ").map { String($0) }.filter { !$0.isEmpty }
guard !words.isEmpty else { return nil }
let summaryWords = words.prefix(Self.sessionSummaryMaxWords)
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageList/MessageListComponents.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageList/MessageListComponents.swift
index 9322ffe059..dfbe67db60 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageList/MessageListComponents.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageList/MessageListComponents.swift
@@ -123,7 +123,7 @@ struct UserMessageBubbleView: View {
.font(EnsuTypography.message)
.foregroundStyle(EnsuColor.userMessageText)
.lineSpacing(EnsuLineHeight.spacing(fontSize: 15, lineHeight: 1.7))
- .multilineTextAlignment(.trailing)
+ .multilineTextAlignment(.leading)
.textSelection(.enabled)
}
.padding(EnsuSpacing.md)
@@ -581,8 +581,8 @@ struct MarkdownView: View {
let showTrailingCursor = showCursor && (!inlineCursorSupported || blocks.isEmpty)
VStack(alignment: .leading, spacing: EnsuSpacing.md) {
- ForEach(Array(blocks.enumerated()), id: \.element.id) { index, block in
- let isLast = index == blocks.count - 1
+ ForEach(blocks, id: \.id) { (block: MarkdownBlock) in
+ let isLast = block.id == (blocks.last?.id ?? -1)
switch block.kind {
case .heading(let level, let text):
let displayText = showCursor && isLast ? text + StreamingCursor.glyph : text
@@ -603,14 +603,11 @@ struct MarkdownView: View {
case .math(let text):
MathBlockView(text: text)
case .list(let items):
- let resolvedItems: [String]
- if showCursor && isLast {
- resolvedItems = items.enumerated().map { offset, item in
+ let resolvedItems = (showCursor && isLast)
+ ? items.enumerated().map { offset, item in
offset == items.count - 1 ? item + StreamingCursor.glyph : item
}
- } else {
- resolvedItems = items
- }
+ : items
VStack(alignment: .leading, spacing: 6) {
ForEach(resolvedItems, id: \.self) { item in
diff --git a/mobile/native/darwin/Apps/ensu/ensu/FeatureFlags.swift b/mobile/native/darwin/Apps/ensu/ensu/FeatureFlags.swift
index e0c80844fa..7095322899 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/FeatureFlags.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/FeatureFlags.swift
@@ -4,5 +4,6 @@ import Foundation
enum EnsuFeatureFlags {
static let enableSignIn = true
static let enableImageUploads = true
+ static let enableModelSettings = false
}
#endif
diff --git a/mobile/native/darwin/Apps/ensu/ensu/HomeView.swift b/mobile/native/darwin/Apps/ensu/ensu/HomeView.swift
index 55fd0d5c29..e5475addb9 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/HomeView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/HomeView.swift
@@ -13,7 +13,9 @@ struct HomeView: View {
.onChange(of: appState.isLoggedIn) { isLoggedIn in
if isLoggedIn {
isShowingAuth = false
- chatModel.syncNow()
+ chatModel.syncAfterLogin()
+ } else {
+ chatModel.handleLogout()
}
}
}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/CredentialStore.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/CredentialStore.swift
index 2260d2ce09..3d1aa7ffe7 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Services/CredentialStore.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/CredentialStore.swift
@@ -11,6 +11,7 @@ final class CredentialStore {
private enum DefaultsKey {
static let email = "ensu.email"
static let userId = "ensu.userId"
+ static let lastUserId = "ensu.lastUserId"
}
private enum KeychainAccount {
@@ -94,12 +95,33 @@ final class CredentialStore {
}
func clear() {
+ let currentUserId = userId
UserDefaults.standard.removeObject(forKey: DefaultsKey.email)
UserDefaults.standard.removeObject(forKey: DefaultsKey.userId)
+ if let currentUserId {
+ UserDefaults.standard.set(NSNumber(value: currentUserId), forKey: DefaultsKey.lastUserId)
+ }
try? KeychainStore.delete(service: keychainService, account: KeychainAccount.token)
try? KeychainStore.delete(service: keychainService, account: KeychainAccount.masterKey)
try? KeychainStore.delete(service: keychainService, account: KeychainAccount.secretKey)
// Note: keep chatDbKey to preserve local chats across sign-out.
}
+
+ func clearAll() {
+ UserDefaults.standard.removeObject(forKey: DefaultsKey.email)
+ UserDefaults.standard.removeObject(forKey: DefaultsKey.userId)
+ UserDefaults.standard.removeObject(forKey: DefaultsKey.lastUserId)
+
+ try? KeychainStore.delete(service: keychainService, account: KeychainAccount.token)
+ try? KeychainStore.delete(service: keychainService, account: KeychainAccount.masterKey)
+ try? KeychainStore.delete(service: keychainService, account: KeychainAccount.secretKey)
+ try? KeychainStore.delete(service: keychainService, account: KeychainAccount.chatDbKey)
+ }
+
+ func isSameUser(_ newUserId: Int64) -> Bool {
+ let value = UserDefaults.standard.object(forKey: DefaultsKey.lastUserId) as? NSNumber
+ let lastUserId = value?.int64Value
+ return lastUserId == nil || lastUserId == newUserId
+ }
}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/EnsuAppState.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/EnsuAppState.swift
index 57e5d76598..8a0b1250c1 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Services/EnsuAppState.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/EnsuAppState.swift
@@ -14,6 +14,7 @@ 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 cdb22f0f85..c07be3d945 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Services/EnsuAuthService.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/EnsuAuthService.swift
@@ -64,15 +64,22 @@ final class EnsuAuthService {
}
func getSrpAttributes(email: String) async throws -> SrpAttributes {
- let attrs = try await networkFactory.authentication.getSRPAttributes(email: email)
- return SrpAttributes(
- srpUserId: attrs.srpUserID,
- srpSalt: attrs.srpSalt,
- kekSalt: attrs.kekSalt,
- memLimit: UInt32(attrs.memLimit),
- opsLimit: UInt32(attrs.opsLimit),
- isEmailMfaEnabled: attrs.isEmailMFAEnabled
- )
+ do {
+ let attrs = try await networkFactory.authentication.getSRPAttributes(email: email)
+ return SrpAttributes(
+ srpUserId: attrs.srpUserID,
+ srpSalt: attrs.srpSalt,
+ kekSalt: attrs.kekSalt,
+ memLimit: UInt32(attrs.memLimit),
+ opsLimit: UInt32(attrs.opsLimit),
+ isEmailMfaEnabled: attrs.isEmailMFAEnabled
+ )
+ } catch let error as EnteError {
+ if case let .serverError(code, _) = error, code == 404 {
+ throw AccountNotFoundError()
+ }
+ throw error
+ }
}
func sendOtp(email: String) async throws {
@@ -243,6 +250,11 @@ final class EnsuAuthService {
let secretKey = Data(secretKeyBytes)
let token = Data(tokenBytes).base64URLPaddedEncodedString()
+ if !CredentialStore.shared.isSameUser(userId) {
+ CredentialStore.shared.clear()
+ ChatDataCleaner.deleteSyncState()
+ }
+
try CredentialStore.shared.save(
email: email,
userId: userId,
@@ -286,3 +298,4 @@ private extension AuthResponsePayload {
struct PasskeySessionNotVerifiedError: Error {}
struct PasskeySessionExpiredError: Error {}
+struct AccountNotFoundError: Error {}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Settings/DeveloperSettingsView.swift b/mobile/native/darwin/Apps/ensu/ensu/Settings/DeveloperSettingsView.swift
index 831e16930b..0b2fe438a6 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Settings/DeveloperSettingsView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Settings/DeveloperSettingsView.swift
@@ -73,21 +73,23 @@ struct DeveloperSettingsView: View {
private var content: some View {
VStack(alignment: .leading, spacing: EnsuSpacing.xxl) {
- #if os(iOS)
- NavigationLink {
- ModelSettingsView(embeddedInNavigation: true)
- } label: {
- settingsRow(title: "Model settings", subtitle: "Model URL, mmproj, context length")
- }
- .buttonStyle(.plain)
- #else
- Button {
- showModelSettings = true
- } label: {
- settingsRow(title: "Model settings", subtitle: "Model URL, mmproj, context length")
+ if EnsuFeatureFlags.enableModelSettings {
+ #if os(iOS)
+ NavigationLink {
+ ModelSettingsView(embeddedInNavigation: true)
+ } label: {
+ settingsRow(title: "Model settings", subtitle: "Model URL, mmproj, context length")
+ }
+ .buttonStyle(.plain)
+ #else
+ Button {
+ showModelSettings = true
+ } label: {
+ settingsRow(title: "Model settings", subtitle: "Model URL, mmproj, context length")
+ }
+ .buttonStyle(.plain)
+ #endif
}
- .buttonStyle(.plain)
- #endif
VStack(alignment: .leading, spacing: 6) {
Text("Server endpoint")
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Settings/SettingsView.swift b/mobile/native/darwin/Apps/ensu/ensu/Settings/SettingsView.swift
index f36499ed60..65f14c6ff2 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Settings/SettingsView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Settings/SettingsView.swift
@@ -79,7 +79,7 @@ struct SettingsView: View {
}
Button("Cancel", role: .cancel) {}
} message: {
- Text("This will stop syncing on this device.")
+ Text("Signing out will remove your online chats from this device. Offline chats stay available.")
}
}
}
diff --git a/rust/llmchat/db/src/db.rs b/rust/llmchat/db/src/db.rs
index 1a55d3a611..ca529ba99f 100644
--- a/rust/llmchat/db/src/db.rs
+++ b/rust/llmchat/db/src/db.rs
@@ -10,6 +10,14 @@ use crate::models::{AttachmentMeta, EntityType, Message, Sender, Session, Stored
use crate::traits::{Clock, RandomUuidGen, SystemClock, UuidGen};
use crate::{Error, Result};
+const SESSION_NEEDS_SYNC_PREDICATE: &str = "deleted_at IS NULL \
+ AND (needs_sync = 1 OR EXISTS (\
+ SELECT 1 FROM messages \
+ WHERE messages.session_uuid = sessions.session_uuid \
+ AND messages.needs_sync = 1 \
+ AND messages.deleted_at IS NULL\
+ ))";
+
pub struct ChatDb<B: Backend> {
backend: B,
key: Zeroizing<Vec<u8>>,
@@ -66,6 +74,7 @@ impl<B: Backend> ChatDb<B> {
title: title.to_string(),
created_at: now,
updated_at: now,
+ server_updated_at: None,
remote_id: None,
needs_sync: true,
deleted_at: None,
@@ -74,7 +83,7 @@ impl<B: Backend> ChatDb<B> {
pub fn get_session(&self, uuid: Uuid) -> Result<Option<Session>> {
let row = self.backend.query_row(
- "SELECT session_uuid, title, created_at, updated_at, remote_id, needs_sync, deleted_at \
+ "SELECT session_uuid, title, created_at, updated_at, server_updated_at, remote_id, needs_sync, deleted_at \
FROM sessions WHERE session_uuid = ? AND deleted_at IS NULL",
&[Value::Text(uuid.to_string())],
)?;
@@ -84,7 +93,7 @@ impl<B: Backend> ChatDb<B> {
pub fn list_sessions(&self) -> Result<Vec<Session>> {
let rows = self.backend.query(
- "SELECT session_uuid, title, created_at, updated_at, remote_id, needs_sync, deleted_at \
+ "SELECT session_uuid, title, created_at, updated_at, server_updated_at, remote_id, needs_sync, deleted_at \
FROM sessions WHERE deleted_at IS NULL ORDER BY updated_at DESC",
&[],
)?;
@@ -95,7 +104,7 @@ impl<B: Backend> ChatDb<B> {
let now = self.clock.now_us();
let encrypted_title = crypto::encrypt_string(title, &self.key)?;
let affected = self.backend.execute(
- "UPDATE sessions SET title = ?, updated_at = ?, needs_sync = 1 \
+ "UPDATE sessions SET title = ?, updated_at = ?, needs_sync = 1, server_updated_at = NULL \
WHERE session_uuid = ? AND deleted_at IS NULL",
&[
Value::Blob(encrypted_title),
@@ -110,31 +119,99 @@ impl<B: Backend> ChatDb<B> {
let now = self.clock.now_us();
self.backend.transaction(|tx| {
tx.execute(
- "UPDATE messages SET deleted_at = ? WHERE session_uuid = ? AND deleted_at IS NULL",
+ "UPDATE messages SET deleted_at = ?, server_updated_at = NULL WHERE session_uuid = ? AND deleted_at IS NULL",
&[Value::Integer(now), Value::Text(uuid.to_string())],
)?;
let affected = tx.execute(
- "UPDATE sessions SET deleted_at = ? WHERE session_uuid = ? AND deleted_at IS NULL",
+ "UPDATE sessions SET deleted_at = ?, server_updated_at = NULL WHERE session_uuid = ? AND deleted_at IS NULL",
&[Value::Integer(now), Value::Text(uuid.to_string())],
)?;
ensure_row_updated(affected, EntityType::Session, uuid)
})
}
+ pub fn upsert_session(
+ &self,
+ session_uuid: Uuid,
+ title: &str,
+ created_at: i64,
+ updated_at: i64,
+ remote_id: Option<String>,
+ needs_sync: bool,
+ deleted_at: Option<i64>,
+ ) -> Result<Session> {
+ let encrypted_title = crypto::encrypt_string(title, &self.key)?;
+ let needs_sync_value = if needs_sync { 1 } else { 0 };
+ let remote_value = remote_id.map(Value::Text).unwrap_or(Value::Null);
+ let deleted_value = deleted_at.map(Value::Integer).unwrap_or(Value::Null);
+
+ self.backend.execute(
+ "INSERT INTO sessions (session_uuid, title, created_at, updated_at, remote_id, needs_sync, deleted_at) \
+ VALUES (?, ?, ?, ?, ?, ?, ?) \
+ ON CONFLICT(session_uuid) DO UPDATE SET \
+ title = excluded.title, \
+ created_at = excluded.created_at, \
+ updated_at = excluded.updated_at, \
+ remote_id = COALESCE(excluded.remote_id, sessions.remote_id), \
+ needs_sync = excluded.needs_sync, \
+ deleted_at = excluded.deleted_at",
+ &[
+ Value::Text(session_uuid.to_string()),
+ Value::Blob(encrypted_title),
+ Value::Integer(created_at),
+ Value::Integer(updated_at),
+ remote_value,
+ Value::Integer(needs_sync_value),
+ deleted_value,
+ ],
+ )?;
+
+ let row = self.backend.query_row(
+ "SELECT session_uuid, title, created_at, updated_at, server_updated_at, remote_id, needs_sync, deleted_at \
+ FROM sessions WHERE session_uuid = ?",
+ &[Value::Text(session_uuid.to_string())],
+ )?;
+ let row = row.ok_or(Error::NotFound {
+ entity: EntityType::Session,
+ id: session_uuid,
+ })?;
+ self.session_from_row(&row)
+ }
+
pub fn get_sessions_needing_sync(&self) -> Result<Vec<Session>> {
- let rows = self.backend.query(
- "SELECT session_uuid, title, created_at, updated_at, remote_id, needs_sync, deleted_at \
+ let query = format!(
+ "SELECT session_uuid, title, created_at, updated_at, server_updated_at, remote_id, needs_sync, deleted_at \
FROM sessions \
- WHERE deleted_at IS NULL \
- AND (needs_sync = 1 OR EXISTS (\
- SELECT 1 FROM messages \
- WHERE messages.session_uuid = sessions.session_uuid \
- AND messages.needs_sync = 1 \
- AND messages.deleted_at IS NULL\
- )) \
- ORDER BY updated_at DESC",
- &[],
- )?;
+ WHERE {SESSION_NEEDS_SYNC_PREDICATE} \
+ ORDER BY updated_at DESC"
+ );
+ let rows = self.backend.query(&query, &[])?;
+ rows.iter().map(|row| self.session_from_row(row)).collect()
+ }
+
+ pub fn count_needing_sync(&self) -> Result<i64> {
+ let query = format!("SELECT COUNT(*) FROM sessions WHERE {SESSION_NEEDS_SYNC_PREDICATE}");
+ let row = self.backend.query_row(&query, &[])?;
+ Ok(row.map(|row| row.get_i64(0)).transpose()?.unwrap_or(0))
+ }
+
+ pub fn get_sessions_needing_sync_batch(
+ &self,
+ limit: i64,
+ order_desc: bool,
+ ) -> Result<Vec<Session>> {
+ if limit <= 0 {
+ return Ok(Vec::new());
+ }
+ let order_clause = if order_desc { "DESC" } else { "ASC" };
+ let query = format!(
+ "SELECT session_uuid, title, created_at, updated_at, server_updated_at, remote_id, needs_sync, deleted_at \
+ FROM sessions \
+ WHERE {SESSION_NEEDS_SYNC_PREDICATE} \
+ ORDER BY updated_at {order_clause} \
+ LIMIT ?"
+ );
+ let rows = self.backend.query(&query, &[Value::Integer(limit)])?;
rows.iter().map(|row| self.session_from_row(row)).collect()
}
@@ -183,14 +260,70 @@ impl<B: Backend> ChatDb<B> {
text: text.to_string(),
attachments,
created_at: now,
+ remote_id: None,
+ server_updated_at: None,
needs_sync: true,
deleted_at: None,
})
}
+ pub fn insert_message_with_uuid_and_state(
+ &self,
+ message_uuid: Uuid,
+ session_uuid: Uuid,
+ sender: &str,
+ text: &str,
+ parent: Option<Uuid>,
+ attachments: Vec<AttachmentMeta>,
+ created_at: i64,
+ deleted_at: Option<i64>,
+ needs_sync: bool,
+ ) -> Result<Message> {
+ let sender: Sender = sender.parse()?;
+ let encrypted_text = crypto::encrypt_string(text, &self.key)?;
+ let attachments_json = self.serialize_attachments(&attachments)?;
+ let deleted_value = deleted_at.map(Value::Integer).unwrap_or(Value::Null);
+ let needs_sync_value = if needs_sync { 1 } else { 0 };
+
+ self.backend.execute(
+ "INSERT INTO messages (message_uuid, session_uuid, parent_message_uuid, sender, text, attachments, created_at, remote_id, server_updated_at, needs_sync, deleted_at) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?) \
+ ON CONFLICT(message_uuid) DO NOTHING",
+ &[
+ Value::Text(message_uuid.to_string()),
+ Value::Text(session_uuid.to_string()),
+ parent
+ .map(|value| Value::Text(value.to_string()))
+ .unwrap_or(Value::Null),
+ Value::Text(sender.as_str().to_string()),
+ Value::Blob(encrypted_text),
+ attachments_json
+ .map(Value::Text)
+ .unwrap_or(Value::Null),
+ Value::Integer(created_at),
+ Value::Integer(needs_sync_value),
+ deleted_value,
+ ],
+ )?;
+
+ Ok(Message {
+ uuid: message_uuid,
+ session_uuid,
+ parent_message_uuid: parent,
+ sender,
+ text: text.to_string(),
+ attachments,
+ created_at,
+ remote_id: None,
+ server_updated_at: None,
+ needs_sync,
+ deleted_at,
+ })
+ }
+
pub fn get_messages(&self, session_uuid: Uuid) -> Result<Vec<Message>> {
let rows = self.backend.query(
- "SELECT message_uuid, session_uuid, parent_message_uuid, sender, text, attachments, created_at, needs_sync, deleted_at \
+ "SELECT message_uuid, session_uuid, parent_message_uuid, sender, text, attachments, created_at, remote_id, server_updated_at, needs_sync, deleted_at \
FROM messages WHERE session_uuid = ? AND deleted_at IS NULL ORDER BY created_at ASC, message_uuid ASC",
&[Value::Text(session_uuid.to_string())],
)?;
@@ -199,7 +332,7 @@ impl<B: Backend> ChatDb<B> {
pub fn get_messages_needing_sync(&self, session_uuid: Uuid) -> Result<Vec<Message>> {
let rows = self.backend.query(
- "SELECT message_uuid, session_uuid, parent_message_uuid, sender, text, attachments, created_at, needs_sync, deleted_at \
+ "SELECT message_uuid, session_uuid, parent_message_uuid, sender, text, attachments, created_at, remote_id, server_updated_at, needs_sync, deleted_at \
FROM messages WHERE session_uuid = ? AND needs_sync = 1 AND deleted_at IS NULL ORDER BY created_at ASC, message_uuid ASC",
&[Value::Text(session_uuid.to_string())],
)?;
@@ -221,7 +354,7 @@ impl<B: Backend> ChatDb<B> {
let session_uuid = Uuid::parse_str(&row.get_string(0)?)?;
let affected = tx.execute(
- "UPDATE messages SET text = ?, needs_sync = 1 WHERE message_uuid = ? AND deleted_at IS NULL",
+ "UPDATE messages SET text = ?, needs_sync = 1, server_updated_at = NULL WHERE message_uuid = ? AND deleted_at IS NULL",
&[Value::Blob(encrypted_text), Value::Text(uuid.to_string())],
)?;
ensure_row_updated(affected, EntityType::Message, uuid)?;
@@ -244,7 +377,7 @@ impl<B: Backend> ChatDb<B> {
let session_uuid = Uuid::parse_str(&row.get_string(0)?)?;
let affected = tx.execute(
- "UPDATE messages SET deleted_at = ? WHERE message_uuid = ? AND deleted_at IS NULL",
+ "UPDATE messages SET deleted_at = ?, server_updated_at = NULL WHERE message_uuid = ? AND deleted_at IS NULL",
&[Value::Integer(now), Value::Text(uuid.to_string())],
)?;
ensure_row_updated(affected, EntityType::Message, uuid)?;
@@ -264,6 +397,98 @@ impl<B: Backend> ChatDb<B> {
ensure_row_updated(affected, EntityType::Session, uuid)
}
+ pub fn get_session_remote_id(&self, uuid: Uuid) -> Result<Option<String>> {
+ let row = self.backend.query_row(
+ "SELECT remote_id FROM sessions WHERE session_uuid = ?",
+ &[Value::Text(uuid.to_string())],
+ )?;
+ let remote_id = match row {
+ Some(row) => row.get_optional_string(0)?,
+ None => None,
+ };
+ Ok(remote_id)
+ }
+
+ pub fn set_session_remote_id(&self, uuid: Uuid, remote_id: &str) -> Result<()> {
+ let affected = self.backend.execute(
+ "UPDATE sessions SET remote_id = ? WHERE session_uuid = ?",
+ &[
+ Value::Text(remote_id.to_string()),
+ Value::Text(uuid.to_string()),
+ ],
+ )?;
+ ensure_row_updated(affected, EntityType::Session, uuid)
+ }
+
+ pub fn get_session_uuid_by_remote_id(&self, remote_id: &str) -> Result<Option<Uuid>> {
+ let row = self.backend.query_row(
+ "SELECT session_uuid FROM sessions WHERE remote_id = ?",
+ &[Value::Text(remote_id.to_string())],
+ )?;
+ let uuid = match row {
+ Some(row) => {
+ let value = row.get_string(0)?;
+ Some(Uuid::parse_str(&value)?)
+ }
+ None => None,
+ };
+ Ok(uuid)
+ }
+
+ pub fn set_session_server_updated_at(&self, uuid: Uuid, updated_at: i64) -> Result<()> {
+ let affected = self.backend.execute(
+ "UPDATE sessions SET server_updated_at = ? WHERE session_uuid = ?",
+ &[Value::Integer(updated_at), Value::Text(uuid.to_string())],
+ )?;
+ ensure_row_updated(affected, EntityType::Session, uuid)
+ }
+
+ pub fn set_message_server_updated_at(&self, uuid: Uuid, updated_at: i64) -> Result<()> {
+ let affected = self.backend.execute(
+ "UPDATE messages SET server_updated_at = ? WHERE message_uuid = ?",
+ &[Value::Integer(updated_at), Value::Text(uuid.to_string())],
+ )?;
+ ensure_row_updated(affected, EntityType::Message, uuid)
+ }
+
+ pub fn set_message_remote_id(&self, uuid: Uuid, remote_id: &str) -> Result<()> {
+ let affected = self.backend.execute(
+ "UPDATE messages SET remote_id = ? WHERE message_uuid = ?",
+ &[
+ Value::Text(remote_id.to_string()),
+ Value::Text(uuid.to_string()),
+ ],
+ )?;
+ ensure_row_updated(affected, EntityType::Message, uuid)
+ }
+
+ pub fn get_message_remote_id(&self, uuid: Uuid) -> Result<Option<String>> {
+ let row = self.backend.query_row(
+ "SELECT remote_id FROM messages WHERE message_uuid = ?",
+ &[Value::Text(uuid.to_string())],
+ )?;
+ let remote_id = match row {
+ Some(row) => row.get_optional_string(0)?,
+ None => None,
+ };
+ Ok(remote_id)
+ }
+
+ pub fn get_message_uuid_by_remote_id(&self, remote_id: &str) -> Result<Option<Uuid>> {
+ let row = self.backend.query_row(
+ "SELECT message_uuid FROM messages WHERE remote_id = ?",
+ &[Value::Text(remote_id.to_string())],
+ )?;
+ let uuid = match row {
+ Some(row) => {
+ let value = row.get_string(0)?;
+ Some(Uuid::parse_str(&value)?)
+ }
+ None => None,
+ };
+ Ok(uuid)
+ }
+
pub fn mark_all_needs_sync(&self) -> Result<()> {
self.backend.execute(
"UPDATE sessions SET needs_sync = 1 WHERE deleted_at IS NULL",
@@ -276,6 +501,28 @@ impl<B: Backend> ChatDb<B> {
Ok(())
}
+ pub fn clear_all_server_timestamps(&self) -> Result<()> {
+ self.backend
+ .execute("UPDATE sessions SET server_updated_at = NULL", &[])?;
+ self.backend
+ .execute("UPDATE messages SET server_updated_at = NULL", &[])?;
+ Ok(())
+ }
+
+ pub fn reset_sync_state(&self) -> Result<()> {
+ self.backend.execute(
+ "UPDATE sessions SET remote_id = NULL, server_updated_at = NULL, \
+ needs_sync = CASE WHEN deleted_at IS NULL THEN 1 ELSE needs_sync END",
+ &[],
+ )?;
+ self.backend.execute(
+ "UPDATE messages SET remote_id = NULL, server_updated_at = NULL, \
+ needs_sync = CASE WHEN deleted_at IS NULL THEN 1 ELSE needs_sync END",
+ &[],
+ )?;
+ Ok(())
+ }
+
pub fn mark_message_synced(&self, uuid: Uuid) -> Result<()> {
let affected = self.backend.execute(
"UPDATE messages SET needs_sync = 0 WHERE message_uuid = ? AND deleted_at IS NULL",
@@ -287,6 +534,7 @@ impl<B: Backend> ChatDb<B> {
pub fn upsert_session_from_remote(
&self,
session_uuid: Uuid,
+ remote_id: &str,
title: &str,
created_at: i64,
updated_at: i64,
@@ -307,7 +555,7 @@ impl<B: Backend> ChatDb<B> {
Value::Blob(encrypted_title),
Value::Integer(created_at),
Value::Integer(updated_at),
- Value::Text(session_uuid.to_string()),
+ Value::Text(remote_id.to_string()),
],
)?;
@@ -342,6 +590,7 @@ impl<B: Backend> ChatDb<B> {
&self,
message_uuid: Uuid,
session_uuid: Uuid,
+ remote_id: &str,
sender: &str,
text: &str,
parent: Option<Uuid>,
@@ -353,8 +602,8 @@ impl<B: Backend> ChatDb<B> {
let attachments_json = self.serialize_attachments(&attachments)?;
self.backend.execute(
- "INSERT INTO messages (message_uuid, session_uuid, parent_message_uuid, sender, text, attachments, created_at, needs_sync, deleted_at) \
- VALUES (?, ?, ?, ?, ?, ?, ?, 0, NULL) \
+ "INSERT INTO messages (message_uuid, session_uuid, parent_message_uuid, sender, text, attachments, created_at, remote_id, needs_sync, deleted_at) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, NULL) \
ON CONFLICT(message_uuid) DO UPDATE SET \
session_uuid = excluded.session_uuid, \
parent_message_uuid = excluded.parent_message_uuid, \
@@ -362,6 +611,7 @@ impl<B: Backend> ChatDb<B> {
text = excluded.text, \
attachments = excluded.attachments, \
created_at = MIN(messages.created_at, excluded.created_at), \
+ remote_id = COALESCE(messages.remote_id, excluded.remote_id), \
needs_sync = CASE WHEN messages.needs_sync = 1 THEN 1 ELSE excluded.needs_sync END, \
deleted_at = NULL",
&[
@@ -376,6 +626,7 @@ impl<B: Backend> ChatDb<B> {
.map(Value::Text)
.unwrap_or(Value::Null),
Value::Integer(created_at),
+ Value::Text(remote_id.to_string()),
],
)?;
@@ -389,6 +640,8 @@ impl<B: Backend> ChatDb<B> {
text: text.to_string(),
attachments,
created_at,
+ remote_id: Some(remote_id.to_string()),
+ server_updated_at: None,
needs_sync: false,
deleted_at: None,
})
@@ -436,6 +689,39 @@ impl<B: Backend> ChatDb<B> {
Ok(deletions)
}
+ pub fn get_deleted_sessions(&self) -> Result<Vec<(Uuid, i64)>> {
+ let rows = self.backend.query(
+ "SELECT session_uuid, deleted_at FROM sessions WHERE deleted_at IS NOT NULL ORDER BY deleted_at ASC",
+ &[],
+ )?;
+ rows.iter()
+ .map(|row| {
+ let uuid = Uuid::parse_str(&row.get_string(0)?)?;
+ let deleted_at = row.get_i64(1)?;
+ Ok((uuid, deleted_at))
+ })
+ .collect()
+ }
+
+ pub fn get_deleted_messages(&self) -> Result<Vec<(Uuid, i64)>> {
+ let rows = self.backend.query(
+ "SELECT messages.message_uuid, messages.deleted_at \
+ FROM messages \
+ JOIN sessions ON messages.session_uuid = sessions.session_uuid \
+ WHERE messages.deleted_at IS NOT NULL \
+ AND sessions.deleted_at IS NULL \
+ ORDER BY messages.deleted_at ASC",
+ &[],
+ )?;
+ rows.iter()
+ .map(|row| {
+ let uuid = Uuid::parse_str(&row.get_string(0)?)?;
+ let deleted_at = row.get_i64(1)?;
+ Ok((uuid, deleted_at))
+ })
+ .collect()
+ }
+
pub fn hard_delete(&self, entity_type: EntityType, uuid: Uuid) -> Result<()> {
match entity_type {
EntityType::Session => {
@@ -460,14 +746,16 @@ impl<B: Backend> ChatDb<B> {
let title = crypto::decrypt_string(&title_blob, &self.key)?;
let created_at = row.get_i64(2)?;
let updated_at = row.get_i64(3)?;
- let remote_id = row.get_optional_string(4)?;
- let needs_sync = bool_from_i64(row.get_i64(5)?)?;
- let deleted_at = row.get_optional_i64(6)?;
+ let server_updated_at = row.get_optional_i64(4)?;
+ let remote_id = row.get_optional_string(5)?;
+ let needs_sync = bool_from_i64(row.get_i64(6)?)?;
+ let deleted_at = row.get_optional_i64(7)?;
Ok(Session {
uuid,
title,
created_at,
updated_at,
+ server_updated_at,
remote_id,
needs_sync,
deleted_at,
@@ -487,8 +775,10 @@ impl<B: Backend> ChatDb<B> {
let attachments_json = row.get_optional_string(5)?;
let attachments = self.deserialize_attachments(attachments_json)?;
let created_at = row.get_i64(6)?;
- let needs_sync = bool_from_i64(row.get_i64(7)?)?;
- let deleted_at = row.get_optional_i64(8)?;
+ let remote_id = row.get_optional_string(7)?;
+ let server_updated_at = row.get_optional_i64(8)?;
+ let needs_sync = bool_from_i64(row.get_i64(9)?)?;
+ let deleted_at = row.get_optional_i64(10)?;
Ok(Message {
uuid,
@@ -498,6 +788,8 @@ impl<B: Backend> ChatDb<B> {
text,
attachments,
created_at,
+ remote_id,
+ server_updated_at,
needs_sync,
deleted_at,
})
@@ -547,7 +839,7 @@ impl<B: Backend> ChatDb<B> {
updated_at: i64,
) -> Result<()> {
let affected = backend.execute(
- "UPDATE sessions SET updated_at = ?, needs_sync = 1 WHERE session_uuid = ? AND deleted_at IS NULL",
+ "UPDATE sessions SET updated_at = ?, needs_sync = 1, server_updated_at = NULL WHERE session_uuid = ? AND deleted_at IS NULL",
&[Value::Integer(updated_at), Value::Text(session_uuid.to_string())],
)?;
ensure_row_updated(affected, EntityType::Session, session_uuid)
diff --git a/rust/llmchat/db/src/lib.rs b/rust/llmchat/db/src/lib.rs
index 09ba43bd32..54c7a9e60d 100644
--- a/rust/llmchat/db/src/lib.rs
+++ b/rust/llmchat/db/src/lib.rs
@@ -11,6 +11,8 @@ pub mod llmchat;
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};
@@ -19,6 +21,7 @@ pub use crate::db::ChatDb;
pub use crate::error::{Error, Result};
pub use crate::llmchat::LlmChatDb;
pub use crate::models::{AttachmentKind, AttachmentMeta, EntityType, Message, Sender, Session};
+pub use crate::sync_state_db::{SyncEntityState, SyncStateDb};
pub use crate::traits::{
AttachmentStore, Clock, FileMetaStore, FsAttachmentStore, MetaStore, RandomUuidGen,
SystemClock, UuidGen,
diff --git a/rust/llmchat/db/src/llmchat.rs b/rust/llmchat/db/src/llmchat.rs
index 3e592b2828..b2b9793eb6 100644
--- a/rust/llmchat/db/src/llmchat.rs
+++ b/rust/llmchat/db/src/llmchat.rs
@@ -43,6 +43,27 @@ impl<B: crate::Backend> LlmChatDb<B> {
self.chat.delete_session(uuid)
}
+ pub fn upsert_session(
+ &self,
+ session_uuid: Uuid,
+ title: &str,
+ created_at: i64,
+ updated_at: i64,
+ remote_id: Option<String>,
+ needs_sync: bool,
+ deleted_at: Option<i64>,
+ ) -> Result<Session> {
+ self.chat.upsert_session(
+ session_uuid,
+ title,
+ created_at,
+ updated_at,
+ remote_id,
+ needs_sync,
+ deleted_at,
+ )
+ }
+
pub fn insert_message(
&self,
session_uuid: Uuid,
@@ -67,6 +88,31 @@ impl<B: crate::Backend> LlmChatDb<B> {
Ok(message)
}
+ pub fn insert_message_with_uuid_and_state(
+ &self,
+ message_uuid: Uuid,
+ session_uuid: Uuid,
+ sender: &str,
+ text: &str,
+ parent: Option<Uuid>,
+ attachments: Vec<AttachmentMeta>,
+ created_at: i64,
+ deleted_at: Option<i64>,
+ needs_sync: bool,
+ ) -> Result<Message> {
+ self.chat.insert_message_with_uuid_and_state(
+ message_uuid,
+ session_uuid,
+ sender,
+ text,
+ parent,
+ attachments,
+ created_at,
+ deleted_at,
+ needs_sync,
+ )
+ }
+
pub fn get_messages(&self, session_uuid: Uuid) -> Result<Vec<Message>> {
self.chat.get_messages(session_uuid)
}
@@ -142,18 +188,70 @@ impl<B: crate::Backend> LlmChatDb<B> {
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)
}
@@ -162,12 +260,13 @@ impl<B: crate::Backend> LlmChatDb<B> {
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, title, created_at, updated_at)
+ .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<()> {
@@ -178,6 +277,7 @@ impl<B: crate::Backend> LlmChatDb<B> {
&self,
message_uuid: Uuid,
session_uuid: Uuid,
+ remote_id: &str,
sender: &str,
text: &str,
parent: Option<Uuid>,
@@ -187,6 +287,7 @@ impl<B: crate::Backend> LlmChatDb<B> {
self.chat.upsert_message_from_remote(
message_uuid,
session_uuid,
+ remote_id,
sender,
text,
parent,
@@ -239,6 +340,16 @@ impl<B: crate::Backend> LlmChatDb<B> {
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()
}
diff --git a/rust/llmchat/db/src/migrations.rs b/rust/llmchat/db/src/migrations.rs
index 32b2054829..6cc7968511 100644
--- a/rust/llmchat/db/src/migrations.rs
+++ b/rust/llmchat/db/src/migrations.rs
@@ -1,93 +1,57 @@
-use crate::backend::{RowExt, Value};
+use crate::backend::RowExt;
use crate::schema;
use crate::{Backend, Error, Result};
-pub const LATEST_VERSION: i64 = 2;
+pub const LATEST_VERSION: i64 = 4;
pub fn migrate<B: Backend>(backend: &B) -> Result<()> {
- let version = user_version(backend)?;
- let mut updated = false;
- match version {
- 0 => {
- backend.execute_batch(schema::CREATE_ALL)?;
- updated = true;
+ let mut version = user_version(backend)?;
+
+ while version < LATEST_VERSION {
+ match version {
+ 0 => {
+ backend.execute_batch(schema::CREATE_ALL)?;
+ version = LATEST_VERSION;
+ }
+ 1 => {
+ backend.execute(
+ "ALTER TABLE messages ADD COLUMN needs_sync INTEGER NOT NULL DEFAULT 1 CHECK(needs_sync IN (0,1));",
+ &[],
+ )?;
+ backend.execute(
+ "UPDATE messages SET needs_sync = 0 WHERE session_uuid IN (SELECT session_uuid FROM sessions WHERE needs_sync = 0);",
+ &[],
+ )?;
+ version = 2;
+ }
+ 2 => {
+ backend.execute(
+ "ALTER TABLE sessions ADD COLUMN server_updated_at INTEGER;",
+ &[],
+ )?;
+ backend.execute(
+ "ALTER TABLE messages ADD COLUMN server_updated_at INTEGER;",
+ &[],
+ )?;
+ version = 3;
+ }
+ 3 => {
+ backend.execute("ALTER TABLE messages ADD COLUMN remote_id TEXT;", &[])?;
+ version = 4;
+ }
+ other => {
+ return Err(Error::Migration(format!(
+ "unsupported schema version {other}"
+ )));
+ }
}
- 1 => {
- backend.execute(
- "ALTER TABLE messages ADD COLUMN needs_sync INTEGER NOT NULL DEFAULT 1 CHECK(needs_sync IN (0,1));",
- &[],
- )?;
- backend.execute(
- "UPDATE messages SET needs_sync = 0 WHERE session_uuid IN (SELECT session_uuid FROM sessions WHERE needs_sync = 0);",
- &[],
- )?;
- updated = true;
- }
- LATEST_VERSION => {}
- other => {
- return Err(Error::Migration(format!(
- "unsupported schema version {other}"
- )));
- }
- }
-
- if ensure_needs_sync_columns(backend)? {
- updated = true;
- }
- if updated {
- backend.execute("PRAGMA user_version = 2;", &[])?;
+ backend.execute(&format!("PRAGMA user_version = {version};"), &[])?;
}
Ok(())
}
-fn ensure_needs_sync_columns<B: Backend>(backend: &B) -> Result<bool> {
- if !table_exists(backend, "sessions")? || !table_exists(backend, "messages")? {
- return Ok(false);
- }
-
- let mut updated = false;
- if !column_exists(backend, "sessions", "needs_sync")? {
- backend.execute(
- "ALTER TABLE sessions ADD COLUMN needs_sync INTEGER NOT NULL DEFAULT 1 CHECK(needs_sync IN (0,1));",
- &[],
- )?;
- updated = true;
- }
-
- if !column_exists(backend, "messages", "needs_sync")? {
- backend.execute(
- "ALTER TABLE messages ADD COLUMN needs_sync INTEGER NOT NULL DEFAULT 1 CHECK(needs_sync IN (0,1));",
- &[],
- )?;
- backend.execute(
- "UPDATE messages SET needs_sync = 0 WHERE session_uuid IN (SELECT session_uuid FROM sessions WHERE needs_sync = 0);",
- &[],
- )?;
- updated = true;
- }
-
- Ok(updated)
-}
-
-fn column_exists<B: Backend>(backend: &B, table: &str, column: &str) -> Result<bool> {
- let rows = backend.query(&format!("PRAGMA table_info({table});"), &[])?;
- Ok(rows.iter().any(|row| match row.get(1) {
- Some(Value::Text(name)) => name == column,
- _ => false,
- }))
-}
-
-fn table_exists<B: Backend>(backend: &B, table: &str) -> Result<bool> {
- Ok(backend
- .query_row(
- "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",
- &[Value::Text(table.to_string())],
- )?
- .is_some())
-}
-
fn user_version<B: Backend>(backend: &B) -> Result<i64> {
let row = backend
.query_row("PRAGMA user_version;", &[])?
diff --git a/rust/llmchat/db/src/models.rs b/rust/llmchat/db/src/models.rs
index 4404421012..b735631355 100644
--- a/rust/llmchat/db/src/models.rs
+++ b/rust/llmchat/db/src/models.rs
@@ -7,6 +7,7 @@ pub struct Session {
pub title: String,
pub created_at: i64,
pub updated_at: i64,
+ pub server_updated_at: Option<i64>,
pub remote_id: Option<String>,
pub needs_sync: bool,
pub deleted_at: Option<i64>,
@@ -21,6 +22,8 @@ pub struct Message {
pub text: String,
pub attachments: Vec<AttachmentMeta>,
pub created_at: i64,
+ pub remote_id: Option<String>,
+ pub server_updated_at: Option<i64>,
pub needs_sync: bool,
pub deleted_at: Option<i64>,
}
diff --git a/rust/llmchat/db/src/schema.rs b/rust/llmchat/db/src/schema.rs
index 7e40d05ccf..3a9580f317 100644
--- a/rust/llmchat/db/src/schema.rs
+++ b/rust/llmchat/db/src/schema.rs
@@ -2,13 +2,14 @@ pub const PRAGMA_FOREIGN_KEYS: &str = "PRAGMA foreign_keys = ON;";
pub const CREATE_SESSIONS: &str = "
CREATE TABLE IF NOT EXISTS sessions (
- session_uuid TEXT PRIMARY KEY NOT NULL,
- title BLOB NOT NULL,
- created_at INTEGER NOT NULL,
- updated_at INTEGER NOT NULL,
- remote_id TEXT UNIQUE,
- needs_sync INTEGER NOT NULL DEFAULT 1 CHECK(needs_sync IN (0,1)),
- deleted_at INTEGER
+ session_uuid TEXT PRIMARY KEY NOT NULL,
+ title BLOB NOT NULL,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL,
+ server_updated_at INTEGER,
+ remote_id TEXT UNIQUE,
+ needs_sync INTEGER NOT NULL DEFAULT 1 CHECK(needs_sync IN (0,1)),
+ deleted_at INTEGER
);
";
@@ -21,6 +22,8 @@ CREATE TABLE IF NOT EXISTS messages (
text BLOB NOT NULL,
attachments TEXT,
created_at INTEGER NOT NULL,
+ remote_id TEXT,
+ server_updated_at INTEGER,
needs_sync INTEGER NOT NULL DEFAULT 1 CHECK(needs_sync IN (0,1)),
deleted_at INTEGER,
FOREIGN KEY (session_uuid) REFERENCES sessions(session_uuid) ON DELETE CASCADE
@@ -36,13 +39,14 @@ pub const CREATE_ALL: &str = "
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS sessions (
- session_uuid TEXT PRIMARY KEY NOT NULL,
- title BLOB NOT NULL,
- created_at INTEGER NOT NULL,
- updated_at INTEGER NOT NULL,
- remote_id TEXT UNIQUE,
- needs_sync INTEGER NOT NULL DEFAULT 1 CHECK(needs_sync IN (0,1)),
- deleted_at INTEGER
+ session_uuid TEXT PRIMARY KEY NOT NULL,
+ title BLOB NOT NULL,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL,
+ server_updated_at INTEGER,
+ remote_id TEXT UNIQUE,
+ needs_sync INTEGER NOT NULL DEFAULT 1 CHECK(needs_sync IN (0,1)),
+ deleted_at INTEGER
);
CREATE TABLE IF NOT EXISTS messages (
@@ -53,6 +57,8 @@ CREATE TABLE IF NOT EXISTS messages (
text BLOB NOT NULL,
attachments TEXT,
created_at INTEGER NOT NULL,
+ remote_id TEXT,
+ server_updated_at INTEGER,
needs_sync INTEGER NOT NULL DEFAULT 1 CHECK(needs_sync IN (0,1)),
deleted_at INTEGER,
FOREIGN KEY (session_uuid) REFERENCES sessions(session_uuid) ON DELETE CASCADE
diff --git a/rust/llmchat/db/src/sync_state_db.rs b/rust/llmchat/db/src/sync_state_db.rs
new file mode 100644
index 0000000000..6334e54b96
--- /dev/null
+++ b/rust/llmchat/db/src/sync_state_db.rs
@@ -0,0 +1,230 @@
+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/llmchat/db/src/sync_state_schema.rs b/rust/llmchat/db/src/sync_state_schema.rs
new file mode 100644
index 0000000000..7f4d311b10
--- /dev/null
+++ b/rust/llmchat/db/src/sync_state_schema.rs
@@ -0,0 +1,49 @@
+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/llmchat/sync/src/conflict.rs b/rust/llmchat/sync/src/conflict.rs
index 09152b2c2b..dc3a3e4240 100644
--- a/rust/llmchat/sync/src/conflict.rs
+++ b/rust/llmchat/sync/src/conflict.rs
@@ -3,6 +3,79 @@ use std::collections::{HashMap, HashSet};
use llmchat_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,
@@ -117,6 +190,8 @@ mod tests {
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,
};
diff --git a/rust/llmchat/sync/src/errors.rs b/rust/llmchat/sync/src/errors.rs
index 1a385f6a98..aa04f3248d 100644
--- a/rust/llmchat/sync/src/errors.rs
+++ b/rust/llmchat/sync/src/errors.rs
@@ -27,6 +27,8 @@ pub enum SyncError {
AttachmentMissing(String),
#[error("invalid response: {0}")]
InvalidResponse(String),
+ #[error("sync already in progress")]
+ SyncInProgress,
#[error("serde error: {0}")]
Serde(String),
#[error("io error: {0}")]
diff --git a/rust/llmchat/sync/src/lib.rs b/rust/llmchat/sync/src/lib.rs
index 78f8de0660..ef465fd53c 100644
--- a/rust/llmchat/sync/src/lib.rs
+++ b/rust/llmchat/sync/src/lib.rs
@@ -7,4 +7,7 @@ pub mod models;
pub mod sync;
pub use errors::SyncError;
-pub use sync::{SyncAuth, SyncEngine, SyncResult, SyncStats};
+pub use sync::{
+ MigrationConfig, MigrationPriority, MigrationProgress, MigrationProgressCallback,
+ MigrationState, SyncAuth, SyncEngine, SyncResult, SyncStats, fetch_chat_key,
+};
diff --git a/rust/llmchat/sync/src/models.rs b/rust/llmchat/sync/src/models.rs
index dd1cc76487..34c36e0dee 100644
--- a/rust/llmchat/sync/src/models.rs
+++ b/rust/llmchat/sync/src/models.rs
@@ -56,10 +56,6 @@ impl ChatKeyPayload {
pub struct RemoteSession {
#[serde(rename = "sessionUUID", alias = "session_uuid")]
pub session_uuid: String,
- #[serde(rename = "rootSessionUUID", alias = "root_session_uuid")]
- pub root_session_uuid: Option<String>,
- #[serde(rename = "branchFromMessageUUID", alias = "branch_from_message_uuid")]
- pub branch_from_message_uuid: Option<String>,
#[serde(rename = "encryptedData", alias = "encrypted_data")]
pub encrypted_data: String,
pub header: String,
diff --git a/rust/llmchat/sync/src/sync.rs b/rust/llmchat/sync/src/sync.rs
index 390d59819e..754d3fb73a 100644
--- a/rust/llmchat/sync/src/sync.rs
+++ b/rust/llmchat/sync/src/sync.rs
@@ -1,18 +1,22 @@
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
use zeroize::Zeroizing;
use ente_core::crypto::keys;
use llmchat_db::{
- AttachmentKind, AttachmentMeta, AttachmentStore, Clock, EntityType, FileMetaStore,
- FsAttachmentStore, LlmChatDb, Message, MetaStore, Sender, SqliteBackend, SystemClock,
+ AttachmentKind, AttachmentMeta, AttachmentStore, Clock, EntityType, FsAttachmentStore,
+ LlmChatDb, Message, Sender, Session, SqliteBackend, SyncEntityState, SyncStateDb, SystemClock,
UploadState,
};
use uuid::Uuid;
-use crate::conflict::{find_duplicate_message, order_for_sync};
+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,
};
@@ -26,6 +30,50 @@ use crate::models::{
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 {
@@ -60,40 +108,55 @@ enum ChatKeyStatus {
pub struct SyncEngine {
db: LlmChatDb<SqliteBackend>,
- meta_store: FileMetaStore,
+ 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,
- attachments_db_path: String,
+ sync_db_path: String,
db_key: Vec<u8>,
attachments_dir: String,
- meta_dir: String,
+ _meta_dir: String,
plaintext_dir: Option<String>,
) -> Result<Self, SyncError> {
llmchat_db::traits::ensure_directory(&attachments_dir)?;
- llmchat_db::traits::ensure_directory(&meta_dir)?;
if let Some(ref dir) = plaintext_dir {
let _ = llmchat_db::traits::ensure_directory(dir);
}
- let db = LlmChatDb::open_sqlite_with_defaults(main_db_path, attachments_db_path, db_key)?;
- let meta_store = FileMetaStore::new(meta_dir);
+ let db = LlmChatDb::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,
- meta_store,
+ 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);
}
@@ -132,6 +195,115 @@ impl SyncEngine {
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() != llmchat_db::crypto::KEY_BYTES {
+ return Err(SyncError::Crypto("invalid master key length".to_string()));
+ }
+
+ let SyncAuth {
+ base_url,
+ auth_token,
+ master_key,
+ user_agent,
+ client_package,
+ client_version,
+ } = auth;
+
+ let http = HttpClient::new(HttpConfig {
+ base_url,
+ auth_token,
+ user_agent,
+ client_package,
+ client_version,
+ timeout_secs: None,
+ })?;
+
+ let (chat_key, 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,
@@ -139,9 +311,132 @@ impl SyncEngine {
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 = llmchat_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 _ = self.db.insert_message_with_uuid_and_state(
+ message.uuid,
+ session.uuid,
+ message.sender.as_str(),
+ &message.text,
+ message.parent_message_uuid,
+ message.attachments.clone(),
+ 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() != llmchat_db::crypto::KEY_BYTES {
+ return Err(SyncError::Crypto("invalid master key length".to_string()));
+ }
+
+ let SyncAuth {
+ base_url,
+ auth_token,
+ master_key,
+ user_agent,
+ client_package,
+ client_version,
+ } = auth;
+
+ let http = HttpClient::new(HttpConfig {
+ base_url,
+ auth_token,
+ user_agent,
+ client_package,
+ client_version,
+ timeout_secs: None,
+ })?;
+
+ 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(())
@@ -315,6 +610,8 @@ impl SyncEngine {
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) {
@@ -339,9 +636,48 @@ impl SyncEngine {
}
let payload: SessionPayload =
decrypt_payload(&session.encrypted_data, &session.header, chat_key)?;
- let uuid = Uuid::parse_str(&session.session_uuid)
+ let remote_uuid = Uuid::parse_str(&session.session_uuid)
.map_err(|e| SyncError::InvalidResponse(e.to_string()))?;
- let local = self.db.get_session(uuid).ok().flatten();
+ let 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() {
+ if let Some(existing_remote) = state.remote_id.as_deref() {
+ if 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)
@@ -350,7 +686,7 @@ impl SyncEngine {
.as_ref()
.map(|existing| existing.updated_at)
.unwrap_or(session.updated_at);
- if let Some(remote_updated) = remote_message_updates.get(&uuid) {
+ if let Some(remote_updated) = remote_message_updates.get(&remote_uuid) {
if effective_updated_at < *remote_updated {
effective_updated_at = *remote_updated;
}
@@ -366,11 +702,17 @@ impl SyncEngine {
.unwrap_or(session.created_at);
let _ = self.db.upsert_session_from_remote(
- uuid,
+ 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;
}
@@ -380,10 +722,28 @@ impl SyncEngine {
}
let payload: MessagePayload =
decrypt_payload(&message.encrypted_data, &message.header, chat_key)?;
- let message_uuid = Uuid::parse_str(&message.message_uuid)
+ let remote_message_uuid = Uuid::parse_str(&message.message_uuid)
.map_err(|e| SyncError::InvalidResponse(e.to_string()))?;
- let session_uuid = Uuid::parse_str(&message.session_uuid)
+ 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
@@ -395,12 +755,69 @@ impl SyncEngine {
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() {
+ if let Some(existing_remote) = state.remote_id.as_deref() {
+ if 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(Some(parent)));
+ .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
@@ -416,19 +833,26 @@ impl SyncEngine {
created_at,
parent_uuid,
) {
- duplicate_map.insert(message_uuid, dup_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
@@ -450,132 +874,231 @@ impl SyncEngine {
let clock = SystemClock;
let now = clock.now_us();
+ let offline_db = self.open_offline_db()?;
for tombstone in &response.tombstones.sessions {
- let uuid = Uuid::parse_str(&tombstone.session_uuid)
+ 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 _ = self.db.apply_session_tombstone(uuid, deleted_at);
+ 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() {
+ if 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 uuid = Uuid::parse_str(&tombstone.message_uuid)
+ 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(uuid, deleted_at);
+ 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<llmchat_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 = llmchat_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() {
+ if 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 pending_deletes = self.db.get_pending_deletions()?;
- for (entity_type, uuid) in pending_deletes {
- match entity_type {
- EntityType::Session => {
- http.delete("/llmchat/chat/session", &[("id", uuid.to_string())])?;
- let _ = self.db.delete_attachment_tracking_for_session(uuid);
- self.db.hard_delete(entity_type, uuid)?;
- }
- EntityType::Message => {
- http.delete("/llmchat/chat/message", &[("id", uuid.to_string())])?;
- let _ = self.db.delete_attachment_tracking_for_message(uuid);
- self.db.hard_delete(entity_type, uuid)?;
- }
+ let 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 sessions = self.db.get_sessions_needing_sync()?;
- for session in sessions {
- let session_uuid = session.uuid;
- let messages = self.db.get_messages_needing_sync(session_uuid)?;
- let should_upsert_session = session.needs_sync || session.remote_id.is_none();
-
- 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 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 upload_states = self.collect_attachment_states(&messages)?;
- let blocked = blocked_messages(&messages, &upload_states);
+ let sessions = self.db.list_sessions()?;
+ for session in sessions {
+ self.push_session_with_messages(http, chat_key, &session, result)?;
+ }
- let ordered = order_for_sync(&messages);
- let filtered: Vec<Message> = ordered
- .into_iter()
- .filter(|message| !blocked.contains(&message.uuid))
- .collect();
+ Ok(())
+ }
- if should_upsert_session {
- 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_request = UpsertSessionRequest {
- session_uuid: session_uuid.to_string(),
- root_session_uuid: session_uuid.to_string(),
- branch_from_message_uuid: None,
- encrypted_data: encrypted.encrypted_data,
- header: encrypted.header,
- client_metadata: Some(client_metadata),
- };
- let _response: serde_json::Value =
- http.post_json("/llmchat/chat/session", &session_request)?;
- result.pushed.sessions += 1;
- }
+ 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);
- }
+ 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 _ = self
- .db
- .mark_session_synced(session_uuid, &session_uuid.to_string());
+ if blocked.is_empty() && filtered.len() == messages.len() {
+ 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);
}
- } else if should_upsert_session {
- 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_request = UpsertSessionRequest {
- session_uuid: session_uuid.to_string(),
- root_session_uuid: session_uuid.to_string(),
- branch_from_message_uuid: None,
- encrypted_data: encrypted.encrypted_data,
- header: encrypted.header,
- client_metadata: Some(client_metadata),
- };
- let _response: serde_json::Value =
- http.post_json("/llmchat/chat/session", &session_request)?;
- result.pushed.sessions += 1;
- let _ = self
- .db
- .mark_session_synced(session_uuid, &session_uuid.to_string());
+ }
+ } 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,
@@ -618,23 +1141,42 @@ impl SyncEngine {
text: message.text.clone(),
};
let encrypted = encrypt_payload(&message_payload, chat_key)?;
- let attachments =
- self.encrypt_attachments(message.session_uuid, &message.attachments, chat_key)?;
+ let 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: message.uuid.to_string(),
- session_uuid: message.session_uuid.to_string(),
- parent_message_uuid: message.parent_message_uuid.map(|v| v.to_string()),
+ 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: serde_json::Value =
+ 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(())
}
@@ -671,6 +1213,7 @@ impl SyncEngine {
fn encrypt_attachments(
&self,
session_uuid: Uuid,
+ message_uuid: Uuid,
attachments: &[AttachmentMeta],
chat_key: &[u8],
) -> Result<Vec<RemoteAttachment>, SyncError> {
@@ -688,7 +1231,8 @@ impl SyncEngine {
fallback
}
};
- let client_metadata = encode_attachment_metadata(attachment, chat_key)?;
+ let client_metadata =
+ encode_attachment_metadata(attachment, message_uuid, chat_key)?;
Ok(RemoteAttachment {
id: remote_id,
size: encrypted_size,
@@ -715,6 +1259,28 @@ impl SyncEngine {
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,
@@ -983,7 +1549,7 @@ impl SyncEngine {
}
fn load_cursor(&self) -> Result<SyncCursor, SyncError> {
- match self.meta_store.get(CURSOR_META_KEY)? {
+ match self.sync_state.get_meta(CURSOR_META_KEY)? {
Some(data) => Ok(serde_json::from_slice(&data)?),
None => Ok(SyncCursor::default()),
}
@@ -991,30 +1557,16 @@ impl SyncEngine {
fn save_cursor(&self, cursor: &SyncCursor) -> Result<(), SyncError> {
let data = serde_json::to_vec(cursor)?;
- self.meta_store.set(CURSOR_META_KEY, &data)?;
+ 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> {
- let data = match self.meta_store.get(CHAT_KEY_META_KEY)? {
- Some(data) => data,
- None => return Ok(None),
- };
- let payload: ChatKeyPayload = serde_json::from_slice(&data)?;
- let encrypted = payload
- .encrypted_value()
- .ok_or_else(|| SyncError::InvalidResponse("missing encrypted chat key".to_string()))?;
- let encrypted_payload = crate::models::EncryptedPayload {
- encrypted_data: encrypted.to_string(),
- header: payload.header,
- };
- Ok(Some(decrypt_chat_key(&encrypted_payload, master_key)?))
+ load_chat_key_from_meta(&self.sync_state, master_key)
}
fn save_chat_key_to_meta(&self, payload: &ChatKeyPayload) -> Result<(), SyncError> {
- let data = serde_json::to_vec(payload)?;
- self.meta_store.set(CHAT_KEY_META_KEY, &data)?;
- Ok(())
+ save_chat_key_to_meta(&self.sync_state, payload)
}
fn get_or_create_chat_key(
@@ -1022,22 +1574,115 @@ impl SyncEngine {
http: &HttpClient,
master_key: &[u8],
) -> Result<(Vec<u8>, ChatKeyStatus), SyncError> {
- if let Some(key) = self.load_chat_key_from_meta(master_key)? {
- return Ok((key, ChatKeyStatus::Cached));
- }
+ get_or_create_chat_key_with_state(&self.sync_state, http, master_key)
+ }
+}
- let remote = http.get_json_optional::<ChatKeyPayload>("/llmchat/chat/key", &[]);
- let remote = match remote {
- Ok(value) => value,
- Err(SyncError::Http {
- status: 400,
- code: Some(code),
- ..
- }) if code == "AuthKeyNotCreated" => None,
- Err(err) => return Err(err),
+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() != llmchat_db::crypto::KEY_BYTES {
+ return Err(SyncError::Crypto("invalid master key length".to_string()));
+ }
+
+ let SyncAuth {
+ base_url,
+ auth_token,
+ master_key,
+ user_agent,
+ client_package,
+ client_version,
+ } = auth;
+
+ let http = HttpClient::new(HttpConfig {
+ base_url,
+ auth_token,
+ user_agent,
+ client_package,
+ client_version,
+ timeout_secs: None,
+ })?;
+
+ let 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));
+ }
- if let Some(payload) = remote {
+ let chat_key = keys::generate_stream_key();
+ 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())
})?;
@@ -1046,16 +1691,10 @@ impl SyncEngine {
header: payload.header.clone(),
};
let key = decrypt_chat_key(&encrypted_payload, master_key)?;
- self.save_chat_key_to_meta(&payload)?;
- return Ok((key, ChatKeyStatus::Remote));
+ save_chat_key_to_meta(sync_state, &payload)?;
+ Ok((key, ChatKeyStatus::Remote))
}
-
- let chat_key = keys::generate_stream_key();
- let encrypted = encrypt_chat_key(&chat_key, master_key)?;
- let payload = ChatKeyPayload::from_encrypted(&encrypted);
- http.post_empty("/llmchat/chat/key", &payload)?;
- self.save_chat_key_to_meta(&payload)?;
- Ok((chat_key, ChatKeyStatus::Created))
+ Err(err) => Err(err),
}
}
@@ -1088,6 +1727,13 @@ fn encode_client_metadata(
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?;
@@ -1116,6 +1762,8 @@ fn decode_client_created_at(value: &str, chat_key: &[u8]) -> Option<i64> {
struct AttachmentClientMetadata {
#[serde(rename = "clientId")]
client_id: String,
+ #[serde(rename = "localId", default)]
+ local_id: Option<String>,
#[serde(default)]
encrypted_name: Option<String>,
#[serde(default)]
@@ -1124,12 +1772,14 @@ struct AttachmentClientMetadata {
fn encode_attachment_metadata(
attachment: &AttachmentMeta,
+ message_uuid: Uuid,
chat_key: &[u8],
) -> Result<String, SyncError> {
let encrypted_name = llmchat_db::crypto::encrypt_json_field(&attachment.name, chat_key)
.map_err(|err| SyncError::Crypto(err.to_string()))?;
let payload = AttachmentClientMetadata {
- client_id: attachment.id.clone(),
+ client_id: format!("{}:{}", message_uuid, attachment.id),
+ local_id: Some(attachment.id.clone()),
encrypted_name: Some(encrypted_name),
kind: Some(attachment.kind),
};
@@ -1150,14 +1800,19 @@ fn decode_attachment_metadata(
let name = llmchat_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: payload.client_id.clone(),
+ id: local_id.clone(),
kind,
size: attachment.size,
name,
},
- payload.client_id,
+ local_id,
));
}
@@ -1183,12 +1838,12 @@ fn decode_attachment_metadata(
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct UpsertSessionRequest {
- #[serde(rename = "sessionUUID", alias = "session_uuid")]
- session_uuid: String,
- #[serde(rename = "rootSessionUUID", alias = "root_session_uuid")]
- root_session_uuid: String,
- #[serde(rename = "branchFromMessageUUID", alias = "branch_from_message_uuid")]
- branch_from_message_uuid: Option<String>,
+ #[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,
@@ -1200,11 +1855,33 @@ struct UpsertSessionRequest {
client_metadata: Option<String>,
}
-#[derive(Debug, serde::Serialize)]
+#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
-struct UpsertMessageRequest {
+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")]
@@ -1222,6 +1899,17 @@ struct UpsertMessageRequest {
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();
diff --git a/rust/llmchat/sync/tests/sync_integration.rs b/rust/llmchat/sync/tests/sync_integration.rs
index f970b27a12..b619197323 100644
--- a/rust/llmchat/sync/tests/sync_integration.rs
+++ b/rust/llmchat/sync/tests/sync_integration.rs
@@ -110,8 +110,6 @@ fn pull_applies_remote_sessions_and_messages() {
let diff = DiffResponse {
sessions: vec![RemoteSession {
session_uuid: session_uuid.to_string(),
- root_session_uuid: None,
- branch_from_message_uuid: None,
encrypted_data: encrypted_session.encrypted_data,
header: encrypted_session.header,
client_metadata: None,
@@ -257,8 +255,6 @@ fn tombstone_removes_messages() {
let diff = DiffResponse {
sessions: vec![RemoteSession {
session_uuid: session_uuid.to_string(),
- root_session_uuid: None,
- branch_from_message_uuid: None,
encrypted_data: encrypted_session.encrypted_data,
header: encrypted_session.header,
client_metadata: None,
diff --git a/rust/llmchat/uniffi/llmchat_sync_uniffi/src/api.rs b/rust/llmchat/uniffi/llmchat_sync_uniffi/src/api.rs
index 15c6a1a61c..1c08ae015f 100644
--- a/rust/llmchat/uniffi/llmchat_sync_uniffi/src/api.rs
+++ b/rust/llmchat/uniffi/llmchat_sync_uniffi/src/api.rs
@@ -5,11 +5,16 @@ use thiserror::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 {
- SyncError::Message(err.to_string())
+ match err {
+ core::SyncError::SyncInProgress => SyncError::SyncInProgress,
+ other => SyncError::Message(other.to_string()),
+ }
}
}
@@ -36,6 +41,98 @@ impl From<SyncAuth> for core::SyncAuth {
}
}
+#[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,
@@ -70,6 +167,12 @@ impl From<core::SyncResult> for SyncResult {
}
}
+#[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 LlmChatSync {
inner: core::SyncEngine,
@@ -102,6 +205,46 @@ impl LlmChatSync {
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,