π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Make the Rust downloader the sole model download path on Android
Manav Rathibf4229390d44
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.ktindex d7d7c0e927..94998d1ba6 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt@@ -33,7 +33,6 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {val logRepository = FileLogRepository(application)private val llmProvider = LlmProvider(- context = application,modelDir = resolveModelDir(application),transcriber = transcriber,legacyModelDir = File(application.filesDir, "llm"),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.ktindex 77d0f6da4f..d6cf0efdb9 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,7 +13,6 @@ data class LlmModelTarget(data class DownloadProgress(val percent: Int?,val status: String,- val failure: DownloadFailure? = null,val phase: DownloadPhase = DownloadPhase.Downloading)@@ -24,16 +23,6 @@ enum class DownloadPhase {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)- 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.ktindex b6d67e9832..84cbf322b3 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@@ -1,9 +1,5 @@package io.ente.ensu.llm-import android.app.DownloadManager-import android.content.Context-import android.net.Uri-import android.os.Environmentimport android.util.Logimport io.ente.ensu.bindings.LlmChatMessage as NativeChatMessageimport io.ente.ensu.bindings.LlmChatRequest@@ -31,20 +27,14 @@ import java.util.concurrent.ConcurrentHashMapimport java.util.concurrent.locks.ReentrantLockimport kotlin.coroutines.coroutineContextimport kotlin.math.max-import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Job-import kotlinx.coroutines.delayimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLockimport kotlinx.coroutines.withContext-import kotlinx.serialization.Serializable-import kotlinx.serialization.encodeToString-import kotlinx.serialization.json.Jsonimport okhttp3.OkHttpClientclass LlmProvider(- context: Context,private val modelDir: File,private val transcriber: Transcriber,private val deviceCapabilityProvider: AndroidDeviceCapabilityProvider,@@ -56,30 +46,7 @@ class LlmProvider(val requestedContextLength: Int?)- @Serializable- private data class DownloadRecord(- val downloadId: Long,- val label: String,- val url: String,- val destinationPath: String- )-- private data class DownloadRow(- val status: Int,- val reason: Int,- val bytesDownloaded: Long,- val totalBytes: Long- )-private val httpClient = OkHttpClient()- private val appContext = context.applicationContext- private val externalDownloadsRoot =- appContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)- private val downloadManager =- appContext.getSystemService(DownloadManager::class.java)- private val downloadPrefs =- appContext.getSharedPreferences("ensu.system.downloads", Context.MODE_PRIVATE)- private val json = Json { ignoreUnknownKeys = true }@Volatile private var loadedModel: LlmModel? = null@Volatile private var loadedContext: LlmContext? = null@@ -157,7 +124,7 @@ class LlmProvider(withContext(ioDispatcher) {runCatching {modelLoadMutex.withLock {- if (!isDownloadComplete(target)) return@withLock+ if (!ModelDownloadSupport.isTargetDownloaded(modelDir, target)) return@withLockval mmprojPath = ModelDownloadSupport.mmprojPathFor(modelDir, target)?.takeIf { it.exists() }?.absolutePath@@ -177,7 +144,7 @@ class LlmProvider(fun isModelDownloaded(target: LlmModelTarget): Boolean {migrateLegacyDownloads(target)- return isDownloadComplete(target)+ return ModelDownloadSupport.isTargetDownloaded(modelDir, target)}suspend fun estimateModelDownloadSize(target: LlmModelTarget): Long? = withContext(ioDispatcher) {@@ -202,104 +169,6 @@ class LlmProvider(if (sizes.isEmpty()) null else sizes.sum()}- suspend fun currentDownloadProgress(target: LlmModelTarget): DownloadProgress? =- withContext(ioDispatcher) {- migrateLegacyDownloads(target)- val targets = ModelDownloadSupport.expectedTargets(modelDir, target)- val records = loadDownloadRecords(target)- if (records.isEmpty()) {- if (ModelDownloadSupport.isTargetDownloaded(modelDir, target)) {- clearDownloadRecords(target)- }- return@withContext null- }- val recordsByPath = records.associateBy { it.destinationPath }-- val rowsById = queryDownloadRows(recordsByPath.values.map { it.downloadId })- var hasActiveDownload = false- var hasKnownTotal = true- var downloadedBytes = 0L- var totalBytes = 0L-- for (download in targets) {- val record = recordsByPath[download.destination.absolutePath]- if (record == null) {- if (download.destination.exists() && ModelDownloadSupport.looksLikeGguf(download.destination)) {- val size = download.destination.length().coerceAtLeast(0L)- downloadedBytes += size- totalBytes += size- continue- }- hasKnownTotal = false- continue- }- val row = rowsById[record.downloadId]- if (row == null) {- hasKnownTotal = false- continue- }-- when (row.status) {- DownloadManager.STATUS_PENDING,- DownloadManager.STATUS_PAUSED,- DownloadManager.STATUS_RUNNING -> {- hasActiveDownload = true- downloadedBytes += row.bytesDownloaded.coerceAtLeast(0L)- if (row.totalBytes > 0) {- totalBytes += row.totalBytes- } else {- hasKnownTotal = false- }- }-- DownloadManager.STATUS_SUCCESSFUL -> {- if (download.destination.exists() &&- ModelDownloadSupport.looksLikeGguf(download.destination)- ) {- val size = download.destination.length().coerceAtLeast(0L)- downloadedBytes += size- totalBytes += size- } else {- clearDownloadRecords(target)- val failure = DownloadFailure.InvalidContent(- "${download.label} download is invalid"- )- return@withContext DownloadProgress(- null, failure.message, failure, DownloadPhase.Failed- )- }- }-- DownloadManager.STATUS_FAILED -> {- clearDownloadRecords(target)- val failure = downloadFailure(row.reason)- return@withContext DownloadProgress(- null, failure.message, failure, DownloadPhase.Failed- )- }- }- }-- if (!hasActiveDownload) {- if (isDownloadComplete(target)) {- clearDownloadRecords(target)- }- return@withContext null- }-- val percent = if (hasKnownTotal && totalBytes > 0) {- ((downloadedBytes * 100) / totalBytes).toInt().coerceIn(0, 99)- } else {- 0- }- val status = if (hasKnownTotal && totalBytes > 0) {- "Downloading... ${io.ente.ensu.format.formatBytes(downloadedBytes)} / ${io.ente.ensu.format.formatBytes(totalBytes)}"- } else {- "Downloading model..."- }- DownloadProgress(percent = percent, status = status)- }-fun loadedContextLength(target: LlmModelTarget): Int? {val modelKey = LoadedModelKey(target.id, target.contextLength)return if (currentModelKey == modelKey && loadedContext != null && loadedModel != null) {@@ -331,11 +200,6 @@ class LlmProvider(fun cancelDownload() {manualDownloadCancelled = true- val ids = loadAllDownloadRecords().map { it.downloadId }.distinct()- if (ids.isNotEmpty() && downloadManager != null) {- downloadManager.remove(*ids.toLongArray())- }- clearAllDownloadRecords()}private fun LlmMessage.roleString(): String {@@ -383,7 +247,7 @@ class LlmProvider(migrateLegacyDownloads(target)val modelFile = ModelDownloadSupport.modelPathFor(modelDir, target)if (!ModelDownloadSupport.isTargetDownloaded(modelDir, target)) {- awaitForegroundDownload(target, onProgress)+ awaitRustForegroundDownload(target, onProgress)}onProgress(DownloadProgress(100, "Loading model...", phase = DownloadPhase.Loading))@@ -427,61 +291,6 @@ class LlmProvider(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("LlmProvider", "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) {- awaitRustForegroundDownload(target, onProgress)- return- }- ensureDownloadsEnqueued(target)- val maxPolls = 7_200- var emptyPollCount = 0- var pollCount = 0- while (true) {- val progress = currentDownloadProgress(target)- if (progress == null) {- if (isDownloadComplete(target)) {- clearDownloadRecords(target)- return- }- emptyPollCount += 1- if (emptyPollCount >= 3) {- ensureDownloadsEnqueued(target)- }- } else {- emptyPollCount = 0- progress.failure?.let { throw it }- onProgress(progress)- }- pollCount += 1- if (pollCount >= maxPolls) {- throw DownloadFailure.TimedOut()- }- delay(500)- }- }-private suspend fun awaitRustForegroundDownload(target: LlmModelTarget,onProgress: (DownloadProgress) -> Unit@@ -515,18 +324,6 @@ class LlmProvider(}}- private fun Throwable.isDownloadCancellation(): Boolean {- return this is LlmException.Cancelled || this is CancellationException- }-- 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(@@ -576,151 +373,6 @@ class LlmProvider(return DownloadProgress(percent, status)}- private fun ensureDownloadsEnqueued(target: LlmModelTarget) {- val manager = downloadManager ?: return- val expectedTargets = ModelDownloadSupport.expectedTargets(modelDir, target)- val existingRecords = loadDownloadRecords(target).associateBy { it.destinationPath }- val rowsById = queryDownloadRows(existingRecords.values.map { it.downloadId })- val updatedRecords = mutableListOf<DownloadRecord>()-- expectedTargets.forEach { download ->- if (download.destination.exists() && ModelDownloadSupport.looksLikeGguf(download.destination)) {- return@forEach- }-- val existingRecord = existingRecords[download.destination.absolutePath]- val existingRow = existingRecord?.let { rowsById[it.downloadId] }- val keepExisting = existingRecord != null && existingRow != null && existingRow.status in setOf(- DownloadManager.STATUS_PENDING,- DownloadManager.STATUS_PAUSED,- DownloadManager.STATUS_RUNNING,- DownloadManager.STATUS_SUCCESSFUL- )- if (keepExisting) {- updatedRecords += requireNotNull(existingRecord)- return@forEach- }-- if (download.destination.exists() && !ModelDownloadSupport.looksLikeGguf(download.destination)) {- download.destination.delete()- }-- val request = DownloadManager.Request(Uri.parse(download.url))- .setTitle("Downloading model")- .setDescription(download.label)- .setMimeType("application/octet-stream")- .setAllowedOverMetered(true)- .setAllowedOverRoaming(true)- .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)- .setDestinationInExternalFilesDir(- appContext,- Environment.DIRECTORY_DOWNLOADS,- relativeDestinationPath(download.destination)- )- val id = manager.enqueue(request)- updatedRecords += DownloadRecord(- downloadId = id,- label = download.label,- url = download.url,- destinationPath = download.destination.absolutePath- )- }-- saveDownloadRecords(target, updatedRecords)- }-- private fun queryDownloadRows(ids: Collection<Long>): Map<Long, DownloadRow> {- if (ids.isEmpty()) return emptyMap()- val manager = downloadManager ?: return emptyMap()- val query = DownloadManager.Query().setFilterById(*ids.toLongArray())- val rows = mutableMapOf<Long, DownloadRow>()- manager.query(query)?.use { cursor ->- val idColumn = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID)- val statusColumn = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS)- val reasonColumn = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON)- val downloadedColumn =- cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)- val totalColumn = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)- while (cursor.moveToNext()) {- rows[cursor.getLong(idColumn)] = DownloadRow(- status = cursor.getInt(statusColumn),- reason = cursor.getInt(reasonColumn),- bytesDownloaded = cursor.getLong(downloadedColumn),- totalBytes = cursor.getLong(totalColumn)- )- }- }- return rows- }-- private fun loadDownloadRecords(target: LlmModelTarget): List<DownloadRecord> {- val raw = downloadPrefs.getString(downloadPrefsKey(target), null) ?: return emptyList()- return runCatching { json.decodeFromString<List<DownloadRecord>>(raw) }.getOrDefault(emptyList())- }-- private fun saveDownloadRecords(target: LlmModelTarget, records: List<DownloadRecord>) {- val editor = downloadPrefs.edit()- if (records.isEmpty()) {- editor.remove(downloadPrefsKey(target))- } else {- editor.putString(downloadPrefsKey(target), json.encodeToString(records))- }- editor.apply()- }-- private fun clearDownloadRecords(target: LlmModelTarget) {- downloadPrefs.edit().remove(downloadPrefsKey(target)).apply()- }-- private fun loadAllDownloadRecords(): List<DownloadRecord> {- return downloadPrefs.all.keys- .filter { it.startsWith(DOWNLOAD_PREF_PREFIX) }- .flatMap { key ->- val raw = downloadPrefs.getString(key, null).orEmpty()- runCatching { json.decodeFromString<List<DownloadRecord>>(raw) }.getOrDefault(emptyList())- }- }-- private fun clearAllDownloadRecords() {- val editor = downloadPrefs.edit()- downloadPrefs.all.keys- .filter { it.startsWith(DOWNLOAD_PREF_PREFIX) }- .forEach(editor::remove)- editor.apply()- }-- private fun downloadPrefsKey(target: LlmModelTarget): String = "$DOWNLOAD_PREF_PREFIX${target.id}"-- private fun relativeDestinationPath(destination: File): String {- val root = externalDownloadsRoot?.absoluteFile?.toPath()?.normalize()- ?: error("External downloads directory unavailable")- val destinationPath = destination.absoluteFile.toPath().normalize()- return root.relativize(destinationPath).toString()- }-- private fun isDownloadComplete(target: LlmModelTarget): Boolean {- val records = loadDownloadRecords(target)- if (records.isEmpty()) {- return ModelDownloadSupport.isTargetDownloaded(modelDir, target)- }-- val rowsById = queryDownloadRows(records.map { it.downloadId })- val hasActiveDownload = rowsById.values.any { row ->- row.status == DownloadManager.STATUS_PENDING ||- row.status == DownloadManager.STATUS_PAUSED ||- row.status == DownloadManager.STATUS_RUNNING- }- if (hasActiveDownload) {- return false- }-- val isDownloaded = ModelDownloadSupport.isTargetDownloaded(modelDir, target)- if (isDownloaded) {- clearDownloadRecords(target)- }- return isDownloaded- }-private fun migrateLegacyDownloads(target: LlmModelTarget) {val legacyDir = legacyModelDir ?: returnif (legacyDir.absolutePath == modelDir.absolutePath) return@@ -765,22 +417,6 @@ class LlmProvider(}}- 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.")- }- }-- companion object {- private const val DOWNLOAD_PREF_PREFIX = "target."- }-private fun generateStreamWithCallback(context: LlmContext,request: LlmChatRequest,diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelDownloadSupport.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelDownloadSupport.ktindex 081fb49b35..192e07ae86 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelDownloadSupport.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelDownloadSupport.kt@@ -1,12 +1,9 @@package io.ente.ensu.llm-import io.ente.ensu.llm.DownloadProgressimport io.ente.ensu.llm.LlmModelTarget-import io.ente.ensu.format.formatBytesimport okhttp3.OkHttpClientimport okhttp3.Requestimport java.io.File-import java.io.FileOutputStreamimport java.io.IOExceptionimport java.security.MessageDigest@@ -44,12 +41,6 @@ internal object ModelDownloadSupport {return pathForUrl(modelDir, target, url, fallback = "mmproj.gguf")}- fun existingDownloadBytes(dest: File): Long {- if (dest.exists()) return dest.length()- val tmp = File(dest.absolutePath + ".tmp")- return tmp.length().takeIf { tmp.exists() && it > 0 } ?: 0L- }-fun fetchContentLength(httpClient: OkHttpClient, url: String): Long? {val request = Request.Builder().url(url).head().build()return try {@@ -63,63 +54,6 @@ internal object ModelDownloadSupport {}}- fun downloadTargets(- httpClient: OkHttpClient,- targets: List<DownloadTarget>,- onProgress: (DownloadProgress) -> Unit,- isCancelled: () -> Boolean- ) {- val downloads = targets.filterNot { it.destination.exists() }- if (downloads.isEmpty()) return-- targets.forEach { it.destination.parentFile?.mkdirs() }-- val lengths = targets.map { download ->- download.destination.length().takeIf { it > 0 } ?: fetchContentLength(httpClient, download.url)- }- val totalBytes = lengths.filterNotNull().sum()- val hasTotal = lengths.all { it != null } && totalBytes > 0- var downloadedSoFar = targets.zip(lengths).sumOf { (download, total) ->- existingDownloadBytes(download.destination).coerceAtMost(total ?: existingDownloadBytes(download.destination))- }-- if (hasTotal && downloadedSoFar > 0) {- val initialPercent = ((downloadedSoFar * 100) / totalBytes).toInt().coerceIn(0, 99)- onProgress(- DownloadProgress(- percent = initialPercent,- status = "Downloading... ${formatBytes(downloadedSoFar)} / ${formatBytes(totalBytes)}"- )- )- } else {- onProgress(DownloadProgress(percent = 0, status = "Starting download..."))- }-- downloads.forEach { download ->- val expectedIndex = targets.indexOfFirst { it.destination == download.destination }- val fileTotal = lengths.getOrNull(expectedIndex)- val existingBytesForFile = existingDownloadBytes(download.destination)- val bytesBeforeFile = downloadedSoFar - existingBytesForFile- downloadFile(httpClient, download.url, download.destination, isCancelled) { downloaded, total ->- val overallDownloaded = bytesBeforeFile + downloaded- val percent = if (hasTotal) {- ((overallDownloaded * 100) / totalBytes).toInt()- } else {- val step = 100f / targets.size- val filePercent = total?.let { downloaded.toFloat() / it } ?: 0f- ((expectedIndex.coerceAtLeast(0) * step) + (filePercent * step)).toInt()- }- val status = if (hasTotal) {- "Downloading... ${formatBytes(overallDownloaded)} / ${formatBytes(totalBytes)}"- } else {- "Downloading ${download.label.lowercase()}... ${formatBytes(downloaded)}"- }- onProgress(DownloadProgress(percent = percent.coerceIn(0, 99), status = status))- }- downloadedSoFar = bytesBeforeFile + (fileTotal ?: existingDownloadBytes(download.destination))- }- }-fun looksLikeGguf(file: File): Boolean {if (!file.exists() || file.length() < 4) return falseval header = ByteArray(4)@@ -129,112 +63,6 @@ internal object ModelDownloadSupport {return header.contentEquals("GGUF".toByteArray())}- private fun downloadFile(- httpClient: OkHttpClient,- url: String,- dest: File,- isCancelled: () -> Boolean,- onProgress: (Long, Long?) -> Unit- ) {- val tmp = File(dest.absolutePath + ".tmp")- var existing = if (tmp.exists()) tmp.length() else 0L- if (existing > 0 && !looksLikeGguf(tmp)) {- tmp.delete()- existing = 0L- }-- while (true) {- val requestBuilder = Request.Builder().url(url)- if (existing > 0) {- requestBuilder.header("Range", "bytes=$existing-")- }- val call = httpClient.newCall(requestBuilder.build())-- val response = call.execute()- if (!response.isSuccessful) {- response.close()- throw IOException("Download failed: HTTP ${response.code}")- }-- if (existing > 0 && response.code == 200) {- response.close()- tmp.delete()- existing = 0L- continue- }-- val body = response.body ?: throw IOException("Empty response body")- val totalBytes = resolveTotalBytes(response, existing, body.contentLength())- if (totalBytes != null && totalBytes <= existing) {- response.close()- tmp.delete()- existing = 0L- continue- }-- val append = existing > 0 && response.code == 206- var downloaded = existing-- FileOutputStream(tmp, append).use { out ->- body.byteStream().use { input ->- val buffer = ByteArray(DEFAULT_BUFFER_SIZE)- while (true) {- if (isCancelled()) {- call.cancel()- response.close()- tmp.delete()- throw IOException("Download cancelled")- }- val read = input.read(buffer)- if (read == -1) break- out.write(buffer, 0, read)- downloaded += read- onProgress(downloaded, totalBytes)- }- }- }- response.close()-- if (totalBytes != null && downloaded < totalBytes) {- tmp.delete()- throw IOException("Download incomplete")- }-- if (!looksLikeGguf(tmp)) {- tmp.delete()- throw IOException("Downloaded file is not GGUF")- }- if (dest.exists()) dest.delete()- if (!tmp.renameTo(dest)) {- try {- tmp.copyTo(dest, overwrite = true)- if (!tmp.delete()) {- throw IOException("Failed to delete temporary download file")- }- } catch (error: IOException) {- dest.delete()- tmp.delete()- throw error- }- }- return- }- }-- private fun resolveTotalBytes(- response: okhttp3.Response,- existing: Long,- remainingLength: Long- ): Long? {- val contentLength = remainingLength.takeIf { it > 0 }- if (existing > 0 && response.code == 206) {- val contentRange = response.header("Content-Range")- val totalFromRange = contentRange?.substringAfter('/')?.toLongOrNull()- return totalFromRange ?: contentLength?.let { existing + it }- }- return contentLength- }-private fun pathForUrl(modelDir: File, target: LlmModelTarget, url: String, fallback: String): File {val baseDir = File(modelDir, "models")val filename = filenameForUrl(url, fallback)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.ktindex 632a79ca4b..227186ac45 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@@ -15,7 +15,6 @@ import kotlinx.coroutines.Jobimport kotlinx.coroutines.delayimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.update-import kotlinx.coroutines.isActiveimport kotlinx.coroutines.launchinternal class ModelSettingsActions(@@ -27,7 +26,6 @@ internal class ModelSettingsActions() {private var scope: CoroutineScope? = nullprivate var modelDownloadJob: Job? = null- private var downloadProgressMonitorJob: Job? = nullfun setScope(scope: CoroutineScope) {this.scope = scope@@ -42,8 +40,6 @@ internal class ModelSettingsActions(if (downloadIdentityChanged(oldTarget, newTarget)) {modelDownloadJob?.cancel()modelDownloadJob = null- downloadProgressMonitorJob?.cancel()- downloadProgressMonitorJob = nullllmProvider.cancelDownload()}refreshModelDownloadInfo()@@ -65,7 +61,6 @@ internal class ModelSettingsActions(fun refreshModelDownloadInfo() {if (!state.value.chat.deviceCapability.isChatSupported()) {- downloadProgressMonitorJob?.cancel()modelDownloadJob?.cancel()llmProvider.cancelDownload()persistModelDownloadRequested(false)@@ -86,7 +81,6 @@ internal class ModelSettingsActions(val target = resolveTarget(state.value.modelSettings)val isDownloaded = llmProvider.isModelDownloaded(target)if (isDownloaded) {- downloadProgressMonitorJob?.cancel()persistModelDownloadRequested(false)}state.update { appState ->@@ -107,25 +101,7 @@ internal class ModelSettingsActions(val scope = scope ?: returnscope.launch {- val progress = llmProvider.currentDownloadProgress(target)- if (progress != null) {- val isFailure = progress.phase == DownloadPhase.Failed- persistModelDownloadRequested(!isFailure)- state.update { appState ->- appState.copy(- chat = appState.chat.copy(- isDownloading = !isFailure,- downloadPercent = progress.percent,- downloadStatus = progress.status,- downloadPhase = progress.phase,- hasRequestedModelDownload = !isFailure- )- )- }- if (!isFailure) {- startDownloadProgressMonitor(target)- }- } else if (!llmProvider.isManualDownloadActive && modelDownloadJob?.isActive != true) {+ if (!llmProvider.isManualDownloadActive && modelDownloadJob?.isActive != true) {persistModelDownloadRequested(false)state.update { appState ->appState.copy(@@ -197,7 +173,6 @@ internal class ModelSettingsActions(modelDownloadJob = scope.launch {var loggedComplete = false- startDownloadProgressMonitor(target)val progressTracker = DownloadProgressTracker(initialPercent = if (isDownloaded) null else 0,initialStatus = if (isDownloaded) null else "Starting download..."@@ -306,7 +281,6 @@ internal class ModelSettingsActions(fun cancelModelDownload() {modelDownloadJob?.cancel()modelDownloadJob = null- downloadProgressMonitorJob?.cancel()llmProvider.cancelDownload()persistModelDownloadRequested(false)state.update { appState ->@@ -323,46 +297,6 @@ internal class ModelSettingsActions(refreshModelDownloadInfo()}- private fun startDownloadProgressMonitor(target: LlmModelTarget) {- val scope = scope ?: return- downloadProgressMonitorJob?.cancel()- downloadProgressMonitorJob = scope.launch {- var emptyPollCount = 0- while (isActive) {- val progress = llmProvider.currentDownloadProgress(target)- if (progress == null) {- emptyPollCount += 1- if (emptyPollCount >= 6) {- break- }- delay(500)- continue- }- emptyPollCount = 0- val isFailure = progress.phase == DownloadPhase.Failed- if (isFailure) {- persistModelDownloadRequested(false)- }- state.update { appState ->- appState.copy(- chat = appState.chat.copy(- isDownloading = !isFailure,- downloadPercent = progress.percent,- downloadStatus = progress.status,- downloadPhase = progress.phase,- hasRequestedModelDownload = if (isFailure) false else appState.chat.hasRequestedModelDownload- )- )- }- if (isFailure) {- break- }- delay(500)- }- refreshModelDownloadInfo()- }- }-private fun persistModelDownloadRequested(requested: Boolean) {scope?.launch {runCatching {@@ -428,8 +362,6 @@ internal class ModelSettingsActions(if (err is kotlinx.coroutines.CancellationException) return falseif (err is LlmException.Cancelled) return falseif (isOutOfStorageError(err)) return false- if (err is DownloadFailure.InvalidContent) return false- if (err is DownloadFailure.Http && err.status in NON_RETRYABLE_HTTP) return falseif (err is LlmException.Download) {when (val error = err.error) {is DownloadError.Validation -> return false@@ -455,7 +387,6 @@ internal class ModelSettingsActions(private fun isOutOfStorageError(err: Throwable): Boolean {var current: Throwable? = errwhile (current != null) {- if (current is DownloadFailure.InsufficientSpace) return trueif (current is LlmException.Download && current.error is DownloadError.StorageFull) {return true}