π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Use Rust as mobile foreground downloader
laurenspriemd92cc5cb29b2
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.ktindex c57a260998..022e805ea6 100644--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt@@ -32,6 +32,7 @@ import io.ente.labs.inference_rs.downloadLlmModelFilesimport io.ente.labs.inference_rs.uniffiEnsureInitializedimport io.ente.labs.inference_rs.InferenceExceptionimport kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Jobimport kotlinx.coroutines.delayimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLock@@ -44,6 +45,7 @@ import java.io.Fileimport java.io.IOExceptionimport java.util.concurrent.ConcurrentHashMapimport java.util.concurrent.locks.ReentrantLock+import kotlin.coroutines.coroutineContextimport kotlin.math.maxclass InferenceRsProvider(@@ -364,7 +366,7 @@ class InferenceRsProvider(migrateLegacyDownloads(target)val modelFile = ModelDownloadSupport.modelPathFor(modelDir, target)if (!ModelDownloadSupport.isTargetDownloaded(modelDir, target)) {- awaitBackgroundDownload(target, onProgress)+ awaitForegroundDownload(target, onProgress)}onProgress(DownloadProgress(100, "Loading model..."))@@ -408,12 +410,31 @@ class InferenceRsProvider(throw lastError ?: IllegalStateException("Failed to load model")}+ private suspend fun awaitForegroundDownload(+ target: LlmModelTarget,+ onProgress: (DownloadProgress) -> Unit+ ) {+ cancelNativeDownloads(target)+ try {+ awaitRustForegroundDownload(target, onProgress)+ } catch (error: Throwable) {+ if (manualDownloadCancelled || error.isDownloadCancellation()) {+ throw error+ }+ if (externalDownloadsRoot == null || downloadManager == null) {+ throw error+ }+ Log.w("InferenceRsProvider", "Rust model download failed; falling back to DownloadManager", error)+ awaitBackgroundDownload(target, onProgress)+ }+ }+private suspend fun awaitBackgroundDownload(target: LlmModelTarget,onProgress: (DownloadProgress) -> Unit) {if (externalDownloadsRoot == null || downloadManager == null) {- awaitManualDownload(target, onProgress)+ awaitRustForegroundDownload(target, onProgress)return}ensureDownloadsEnqueued(target)@@ -446,10 +467,11 @@ class InferenceRsProvider(}}- private fun awaitManualDownload(+ private suspend fun awaitRustForegroundDownload(target: LlmModelTarget,onProgress: (DownloadProgress) -> Unit) {+ val downloadJob = coroutineContext[Job]manualDownloadCancelled = falsemanualDownloadActive = truetry {@@ -469,7 +491,8 @@ class InferenceRsProvider(onProgress(progress.toDomainProgress())}- override fun isCancelled(): Boolean = manualDownloadCancelled+ override fun isCancelled(): Boolean =+ manualDownloadCancelled || downloadJob?.isCancelled == true})} finally {@@ -477,6 +500,18 @@ class InferenceRsProvider(}}+ private fun Throwable.isDownloadCancellation(): Boolean {+ return message?.contains("cancelled", ignoreCase = true) == true+ }++ private fun cancelNativeDownloads(target: LlmModelTarget) {+ val ids = loadDownloadRecords(target).map { it.downloadId }.distinct()+ if (ids.isNotEmpty() && downloadManager != null) {+ downloadManager.remove(*ids.toLongArray())+ }+ clearDownloadRecords(target)+ }+private fun logDownloadMetrics(progress: LlmModelDownloadProgress) {if (progress.fileComplete) {Log.i(diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Services/InferenceRsProvider.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Services/InferenceRsProvider.swiftindex 0ad6b538fc..439aa9279e 100644--- a/mobile/native/darwin/Apps/Ensu/Ensu/Services/InferenceRsProvider.swift+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Services/InferenceRsProvider.swift@@ -158,16 +158,19 @@ final class InferenceRsProvider {if !downloads.isEmpty {onProgress(InferenceDownloadProgress(percent: 0, status: "Starting download..."))+ await downloadManager.cancelDownloads(for: downloads.map(downloadTarget(for:)))do {- await downloadManager.enqueueDownloads(downloads.map(downloadTarget(for:)))- try await waitForDownloads(expectedTargets, onProgress: onProgress)+ try await downloadWithRust(expectedTargets, onProgress: onProgress)} catch {- if error is CancellationError {- await downloadManager.cancelAllDownloads()+ if isDownloadCancellation(error) {throw error}- await downloadManager.cancelAllDownloads()- try await downloadWithRust(expectedTargets, onProgress: onProgress)+ logger.warning(+ "Rust model download failed; falling back to URLSession",+ details: "\(error.localizedDescription)"+ )+ await downloadManager.enqueueDownloads(downloads.map(downloadTarget(for:)))+ try await waitForDownloads(expectedTargets, onProgress: onProgress)}}@@ -553,7 +556,7 @@ final class InferenceRsProvider {LlmModelDownloadTarget(label: $0.label, url: $0.url, destinationPath: $0.destination.path)}- try await Task.detached(priority: .utility) { [weak self] in+ let downloadTask = Task.detached(priority: .utility) { [weak self] inguard let self else { return }let callback = ModelDownloadCallbackSink(onProgress: { progress in@@ -561,11 +564,18 @@ final class InferenceRsProvider {onProgress(progress.toInferenceProgress())},isCancelled: { [weak self] in- self?.isRustDownloadCancelled() ?? true+ (self?.isRustDownloadCancelled() ?? true) || Task.isCancelled})try downloadLlmModelFiles(targets: targets, callback: callback)- }.value+ }++ try await withTaskCancellationHandler {+ try await downloadTask.value+ } onCancel: {+ self.setRustDownloadCancelled(true)+ downloadTask.cancel()+ }}private func setRustDownloadCancelled(_ cancelled: Bool) {@@ -581,6 +591,12 @@ final class InferenceRsProvider {return cancelled}+ private func isDownloadCancellation(_ error: Error) -> Bool {+ error is CancellationError ||+ isRustDownloadCancelled() ||+ error.localizedDescription.range(of: "cancelled", options: .caseInsensitive) != nil+ }+private func logDownloadMetrics(_ progress: LlmModelDownloadProgress) {if progress.fileComplete {logger.info(diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Services/ModelDownloadManager.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Services/ModelDownloadManager.swiftindex b56f09a4de..fb2f59ec3e 100644--- a/mobile/native/darwin/Apps/Ensu/Ensu/Services/ModelDownloadManager.swift+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Services/ModelDownloadManager.swift@@ -157,6 +157,21 @@ final class ModelDownloadManager: NSObject {clearAllRecords()}+ func cancelDownloads(for targets: [ModelDownloadTarget]) async {+ let cancelledIds = Set(targets.map { recordId(for: $0.destination) })+ let tasks = await allTasks()+ tasks.forEach { task in+ guard let taskId = task.taskDescription, cancelledIds.contains(taskId) else { return }+ task.cancel()+ }+ mutateRecords { records in+ cancelledIds.forEach { id in+ guard let record = records.removeValue(forKey: id) else { return }+ removeResumeData(for: record)+ }+ }+ }+func cancelDownloads(except targets: [ModelDownloadTarget]) async {let allowedIds = Set(targets.map { recordId(for: $0.destination) })let tasks = await allTasks()