Skip to content

armgit / ente

Public Imported from GitHub
0

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

Type db errors, download phase, and the validate hook

Manav Rathi02c3d763cf01
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppStore.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppStore.kt
index 33efa00f64..b3ba03ce24 100644
--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppStore.kt
+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppStore.kt
@@ -7,6 +7,7 @@ import io.ente.ensu.chat.ChatRepository
import io.ente.ensu.device.ChatDeviceCapability
import io.ente.ensu.bindings.Transcriber
import io.ente.ensu.device.AndroidDeviceCapabilityProvider
+import io.ente.ensu.llm.DownloadPhase
import io.ente.ensu.llm.LlmProvider
import io.ente.ensu.logging.FileLogRepository
import io.ente.ensu.chat.Attachment
@@ -71,6 +72,7 @@ class AppStore(
isDownloading = if (unsupported) false else _state.value.chat.isDownloading,
downloadPercent = if (unsupported) null else _state.value.chat.downloadPercent,
downloadStatus = if (unsupported) null else _state.value.chat.downloadStatus,
+ downloadPhase = if (unsupported) null else _state.value.chat.downloadPhase,
hasRequestedModelDownload = if (unsupported) false else _state.value.chat.hasRequestedModelDownload,
editingMessageId = if (unsupported) null else _state.value.chat.editingMessageId,
messageText = if (unsupported) "" else _state.value.chat.messageText,
@@ -104,7 +106,8 @@ class AppStore(
chat = _state.value.chat.copy(
hasRequestedModelDownload = true,
isDownloading = true,
- downloadStatus = "Resuming download..."
+ downloadStatus = "Resuming download...",
+ downloadPhase = DownloadPhase.Downloading
)
)
}
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatMessages.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatMessages.kt
index c89120082c..7a3e8142cc 100644
--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatMessages.kt
+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatMessages.kt
@@ -83,6 +83,7 @@ import java.util.Date
import java.util.Locale
import kotlin.math.roundToInt
import kotlin.math.roundToLong
+import io.ente.ensu.llm.DownloadPhase
@Composable
internal fun MessageList(
@@ -96,6 +97,7 @@ internal fun MessageList(
isDownloading: Boolean,
downloadPercent: Int?,
downloadStatus: String?,
+ downloadPhase: DownloadPhase?,
modelDownloadSizeBytes: Long?,
branchSelections: Map<String, Int>,
onEditMessage: (ChatMessage) -> Unit,
@@ -111,6 +113,7 @@ internal fun MessageList(
isDownloading = isDownloading,
downloadPercent = downloadPercent,
downloadStatus = downloadStatus,
+ downloadPhase = downloadPhase,
modelDownloadSizeBytes = modelDownloadSizeBytes,
onDownload = { onStartDownload(true) }
)
@@ -386,6 +389,7 @@ private fun DownloadOnboarding(
isDownloading: Boolean,
downloadPercent: Int?,
downloadStatus: String?,
+ downloadPhase: DownloadPhase?,
modelDownloadSizeBytes: Long?,
onDownload: () -> Unit
) {
@@ -406,10 +410,10 @@ private fun DownloadOnboarding(
)
Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
if (isDownloading) {
- val showProgress = downloadPercent != null ||
- downloadStatus?.contains("Loading", ignoreCase = true) == true
+ val isLoadingModel = downloadPhase == DownloadPhase.Loading
+ val showProgress = downloadPercent != null || isLoadingModel
val statusText = when {
- downloadStatus?.contains("Loading", ignoreCase = true) == true -> downloadStatus
+ isLoadingModel -> downloadStatus
modelDownloadSizeBytes != null && downloadPercent != null && downloadPercent >= 0 -> {
val downloadedBytes = (modelDownloadSizeBytes * (downloadPercent / 100f)).roundToLong()
"Downloading... ${formatBytes(downloadedBytes)} / ${formatBytes(modelDownloadSizeBytes)}"
@@ -450,9 +454,7 @@ private fun DownloadOnboarding(
Text(
text = downloadStatus,
style = EnsuTypography.body,
- color = if (downloadStatus.contains("not enough storage", ignoreCase = true) ||
- downloadStatus.contains("failed", ignoreCase = true)
- ) {
+ color = if (downloadPhase == DownloadPhase.Failed) {
EnsuColor.error
} else {
EnsuColor.textMuted()
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRecovery.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRecovery.kt
deleted file mode 100644
index 7e4bd2130f..0000000000
--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRecovery.kt
+++ /dev/null
@@ -1,14 +0,0 @@
-package io.ente.ensu.chat
-
-internal object ChatRecovery {
- private val resetSignals = listOf(
- "stream pull failed",
- "invalid blob",
- "invalid encrypted"
- )
-
- fun shouldResetFromMessage(message: String): Boolean {
- val lower = message.lowercase()
- return resetSignals.any { lower.contains(it) }
- }
-}
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.kt
index 5fe0a540b7..34fe7ab1fa 100644
--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.kt
+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.kt
@@ -188,19 +188,13 @@ class ChatRepository(
}
private fun shouldResetDb(error: DbException): Boolean {
- val message = when (error) {
- is DbException.Message -> error.v1
- else -> error.message.orEmpty()
- }
- return ChatRecovery.shouldResetFromMessage(message)
+ return error is DbException.Crypto ||
+ error is DbException.InvalidBlobLength ||
+ error is DbException.InvalidEncryptedField
}
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)
+ return error is DbException.ReadonlyDatabase
}
private fun resetDb() {
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatState.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatState.kt
index 8f4fa01602..48db17683e 100644
--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatState.kt
+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatState.kt
@@ -1,6 +1,7 @@
package io.ente.ensu.chat
import io.ente.ensu.device.ChatDeviceCapability
+import io.ente.ensu.llm.DownloadPhase
import io.ente.ensu.chat.Attachment
import io.ente.ensu.chat.ChatMessage
import io.ente.ensu.chat.ChatSession
@@ -16,6 +17,7 @@ data class ChatState(
val isDownloading: Boolean = false,
val downloadPercent: Int? = null,
val downloadStatus: String? = null,
+ val downloadPhase: DownloadPhase? = null,
val messageText: String = "",
val attachments: List<Attachment> = emptyList(),
val editingMessageId: String? = null,
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt
index 0292174706..db0ac306a8 100644
--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt
+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt
@@ -5,6 +5,7 @@ import io.ente.ensu.llm.ModelSettingsActions
import io.ente.ensu.chat.ChatRepository
import io.ente.ensu.device.isChatSupported
import io.ente.ensu.logging.FileLogRepository
+import io.ente.ensu.llm.DownloadPhase
import io.ente.ensu.llm.LlmMessage
import io.ente.ensu.llm.LlmMessageRole
import io.ente.ensu.llm.LlmModelTarget
@@ -189,6 +190,7 @@ internal class ChatStoreActions(
streamingParentId = if (resetCurrent) null else appState.chat.streamingParentId,
downloadPercent = if (resetCurrent) null else appState.chat.downloadPercent,
downloadStatus = if (resetCurrent) null else appState.chat.downloadStatus,
+ downloadPhase = if (resetCurrent) null else appState.chat.downloadPhase,
messageText = if (resetCurrent) "" else appState.chat.messageText,
attachments = if (resetCurrent) emptyList() else appState.chat.attachments,
editingMessageId = if (resetCurrent) null else appState.chat.editingMessageId
@@ -447,6 +449,7 @@ internal class ChatStoreActions(
streamingParentId = userMessage.id,
downloadPercent = null,
downloadStatus = null,
+ downloadPhase = null,
hasRequestedModelDownload = true
)
)
@@ -466,6 +469,7 @@ internal class ChatStoreActions(
isDownloading = resolvedProgress.isDownloading,
downloadPercent = resolvedProgress.percent,
downloadStatus = resolvedProgress.status,
+ downloadPhase = resolvedProgress.phase,
isModelDownloaded = if (resolvedProgress.isFinished) true else appState.chat.isModelDownloaded,
modelDownloadSizeBytes = if (resolvedProgress.isFinished) null else appState.chat.modelDownloadSizeBytes
)
@@ -485,6 +489,7 @@ internal class ChatStoreActions(
streamingParentId = null,
downloadPercent = null,
downloadStatus = if (cancelled) "Download cancelled" else null,
+ downloadPhase = null,
hasRequestedModelDownload = if (cancelled) false else appState.chat.hasRequestedModelDownload
)
)
@@ -528,7 +533,8 @@ internal class ChatStoreActions(
streamingResponse = "",
streamingParentId = null,
downloadPercent = null,
- downloadStatus = null
+ downloadStatus = null,
+ downloadPhase = null
)
)
}
@@ -673,6 +679,7 @@ internal class ChatStoreActions(
streamingParentId = null,
downloadPercent = null,
downloadStatus = null,
+ downloadPhase = null,
messages = displayMessages,
branchSelections = branchSelectionIndices
)
@@ -1188,10 +1195,7 @@ internal class ChatStoreActions(
stopRequested = false
}
- private fun resetGenerationState(
- downloadStatus: String? = null,
- hasRequestedModelDownload: Boolean? = null
- ) {
+ private fun resetGenerationState() {
cancelGeneration()
state.update { appState ->
appState.copy(
@@ -1201,9 +1205,8 @@ internal class ChatStoreActions(
streamingResponse = "",
streamingParentId = null,
downloadPercent = null,
- downloadStatus = downloadStatus,
- hasRequestedModelDownload =
- hasRequestedModelDownload ?: appState.chat.hasRequestedModelDownload
+ downloadStatus = null,
+ downloadPhase = null
)
)
}
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatView.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatView.kt
index 27de19d064..6822d6e8c1 100644
--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatView.kt
+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatView.kt
@@ -222,6 +222,7 @@ fun ChatView(
isDownloading = chatState.isDownloading,
downloadPercent = chatState.downloadPercent,
downloadStatus = chatState.downloadStatus,
+ downloadPhase = chatState.downloadPhase,
modelDownloadSizeBytes = chatState.modelDownloadSizeBytes,
branchSelections = chatState.branchSelections,
onEditMessage = onEditMessage,
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/DownloadProgressTracker.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/DownloadProgressTracker.kt
index 10a8a4b4d6..02d88c8c4b 100644
--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/DownloadProgressTracker.kt
+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/DownloadProgressTracker.kt
@@ -5,6 +5,7 @@ import io.ente.ensu.llm.DownloadProgress
internal data class ResolvedDownloadProgress(
val percent: Int?,
val status: String,
+ val phase: DownloadPhase,
val isDownloading: Boolean,
val isFinished: Boolean
)
@@ -17,8 +18,8 @@ internal class DownloadProgressTracker(
private var lastVisibleStatus: String? = initialStatus
fun resolve(progress: DownloadProgress): ResolvedDownloadProgress {
- val isLoading = progress.status.contains("Loading", ignoreCase = true)
- val isFinished = progress.status.contains("Ready", ignoreCase = true)
+ val isLoading = progress.phase == DownloadPhase.Loading
+ val isFinished = progress.phase == DownloadPhase.Ready
val rawPercent = progress.percent.takeIf { it >= 0 }
val previousPercent = lastVisiblePercent
val previousStatus = lastVisibleStatus
@@ -47,6 +48,7 @@ internal class DownloadProgressTracker(
return ResolvedDownloadProgress(
percent = resolvedPercent,
status = resolvedStatus,
+ phase = progress.phase,
isDownloading = progress.percent >= 0 && !isFinished,
isFinished = isFinished
)
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmModels.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmModels.kt
index d9b45135fb..89e4fe163e 100644
--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmModels.kt
+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmModels.kt
@@ -13,9 +13,17 @@ data class LlmModelTarget(
data class DownloadProgress(
val percent: Int,
val status: String,
- val failure: DownloadFailure? = null
+ val failure: DownloadFailure? = null,
+ val phase: DownloadPhase = DownloadPhase.Downloading
)
+enum class DownloadPhase {
+ Downloading,
+ Loading,
+ Ready,
+ Failed
+}
+
sealed class DownloadFailure(override val message: String) : Exception(message) {
class Http(val status: Int) : DownloadFailure("Download failed: HTTP $status")
class InvalidContent(message: String) : DownloadFailure(message)
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt
index f30051507d..376d248a62 100644
--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt
+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt
@@ -264,14 +264,18 @@ class LlmProvider(
val failure = DownloadFailure.InvalidContent(
"${download.label} download is invalid"
)
- return@withContext DownloadProgress(-1, failure.message, failure)
+ return@withContext DownloadProgress(
+ -1, failure.message, failure, DownloadPhase.Failed
+ )
}
}
DownloadManager.STATUS_FAILED -> {
clearDownloadRecords(target)
val failure = downloadFailure(row.reason)
- return@withContext DownloadProgress(-1, failure.message, failure)
+ return@withContext DownloadProgress(
+ -1, failure.message, failure, DownloadPhase.Failed
+ )
}
}
}
@@ -382,9 +386,9 @@ class LlmProvider(
awaitForegroundDownload(target, onProgress)
}
- onProgress(DownloadProgress(100, "Loading model..."))
+ onProgress(DownloadProgress(100, "Loading model...", phase = DownloadPhase.Loading))
loadWithFallbacks(target, modelFile)
- onProgress(DownloadProgress(100, "Ready"))
+ onProgress(DownloadProgress(100, "Ready", phase = DownloadPhase.Ready))
}
private fun loadWithFallbacks(target: LlmModelTarget, modelFile: File) {
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsActions.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsActions.kt
index af25128509..f8fcfefdee 100644
--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsActions.kt
+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsActions.kt
@@ -78,6 +78,7 @@ internal class ModelSettingsActions(
isDownloading = false,
downloadPercent = null,
downloadStatus = null,
+ downloadPhase = null,
modelDownloadSizeBytes = null,
hasRequestedModelDownload = false
)
@@ -98,6 +99,7 @@ internal class ModelSettingsActions(
isDownloading = if (isDownloaded) false else appState.chat.isDownloading,
downloadPercent = if (isDownloaded) null else appState.chat.downloadPercent,
downloadStatus = if (isDownloaded) null else appState.chat.downloadStatus,
+ downloadPhase = if (isDownloaded) null else appState.chat.downloadPhase,
modelDownloadSizeBytes = if (isDownloaded) null else appState.chat.modelDownloadSizeBytes,
hasRequestedModelDownload = appState.chat.hasRequestedModelDownload || isDownloaded
)
@@ -118,6 +120,7 @@ internal class ModelSettingsActions(
isDownloading = !isFailure,
downloadPercent = progress.percent.takeIf { it >= 0 },
downloadStatus = progress.status,
+ downloadPhase = progress.phase,
hasRequestedModelDownload = !isFailure
)
)
@@ -133,6 +136,7 @@ internal class ModelSettingsActions(
isDownloading = false,
downloadPercent = null,
downloadStatus = null,
+ downloadPhase = null,
hasRequestedModelDownload = false
)
)
@@ -187,6 +191,7 @@ internal class ModelSettingsActions(
isDownloading = true,
downloadPercent = 0,
downloadStatus = "Starting download...",
+ downloadPhase = DownloadPhase.Downloading,
hasRequestedModelDownload = if (userInitiated) true else appState.chat.hasRequestedModelDownload
)
)
@@ -221,6 +226,7 @@ internal class ModelSettingsActions(
isDownloading = resolvedProgress.isDownloading,
downloadPercent = resolvedProgress.percent,
downloadStatus = resolvedProgress.status,
+ downloadPhase = resolvedProgress.phase,
isModelDownloaded = if (resolvedProgress.isFinished) true else appState.chat.isModelDownloaded,
modelDownloadSizeBytes = if (resolvedProgress.isFinished) null else appState.chat.modelDownloadSizeBytes
)
@@ -251,6 +257,7 @@ internal class ModelSettingsActions(
isDownloading = false,
downloadPercent = null,
downloadStatus = failureMessage,
+ downloadPhase = if (cancelled) null else DownloadPhase.Failed,
hasRequestedModelDownload = false
)
)
@@ -311,6 +318,7 @@ internal class ModelSettingsActions(
isDownloading = false,
downloadPercent = null,
downloadStatus = "Download cancelled",
+ downloadPhase = null,
hasRequestedModelDownload = false
)
)
@@ -344,6 +352,7 @@ internal class ModelSettingsActions(
isDownloading = !isFailure,
downloadPercent = progress.percent.takeIf { it >= 0 },
downloadStatus = progress.status,
+ downloadPhase = progress.phase,
hasRequestedModelDownload = if (isFailure) false else appState.chat.hasRequestedModelDownload
)
)
diff --git a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatRecovery.swift b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatRecovery.swift
deleted file mode 100644
index 66c0eda0e8..0000000000
--- a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatRecovery.swift
+++ /dev/null
@@ -1,14 +0,0 @@
-import Foundation
-
-enum ChatRecovery {
- private static let resetSignals = [
- "stream pull failed",
- "invalid blob",
- "invalid encrypted"
- ]
-
- static func shouldResetFromMessage(_ message: String) -> Bool {
- let lowercased = message.lowercased()
- return resetSignals.contains { lowercased.contains($0) }
- }
-}
diff --git a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatView.swift b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatView.swift
index 4a708c2c35..a34ce74ec7 100644
--- a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatView.swift
+++ b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatView.swift
@@ -386,6 +386,7 @@ struct ChatView: View {
isDownloading: viewModel.isDownloading,
downloadPercent: viewModel.downloadToast?.percent,
statusText: viewModel.downloadToast?.status,
+ isLoadingModel: viewModel.downloadToast?.phase == .loading,
totalBytes: viewModel.modelDownloadSizeBytes,
sizeText: viewModel.modelDownloadSizeText,
onDownload: {
diff --git a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift
index 57b6680c6c..64676a5ca7 100644
--- a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift
+++ b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift
@@ -2238,8 +2238,8 @@ private final class DownloadProgressTracker {
}
func resolve(_ progress: DownloadProgress) -> ResolvedDownloadProgress {
- let isLoading = progress.status.localizedCaseInsensitiveContains("Loading")
- let isReady = progress.status.localizedCaseInsensitiveContains("Ready")
+ let isLoading = progress.phase == .loading
+ let isReady = progress.phase == .ready
let rawPercent = progress.percent >= 0 ? progress.percent : nil
let previousPercent = lastVisiblePercent
let previousStatus = lastVisibleStatus
diff --git a/mobile/native/apple/apps/ensu/Ensu/Chat/Components/ChatViewComponents.swift b/mobile/native/apple/apps/ensu/Ensu/Chat/Components/ChatViewComponents.swift
index c0f9afb38f..9be6133170 100644
--- a/mobile/native/apple/apps/ensu/Ensu/Chat/Components/ChatViewComponents.swift
+++ b/mobile/native/apple/apps/ensu/Ensu/Chat/Components/ChatViewComponents.swift
@@ -4,6 +4,7 @@ struct DownloadOnboardingView: View {
let isDownloading: Bool
let downloadPercent: Int?
let statusText: String?
+ let isLoadingModel: Bool
let totalBytes: Int64?
let sizeText: String
let onDownload: () -> Void
@@ -17,7 +18,7 @@ struct DownloadOnboardingView: View {
if isDownloading {
let statusLine: String = {
- if let statusText, statusText.localizedCaseInsensitiveContains("loading") {
+ if let statusText, isLoadingModel {
return statusText
}
if let totalBytes, let percent = downloadPercent, percent >= 0 {
diff --git a/mobile/native/apple/apps/ensu/Ensu/Services/LlmProvider.swift b/mobile/native/apple/apps/ensu/Ensu/Services/LlmProvider.swift
index 7308d98558..e592dcb768 100644
--- a/mobile/native/apple/apps/ensu/Ensu/Services/LlmProvider.swift
+++ b/mobile/native/apple/apps/ensu/Ensu/Services/LlmProvider.swift
@@ -13,6 +13,14 @@ struct DownloadProgress: Equatable {
let percent: Int
let status: String
var failure: DownloadFailure? = nil
+ var phase: DownloadPhase = .downloading
+}
+
+enum DownloadPhase {
+ case downloading
+ case loading
+ case ready
+ case failed
}
enum DownloadFailure: Error, Codable, Equatable, LocalizedError {
@@ -222,7 +230,7 @@ final class LlmProvider {
}
}
- onProgress(DownloadProgress(percent: 100, status: "Loading model..."))
+ onProgress(DownloadProgress(percent: 100, status: "Loading model...", phase: .loading))
do {
try loadModel(target: target, modelPath: modelPath)
} catch {
@@ -234,7 +242,7 @@ final class LlmProvider {
}
throw error
}
- onProgress(DownloadProgress(percent: 100, status: "Ready"))
+ onProgress(DownloadProgress(percent: 100, status: "Ready", phase: .ready))
}
func generateChat(
diff --git a/mobile/native/apple/apps/ensu/Ensu/Services/ModelDownloadManager.swift b/mobile/native/apple/apps/ensu/Ensu/Services/ModelDownloadManager.swift
index d6e269f7c4..f1f1be059d 100644
--- a/mobile/native/apple/apps/ensu/Ensu/Services/ModelDownloadManager.swift
+++ b/mobile/native/apple/apps/ensu/Ensu/Services/ModelDownloadManager.swift
@@ -109,7 +109,9 @@ final class ModelDownloadManager: NSObject {
if relevantTasks.isEmpty {
if let failed = firstFailure(for: targets) {
let failure = failed.failure ?? .failed(failed.errorMessage ?? "Download failed")
- return DownloadProgress(percent: -1, status: failure.message, failure: failure)
+ return DownloadProgress(
+ percent: -1, status: failure.message, failure: failure, phase: .failed
+ )
}
return nil
}
diff --git a/rust/apps/ensu/src-tauri/src/commands/chat_db.rs b/rust/apps/ensu/src-tauri/src/commands/chat_db.rs
index cec3404f94..7036a9c58b 100644
--- a/rust/apps/ensu/src-tauri/src/commands/chat_db.rs
+++ b/rust/apps/ensu/src-tauri/src/commands/chat_db.rs
@@ -55,6 +55,7 @@ impl From<DbError> for ApiError {
E::Uuid(_) => "db_uuid",
E::Utf8(_) => "db_utf8",
E::Io(_) => "db_io",
+ E::ReadonlyDatabase => "db_readonly",
E::Sqlite(_) => "db_sqlite",
E::UnsupportedOperation(_) => "db_unsupported_operation",
E::Migration(_) => "db_migration",
diff --git a/rust/apps/ensu/src-tauri/src/commands/llm.rs b/rust/apps/ensu/src-tauri/src/commands/llm.rs
index b273a0db5c..f18780fd8d 100644
--- a/rust/apps/ensu/src-tauri/src/commands/llm.rs
+++ b/rust/apps/ensu/src-tauri/src/commands/llm.rs
@@ -76,6 +76,7 @@ fn download_code(err: &download::Error) -> &'static str {
download::Error::Http(_) => "http",
download::Error::Validation(_) => "validation",
download::Error::Network(_) => "network",
+ download::Error::StorageFull => "storage_full",
_ => "download",
}
}
diff --git a/rust/bindings/uniffi/ensu/src/db.rs b/rust/bindings/uniffi/ensu/src/db.rs
index 2c9445376e..0de01c5cf5 100644
--- a/rust/bindings/uniffi/ensu/src/db.rs
+++ b/rust/bindings/uniffi/ensu/src/db.rs
@@ -4,13 +4,88 @@ use uuid::Uuid;
#[derive(Debug, Error, uniffi::Error)]
pub enum DbError {
- #[error("{0}")]
- Message(String),
+ #[error("invalid encryption key length: expected {expected}, got {actual}")]
+ InvalidKeyLength { expected: u64, actual: u64 },
+ #[error("invalid blob length: expected at least {minimum} bytes, got {actual}")]
+ InvalidBlobLength { minimum: u64, actual: u64 },
+ #[error("invalid encrypted field format")]
+ InvalidEncryptedField,
+ #[error("unsupported value type: {detail}")]
+ UnsupportedValueType { detail: String },
+ #[error("row error: {detail}")]
+ Row { detail: String },
+ #[error("invalid sender: {detail}")]
+ InvalidSender { detail: String },
+ #[error("{entity} not found: {id}")]
+ NotFound { entity: String, id: String },
+ #[error("{detail}")]
+ Crypto { detail: String },
+ #[error("{detail}")]
+ Json { detail: String },
+ #[error("invalid UUID: {detail}")]
+ InvalidUuid { detail: String },
+ #[error("{detail}")]
+ Utf8 { detail: String },
+ #[error("{detail}")]
+ Io { detail: String },
+ #[error("database is readonly")]
+ ReadonlyDatabase,
+ #[error("{detail}")]
+ Sqlite { detail: String },
+ #[error("unsupported operation: {detail}")]
+ UnsupportedOperation { detail: String },
+ #[error("migration error: {detail}")]
+ Migration { detail: String },
}
impl From<db::Error> for DbError {
fn from(err: db::Error) -> Self {
- DbError::Message(err.to_string())
+ use db::Error as E;
+ match err {
+ E::InvalidKeyLength { expected, actual } => Self::InvalidKeyLength {
+ expected: expected as u64,
+ actual: actual as u64,
+ },
+ E::InvalidBlobLength { minimum, actual } => Self::InvalidBlobLength {
+ minimum: minimum as u64,
+ actual: actual as u64,
+ },
+ E::InvalidEncryptedField => Self::InvalidEncryptedField,
+ E::UnsupportedValueType(detail) => Self::UnsupportedValueType { detail },
+ E::Row(detail) => Self::Row { detail },
+ E::InvalidSender(detail) => Self::InvalidSender { detail },
+ E::NotFound { entity, id } => Self::NotFound {
+ entity: format!("{entity:?}"),
+ id: id.to_string(),
+ },
+ E::Crypto(err) => Self::Crypto {
+ detail: err.to_string(),
+ },
+ E::SerdeJson(err) => Self::Json {
+ detail: err.to_string(),
+ },
+ E::Uuid(err) => Self::InvalidUuid {
+ detail: err.to_string(),
+ },
+ E::Utf8(err) => Self::Utf8 {
+ detail: err.to_string(),
+ },
+ E::Io(err) => Self::Io {
+ detail: err.to_string(),
+ },
+ E::ReadonlyDatabase => Self::ReadonlyDatabase,
+ E::Sqlite(err) => Self::Sqlite {
+ detail: err.to_string(),
+ },
+ E::UnsupportedOperation(detail) => Self::UnsupportedOperation { detail },
+ E::Migration(detail) => Self::Migration { detail },
+ }
+ }
+}
+
+fn invalid_uuid(err: uuid::Error) -> DbError {
+ DbError::InvalidUuid {
+ detail: err.to_string(),
}
}
@@ -165,17 +240,17 @@ impl EnsuDb {
}
pub fn get_session(&self, uuid: String) -> Result<Option<DbSession>, DbError> {
- let uuid = Uuid::parse_str(&uuid).map_err(|e| DbError::Message(e.to_string()))?;
+ let uuid = Uuid::parse_str(&uuid).map_err(invalid_uuid)?;
Ok(self.inner.get_session(uuid)?.map(to_session))
}
pub fn delete_session(&self, uuid: String) -> Result<(), DbError> {
- let uuid = Uuid::parse_str(&uuid).map_err(|e| DbError::Message(e.to_string()))?;
+ let uuid = Uuid::parse_str(&uuid).map_err(invalid_uuid)?;
Ok(self.inner.delete_session(uuid)?)
}
pub fn update_session_title(&self, uuid: String, title: String) -> Result<(), DbError> {
- let uuid = Uuid::parse_str(&uuid).map_err(|e| DbError::Message(e.to_string()))?;
+ let uuid = Uuid::parse_str(&uuid).map_err(invalid_uuid)?;
Ok(self.inner.update_session_title(uuid, &title)?)
}
@@ -187,12 +262,11 @@ impl EnsuDb {
parent_message_uuid: Option<String>,
attachments: Vec<DbAttachmentMeta>,
) -> Result<DbMessage, DbError> {
- let session_uuid =
- Uuid::parse_str(&session_uuid).map_err(|e| DbError::Message(e.to_string()))?;
+ let session_uuid = Uuid::parse_str(&session_uuid).map_err(invalid_uuid)?;
let parent = parent_message_uuid
.map(|v| Uuid::parse_str(&v))
.transpose()
- .map_err(|e| DbError::Message(e.to_string()))?;
+ .map_err(invalid_uuid)?;
let message = self.inner.insert_message(
session_uuid,
@@ -205,8 +279,7 @@ impl EnsuDb {
}
pub fn get_messages(&self, session_uuid: String) -> Result<Vec<DbMessage>, DbError> {
- let session_uuid =
- Uuid::parse_str(&session_uuid).map_err(|e| DbError::Message(e.to_string()))?;
+ let session_uuid = Uuid::parse_str(&session_uuid).map_err(invalid_uuid)?;
Ok(self
.inner
.get_messages(session_uuid)?
@@ -216,7 +289,7 @@ impl EnsuDb {
}
pub fn update_message_text(&self, uuid: String, text: String) -> Result<(), DbError> {
- let uuid = Uuid::parse_str(&uuid).map_err(|e| DbError::Message(e.to_string()))?;
+ let uuid = Uuid::parse_str(&uuid).map_err(invalid_uuid)?;
Ok(self.inner.update_message_text(uuid, &text)?)
}
}
diff --git a/rust/bindings/uniffi/ensu/src/download.rs b/rust/bindings/uniffi/ensu/src/download.rs
index d3b41d94ba..b9043b31c3 100644
--- a/rust/bindings/uniffi/ensu/src/download.rs
+++ b/rust/bindings/uniffi/ensu/src/download.rs
@@ -1,7 +1,5 @@
use ente_ensu::download;
-const ENOSPC: i32 = 28;
-
#[derive(Debug, Clone, uniffi::Enum)]
pub enum DownloadError {
Cancelled,
@@ -29,15 +27,10 @@ impl From<download::Error> for DownloadError {
}
download::Error::Protocol(message) => Self::Protocol { message },
download::Error::InvalidTarget(message) => Self::InvalidTarget { message },
- download::Error::Io(err) => {
- if err.raw_os_error() == Some(ENOSPC) {
- Self::StorageFull
- } else {
- Self::Io {
- message: err.to_string(),
- }
- }
- }
+ download::Error::StorageFull => Self::StorageFull,
+ download::Error::Io(err) => Self::Io {
+ message: err.to_string(),
+ },
download::Error::Json(err) => Self::Io {
message: err.to_string(),
},
diff --git a/rust/crates/ensu/src/db/error.rs b/rust/crates/ensu/src/db/error.rs
index 73bd8c56d8..dc25d3617c 100644
--- a/rust/crates/ensu/src/db/error.rs
+++ b/rust/crates/ensu/src/db/error.rs
@@ -42,9 +42,12 @@ pub enum Error {
#[error(transparent)]
Io(#[from] std::io::Error),
+ #[error("database is readonly")]
+ ReadonlyDatabase,
+
#[cfg(feature = "sqlite")]
#[error(transparent)]
- Sqlite(#[from] rusqlite::Error),
+ Sqlite(rusqlite::Error),
#[error("unsupported operation: {0}")]
UnsupportedOperation(String),
@@ -52,3 +55,17 @@ pub enum Error {
#[error("migration error: {0}")]
Migration(String),
}
+
+#[cfg(feature = "sqlite")]
+impl From<rusqlite::Error> for Error {
+ fn from(err: rusqlite::Error) -> Self {
+ match &err {
+ rusqlite::Error::SqliteFailure(failure, _)
+ if failure.code == rusqlite::ErrorCode::ReadOnly =>
+ {
+ Error::ReadonlyDatabase
+ }
+ _ => Error::Sqlite(err),
+ }
+ }
+}
diff --git a/rust/crates/ensu/src/download.rs b/rust/crates/ensu/src/download.rs
index 9cbd8d67b5..769f7ac30f 100644
--- a/rust/crates/ensu/src/download.rs
+++ b/rust/crates/ensu/src/download.rs
@@ -47,12 +47,24 @@ pub enum Error {
Protocol(String),
#[error("invalid download target: {0}")]
InvalidTarget(String),
+ #[error("not enough storage space")]
+ StorageFull,
#[error(transparent)]
- Io(#[from] std::io::Error),
+ Io(std::io::Error),
#[error(transparent)]
Json(#[from] serde_json::Error),
}
+impl From<std::io::Error> for Error {
+ fn from(err: std::io::Error) -> Self {
+ if err.kind() == std::io::ErrorKind::StorageFull {
+ Error::StorageFull
+ } else {
+ Error::Io(err)
+ }
+ }
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Target {
pub label: String,
@@ -178,7 +190,7 @@ struct ContentRange {
pub fn fetch(
targets: Vec<Target>,
- validate: impl Fn(&Target, &Path) -> Result<(), String>,
+ validate: impl Fn(&Target, &Path) -> Result<(), Error>,
on_progress: impl FnMut(Progress),
is_cancelled: impl Fn() -> bool,
) -> Result<(), Error> {
@@ -191,7 +203,7 @@ pub fn fetch(
async fn fetch_async(
targets: Vec<Target>,
- validate: impl Fn(&Target, &Path) -> Result<(), String>,
+ validate: impl Fn(&Target, &Path) -> Result<(), Error>,
on_progress: impl FnMut(Progress),
is_cancelled: impl Fn() -> bool,
) -> Result<(), Error> {
@@ -395,7 +407,7 @@ async fn download_file(
target: &Target,
destination: &Path,
download_probe: &DownloadProbe,
- validate: &impl Fn(&Target, &Path) -> Result<(), String>,
+ validate: &impl Fn(&Target, &Path) -> Result<(), Error>,
mut on_progress: impl FnMut(FileDownloadProgress),
is_cancelled: &impl Fn() -> bool,
) -> Result<FileDownloadReport, Error> {
@@ -459,7 +471,7 @@ async fn download_file_single(
target: &Target,
destination: &Path,
expected_file_total: Option<u64>,
- validate: &impl Fn(&Target, &Path) -> Result<(), String>,
+ validate: &impl Fn(&Target, &Path) -> Result<(), Error>,
on_progress: &mut dyn FnMut(FileDownloadProgress),
is_cancelled: &impl Fn() -> bool,
) -> Result<FileDownloadReport, Error> {
@@ -651,7 +663,7 @@ async fn download_file_single(
if let Err(err) = validate(target, &tmp_path) {
let _ = fs::remove_file(&tmp_path);
let _ = fs::remove_file(&partial_metadata_path);
- return Err(Error::Validation(err));
+ return Err(err);
}
if destination.exists() {
@@ -690,7 +702,7 @@ async fn download_file_ranged(
destination: &Path,
total: u64,
response_metadata: Option<ResponseMetadata>,
- validate: &impl Fn(&Target, &Path) -> Result<(), String>,
+ validate: &impl Fn(&Target, &Path) -> Result<(), Error>,
on_progress: &mut dyn FnMut(FileDownloadProgress),
is_cancelled: &impl Fn() -> bool,
) -> Result<FileDownloadReport, Error> {
@@ -772,7 +784,7 @@ async fn download_file_ranged(
if let Err(err) = validate(target, &tmp_path) {
let _ = fs::remove_file(&tmp_path);
let _ = fs::remove_file(&range_metadata_path);
- return Err(Error::Validation(err));
+ return Err(err);
}
if destination.exists() {
@@ -1497,7 +1509,7 @@ fn bytes_per_second(bytes: u64, elapsed: Duration) -> f64 {
fn prepare_cached_download(
target: &Target,
destination: &Path,
- validate: &impl Fn(&Target, &Path) -> Result<(), String>,
+ validate: &impl Fn(&Target, &Path) -> Result<(), Error>,
) -> bool {
if !destination.exists() || validate(target, destination).is_err() {
return false;
@@ -1958,7 +1970,7 @@ mod tests {
url: server.url("/model.bin"),
destination_path: destination.display().to_string(),
}],
- |_, _| Err("rejected".to_string()),
+ |_, _| Err(Error::Validation("rejected".to_string())),
|_| {},
|| false,
);
@@ -2054,7 +2066,7 @@ mod tests {
.and_then(|data| data.first().copied())
{
Some(0) => Ok(()),
- _ => Err("bad header".to_string()),
+ _ => Err(Error::Validation("bad header".to_string())),
};
fetch(vec![target.clone()], require_zero_header, |_| {}, || false)
diff --git a/rust/crates/ensu/src/llm/download.rs b/rust/crates/ensu/src/llm/download.rs
index 2503131b61..a569c235e0 100644
--- a/rust/crates/ensu/src/llm/download.rs
+++ b/rust/crates/ensu/src/llm/download.rs
@@ -15,15 +15,18 @@ pub fn download_model_files(
Ok(())
}
-fn validate_gguf(_target: &Target, path: &Path) -> Result<(), String> {
+fn validate_gguf(_target: &Target, path: &Path) -> Result<(), download::Error> {
if file_size(path).is_none_or(|size| size < MIN_MODEL_BYTES) {
- return Err(format!(
+ return Err(download::Error::Validation(format!(
"{} is too small to be a model file",
path.display()
- ));
+ )));
}
if !looks_like_gguf(path) {
- return Err(format!("{} is not a valid GGUF file", path.display()));
+ return Err(download::Error::Validation(format!(
+ "{} is not a valid GGUF file",
+ path.display()
+ )));
}
Ok(())
}
diff --git a/rust/crates/ensu/src/transcription/model.rs b/rust/crates/ensu/src/transcription/model.rs
index afab940549..f02a04b884 100644
--- a/rust/crates/ensu/src/transcription/model.rs
+++ b/rust/crates/ensu/src/transcription/model.rs
@@ -129,12 +129,21 @@ pub(crate) fn download_model(
Ok(final_model_dir)
}
-fn validate_download(target: &download::Target, path: &Path) -> std::result::Result<(), String> {
+fn validate_download(
+ target: &download::Target,
+ path: &Path,
+) -> std::result::Result<(), download::Error> {
if !is_file_present(path) {
- return Err(format!("{} is empty", path.display()));
+ return Err(download::Error::Validation(format!(
+ "{} is empty",
+ path.display()
+ )));
}
if target.destination_path.ends_with(".tar.gz") && !looks_like_gzip(path) {
- return Err(format!("{} is not a gzip archive", path.display()));
+ return Err(download::Error::Validation(format!(
+ "{} is not a gzip archive",
+ path.display()
+ )));
}
Ok(())
}