Skip to content

armgit / ente

Public Imported from GitHub
0

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

Type the fallback downloader errors

Manav Rathi3ad40a68bfb7
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 828eb56384..0292174706 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
@@ -474,7 +474,7 @@ internal class ChatStoreActions(
}
} catch (err: Throwable) {
val cancelled = err is kotlinx.coroutines.CancellationException ||
- err.message?.contains("cancel", ignoreCase = true) == true
+ err is LlmException.Cancelled
if (!isActive()) return@launch
streamingParentId = null
state.update { appState ->
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 05f8b9cb60..d9b45135fb 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
@@ -12,9 +12,20 @@ data class LlmModelTarget(
data class DownloadProgress(
val percent: Int,
- val status: String
+ val status: String,
+ val failure: DownloadFailure? = null
)
+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)
+ class InsufficientSpace : DownloadFailure(
+ "Not enough storage space to download the model. Please free up space and try again."
+ )
+ class TimedOut : DownloadFailure("Download timed out")
+ class Failed(message: String) : DownloadFailure(message)
+}
+
enum class LlmMessageRole {
User,
Assistant,
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 167be8f556..f30051507d 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
@@ -27,11 +27,11 @@ import io.ente.ensu.device.AndroidDeviceCapabilityProvider
import io.ente.ensu.device.requireChatSupported
import io.ente.ensu.format.formatBytes
import java.io.File
-import java.io.IOException
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.locks.ReentrantLock
import kotlin.coroutines.coroutineContext
import kotlin.math.max
+import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
@@ -261,13 +261,17 @@ class LlmProvider(
totalBytes += size
} else {
clearDownloadRecords(target)
- return@withContext DownloadProgress(-1, "${download.label} download is invalid")
+ val failure = DownloadFailure.InvalidContent(
+ "${download.label} download is invalid"
+ )
+ return@withContext DownloadProgress(-1, failure.message, failure)
}
}
DownloadManager.STATUS_FAILED -> {
clearDownloadRecords(target)
- return@withContext DownloadProgress(-1, userFacingDownloadFailure(row.reason))
+ val failure = downloadFailure(row.reason)
+ return@withContext DownloadProgress(-1, failure.message, failure)
}
}
}
@@ -464,13 +468,13 @@ class LlmProvider(
} else {
emptyPollCount = 0
if (progress.percent < 0) {
- throw IOException(progress.status)
+ throw progress.failure ?: DownloadFailure.Failed(progress.status)
}
onProgress(progress)
}
pollCount += 1
if (pollCount >= maxPolls) {
- throw IOException("Download timed out")
+ throw DownloadFailure.TimedOut()
}
delay(500)
}
@@ -510,9 +514,7 @@ class LlmProvider(
}
private fun Throwable.isDownloadCancellation(): Boolean {
- // The message check covers the system DownloadManager fallback path.
- return this is LlmException.Cancelled ||
- message?.contains("cancelled", ignoreCase = true) == true
+ return this is LlmException.Cancelled || this is CancellationException
}
private fun cancelNativeDownloads(target: LlmModelTarget) {
@@ -761,15 +763,15 @@ class LlmProvider(
}
}
- private fun userFacingDownloadFailure(reason: Int): String {
- return when (reason) {
- DownloadManager.ERROR_INSUFFICIENT_SPACE ->
- "Not enough storage space to download the model. Please free up space and try again."
- DownloadManager.ERROR_DEVICE_NOT_FOUND -> "Download storage is unavailable"
- DownloadManager.ERROR_CANNOT_RESUME -> "Download could not resume"
- DownloadManager.ERROR_UNHANDLED_HTTP_CODE,
- DownloadManager.ERROR_HTTP_DATA_ERROR -> "Download failed. Please try again."
- else -> "Download failed. Please try again."
+ private fun downloadFailure(reason: Int): DownloadFailure {
+ return when {
+ reason == DownloadManager.ERROR_INSUFFICIENT_SPACE -> DownloadFailure.InsufficientSpace()
+ reason in 400..599 -> DownloadFailure.Http(reason)
+ reason == DownloadManager.ERROR_DEVICE_NOT_FOUND ->
+ DownloadFailure.Failed("Download storage is unavailable")
+ reason == DownloadManager.ERROR_CANNOT_RESUME ->
+ DownloadFailure.Failed("Download could not resume")
+ else -> DownloadFailure.Failed("Download failed. Please try again.")
}
}
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 b8b1251967..af25128509 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
@@ -5,6 +5,10 @@ import io.ente.ensu.llm.LlmModelTarget
import io.ente.ensu.llm.LlmProvider
import io.ente.ensu.logging.FileLogRepository
import io.ente.ensu.bindings.ConfigDefaults
+import io.ente.ensu.bindings.DownloadError
+import io.ente.ensu.bindings.LlmException
+import android.system.ErrnoException
+import android.system.OsConstants
import io.ente.ensu.logging.LogLevel
import io.ente.ensu.settings.SessionPreferencesDataStore
import io.ente.ensu.AppState
@@ -235,7 +239,7 @@ internal class ModelSettingsActions(
}
} catch (err: Throwable) {
val cancelled = err is kotlinx.coroutines.CancellationException ||
- err.message?.contains("cancel", ignoreCase = true) == true
+ err is LlmException.Cancelled
val failureMessage = if (cancelled) {
"Download cancelled"
} else {
@@ -407,6 +411,7 @@ internal class ModelSettingsActions(
companion object {
private const val MAX_DOWNLOAD_RETRIES = 5
+ private val NON_RETRYABLE_HTTP = setOf(401, 403, 404)
private const val RETRY_DELAY_BASE_MS = 1500L
private const val RETRY_DELAY_MAX_MS = 12000L
private const val DEFAULT_TEMPERATURE = 0.5f
@@ -415,14 +420,16 @@ internal class ModelSettingsActions(
private fun shouldRetryDownload(err: Throwable, retryCount: Int): Boolean {
if (retryCount >= MAX_DOWNLOAD_RETRIES) return false
if (err is kotlinx.coroutines.CancellationException) return false
+ if (err is LlmException.Cancelled) return false
if (isOutOfStorageError(err)) return false
- val message = err.message.orEmpty()
- if (message.contains("not GGUF", ignoreCase = true)) return false
- if (message.contains("HTTP 401", ignoreCase = true) ||
- message.contains("HTTP 403", ignoreCase = true) ||
- message.contains("HTTP 404", ignoreCase = true)
- ) {
- return false
+ if (err is DownloadFailure.InvalidContent) return false
+ if (err is DownloadFailure.Http && err.status in NON_RETRYABLE_HTTP) return false
+ if (err is LlmException.Download) {
+ when (val error = err.error) {
+ is DownloadError.Validation -> return false
+ is DownloadError.Http -> if (error.status.toInt() in NON_RETRYABLE_HTTP) return false
+ else -> {}
+ }
}
return true
}
@@ -442,14 +449,11 @@ internal class ModelSettingsActions(
private fun isOutOfStorageError(err: Throwable): Boolean {
var current: Throwable? = err
while (current != null) {
- val message = current.message.orEmpty()
- if (message.contains("ENOSPC", ignoreCase = true) ||
- message.contains("No space left on device", ignoreCase = true) ||
- message.contains("disk is full", ignoreCase = true) ||
- message.contains("not enough storage", ignoreCase = true)
- ) {
+ if (current is DownloadFailure.InsufficientSpace) return true
+ if (current is LlmException.Download && current.error is DownloadError.StorageFull) {
return true
}
+ if (current is ErrnoException && current.errno == OsConstants.ENOSPC) return true
current = current.cause
}
return false
diff --git a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift
index 0d4ada624c..57b6680c6c 100644
--- a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift
+++ b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift
@@ -1959,8 +1959,7 @@ final class ChatViewModel: ObservableObject {
private func isCancellation(_ error: Error) -> Bool {
if error is CancellationError { return true }
if case LlmError.Cancelled = error { return true }
- // The description check covers the URLSession download fallback path.
- return error.localizedDescription.localizedCaseInsensitiveContains("cancel")
+ return (error as? URLError)?.code == .cancelled
}
private func seedDownloadProgressMemory() {
@@ -1987,11 +1986,13 @@ final class ChatViewModel: ObservableObject {
}
}
- // The message checks cover the URLSession download fallback path.
- let message = error.localizedDescription.lowercased()
- if message.contains("not gguf") { return false }
- if message.contains("http 401") || message.contains("http 403") || message.contains("http 404") {
+ switch error as? DownloadFailure {
+ case .invalidContent:
return false
+ case let .http(status):
+ if status == 401 || status == 403 || status == 404 { return false }
+ default:
+ break
}
return true
}
@@ -2014,26 +2015,9 @@ final class ChatViewModel: ObservableObject {
}
private func isOutOfStorageError(_ error: Error) -> Bool {
- func containsStorageMessage(_ message: String) -> Bool {
- let normalized = message.lowercased()
- return normalized.contains("no space left on device") ||
- normalized.contains("not enough space") ||
- normalized.contains("out of space") ||
- normalized.contains("disk is full") ||
- normalized.contains("enospc")
- }
-
- var current: NSError? = error as NSError
- while let nsError = current {
- if nsError.domain == NSCocoaErrorDomain && nsError.code == NSFileWriteOutOfSpaceError {
- return true
- }
- if containsStorageMessage(nsError.localizedDescription) {
- return true
- }
- current = nsError.userInfo[NSUnderlyingErrorKey] as? NSError
- }
- return containsStorageMessage(error.localizedDescription)
+ if case DownloadFailure.insufficientSpace = error { return true }
+ if case LlmError.Download(.storageFull) = error { return true }
+ return error.isOutOfDiskSpace
}
private nonisolated func attachmentsDirectory() throws -> URL {
diff --git a/mobile/native/apple/apps/ensu/Ensu/Services/LlmProvider.swift b/mobile/native/apple/apps/ensu/Ensu/Services/LlmProvider.swift
index 69305e0fc4..7308d98558 100644
--- a/mobile/native/apple/apps/ensu/Ensu/Services/LlmProvider.swift
+++ b/mobile/native/apple/apps/ensu/Ensu/Services/LlmProvider.swift
@@ -12,6 +12,48 @@ struct LlmModelTarget: Equatable {
struct DownloadProgress: Equatable {
let percent: Int
let status: String
+ var failure: DownloadFailure? = nil
+}
+
+enum DownloadFailure: Error, Codable, Equatable, LocalizedError {
+ case http(Int)
+ case invalidContent(String)
+ case insufficientSpace
+ case timedOut
+ case failed(String)
+
+ var message: String {
+ switch self {
+ case let .http(status):
+ return "Download failed: HTTP \(status)"
+ case let .invalidContent(message):
+ return message
+ case .insufficientSpace:
+ return "Not enough storage space to download the model. Please free up space and try again."
+ case .timedOut:
+ return "Download timed out"
+ case let .failed(message):
+ return message
+ }
+ }
+
+ var errorDescription: String? { message }
+}
+
+extension Error {
+ var isOutOfDiskSpace: Bool {
+ var current: NSError? = self as NSError
+ while let nsError = current {
+ if nsError.domain == NSCocoaErrorDomain, nsError.code == NSFileWriteOutOfSpaceError {
+ return true
+ }
+ if nsError.domain == NSPOSIXErrorDomain, nsError.code == Int(ENOSPC) {
+ return true
+ }
+ current = nsError.userInfo[NSUnderlyingErrorKey] as? NSError
+ }
+ return false
+ }
}
enum LlmMessageRole {
@@ -527,22 +569,14 @@ final class LlmProvider {
if let progress = await downloadManager.progress(for: managerTargets) {
if progress.percent == -1 {
- throw NSError(
- domain: "LlmProvider",
- code: -9,
- userInfo: [NSLocalizedDescriptionKey: progress.status]
- )
+ throw progress.failure ?? DownloadFailure.failed(progress.status)
}
onProgress(progress)
}
pollCount += 1
if pollCount >= maxPolls {
- throw NSError(
- domain: "LlmProvider",
- code: -10,
- userInfo: [NSLocalizedDescriptionKey: "Download timed out"]
- )
+ throw DownloadFailure.timedOut
}
try await Task.sleep(nanoseconds: 500_000_000)
}
@@ -594,10 +628,8 @@ final class LlmProvider {
private func isDownloadCancellation(_ error: Error) -> Bool {
if case LlmError.Cancelled = error { return true }
- // The description check covers the URLSession fallback path.
- return error is CancellationError ||
- isRustDownloadCancelled() ||
- error.localizedDescription.range(of: "cancelled", options: .caseInsensitive) != nil
+ if (error as? URLError)?.code == .cancelled { return true }
+ return error is CancellationError || isRustDownloadCancelled()
}
private func logDownloadMetrics(_ progress: LlmModelDownloadProgress) {
diff --git a/mobile/native/apple/apps/ensu/Ensu/Services/ModelDownloadManager.swift b/mobile/native/apple/apps/ensu/Ensu/Services/ModelDownloadManager.swift
index 7e0aa52856..d6e269f7c4 100644
--- a/mobile/native/apple/apps/ensu/Ensu/Services/ModelDownloadManager.swift
+++ b/mobile/native/apple/apps/ensu/Ensu/Services/ModelDownloadManager.swift
@@ -23,6 +23,7 @@ final class ModelDownloadManager: NSObject {
let destinationPath: String
var state: State
var errorMessage: String?
+ var failure: DownloadFailure?
var resumeDataFile: String?
}
@@ -69,12 +70,13 @@ final class ModelDownloadManager: NSObject {
destinationPath: target.destination.path,
state: .queued,
errorMessage: nil,
+ failure: nil,
resumeDataFile: nil
)
guard let url = URL(string: target.url) else {
saveRecord(record)
- markFailed(id: id, message: "Invalid URL")
+ markFailed(id: id, failure: .failed("Invalid URL"))
continue
}
@@ -105,8 +107,9 @@ final class ModelDownloadManager: NSObject {
}
if relevantTasks.isEmpty {
- if let failure = firstFailure(for: targets) {
- return DownloadProgress(percent: -1, status: failure)
+ 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 nil
}
@@ -204,9 +207,9 @@ final class ModelDownloadManager: NSObject {
return (attrs?[.size] as? NSNumber)?.int64Value ?? 0
}
- private func firstFailure(for targets: [ModelDownloadTarget]) -> String? {
+ private func firstFailure(for targets: [ModelDownloadTarget]) -> DownloadRecord? {
let ids = Set(targets.map { recordId(for: $0.destination) })
- return loadRecords().values.first(where: { ids.contains($0.id) && $0.state == .failed })?.errorMessage
+ return loadRecords().values.first(where: { ids.contains($0.id) && $0.state == .failed })
}
private func loadRecords() -> [String: DownloadRecord] {
@@ -265,10 +268,11 @@ final class ModelDownloadManager: NSObject {
}
}
- private func markFailed(id: String, message: String) {
+ private func markFailed(id: String, failure: DownloadFailure) {
updateRecord(id: id) { record in
record.state = .failed
- record.errorMessage = message
+ record.errorMessage = failure.message
+ record.failure = failure
}
}
@@ -276,6 +280,7 @@ final class ModelDownloadManager: NSObject {
updateRecord(id: id) { record in
record.state = .downloading
record.errorMessage = nil
+ record.failure = nil
removeResumeData(for: record)
record.resumeDataFile = nil
}
@@ -345,7 +350,7 @@ extension ModelDownloadManager: URLSessionDownloadDelegate, URLSessionTaskDelega
guard let record = loadRecords()[id] else { return }
if let response = downloadTask.response as? HTTPURLResponse,
!(200...299).contains(response.statusCode) {
- markFailed(id: id, message: "Download failed: HTTP \(response.statusCode)")
+ markFailed(id: id, failure: .http(response.statusCode))
return
}
@@ -353,7 +358,7 @@ extension ModelDownloadManager: URLSessionDownloadDelegate, URLSessionTaskDelega
do {
if !location.looksLikeGgufFile {
try? FileManager.default.removeItem(at: location)
- markFailed(id: id, message: "Downloaded file is not GGUF")
+ markFailed(id: id, failure: .invalidContent("Downloaded file is not GGUF"))
return
}
try FileManager.default.createDirectory(
@@ -367,7 +372,9 @@ extension ModelDownloadManager: URLSessionDownloadDelegate, URLSessionTaskDelega
try FileManager.default.moveItem(at: location, to: destination)
clearRecord(id: id)
} catch {
- markFailed(id: id, message: error.localizedDescription)
+ let failure: DownloadFailure =
+ error.isOutOfDiskSpace ? .insufficientSpace : .failed(error.localizedDescription)
+ markFailed(id: id, failure: failure)
}
}
@@ -379,6 +386,7 @@ extension ModelDownloadManager: URLSessionDownloadDelegate, URLSessionTaskDelega
updateRecord(id: id) { record in
record.state = .failed
record.errorMessage = error.localizedDescription
+ record.failure = .failed(error.localizedDescription)
removeResumeData(for: record)
record.resumeDataFile = persistResumeData(resumeData, for: id)
}
diff --git a/rust/bindings/uniffi/ensu/src/download.rs b/rust/bindings/uniffi/ensu/src/download.rs
index 35a17f099f..d3b41d94ba 100644
--- a/rust/bindings/uniffi/ensu/src/download.rs
+++ b/rust/bindings/uniffi/ensu/src/download.rs
@@ -1,5 +1,7 @@
use ente_ensu::download;
+const ENOSPC: i32 = 28;
+
#[derive(Debug, Clone, uniffi::Enum)]
pub enum DownloadError {
Cancelled,
@@ -9,6 +11,7 @@ pub enum DownloadError {
SizeMismatch { expected: u64, actual: u64 },
Protocol { message: String },
InvalidTarget { message: String },
+ StorageFull,
Io { message: String },
}
@@ -26,9 +29,15 @@ impl From<download::Error> for DownloadError {
}
download::Error::Protocol(message) => Self::Protocol { message },
download::Error::InvalidTarget(message) => Self::InvalidTarget { message },
- download::Error::Io(err) => Self::Io {
- message: err.to_string(),
- },
+ download::Error::Io(err) => {
+ if err.raw_os_error() == Some(ENOSPC) {
+ Self::StorageFull
+ } else {
+ Self::Io {
+ message: err.to_string(),
+ }
+ }
+ }
download::Error::Json(err) => Self::Io {
message: err.to_string(),
},