π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Resume model downloads across app restarts
Prateek Sunal880e27033685
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.ktindex c45b27e820..5eefcc48f3 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@@ -3,11 +3,13 @@ package io.ente.ensuimport android.app.Applicationimport android.os.Buildimport android.content.pm.PackageManager+import android.os.Environmentimport androidx.lifecycle.AndroidViewModelimport androidx.lifecycle.viewModelScopeimport io.ente.ensu.data.AdvancedSettingsDataStoreimport io.ente.ensu.data.EndpointPreferencesDataStoreimport io.ente.ensu.data.SessionPreferencesDataStore+import io.ente.ensu.data.getModelDownloadRequestedSyncimport io.ente.ensu.data.auth.EnsuAuthServiceimport io.ente.ensu.data.logging.FileLogRepositoryimport io.ente.ensu.data.storage.CredentialStore@@ -30,7 +32,9 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {val logRepository = FileLogRepository(application)private val llmProvider = InferenceRsProvider(- modelDir = File(application.filesDir, "llm")+ context = application,+ modelDir = resolveModelDir(application),+ legacyModelDir = File(application.filesDir, "llm"))private val chatRepository = RustChatRepository(application, credentialStore)private val chatSyncRepository = RustChatSyncRepository(@@ -78,6 +82,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {}}+ store.hydrateModelDownloadRequested(sessionPreferences.getModelDownloadRequestedSync())store.bootstrap(viewModelScope)val email = credentialStore.getEmail()if (credentialStore.isLoggedIn() && !email.isNullOrBlank()) {@@ -117,4 +122,12 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {}return "$versionName+$versionCode"}++ private fun resolveModelDir(application: Application): File {+ val root = application.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+ ?: application.getExternalFilesDir(null)+ ?: application.externalCacheDir+ ?: application.filesDir+ return File(root, "llm")+ }}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.ktindex d3e5aa2bc2..ead9d92425 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@@ -90,7 +90,6 @@ fun HomeView(val context = androidx.compose.ui.platform.LocalContext.currentval navController = rememberAnimatedNavController()val lifecycleOwner = LocalLifecycleOwner.current- val latestChatState by rememberUpdatedState(appState.chat)val latestStore by rememberUpdatedState(store)val navBackStackEntry by navController.currentBackStackEntryAsState()val currentRoute = navBackStackEntry?.destination?.route ?: HomeRoute.Chat@@ -186,15 +185,7 @@ fun HomeView(DisposableEffect(lifecycleOwner) {val observer = LifecycleEventObserver { _, event ->if (event == Lifecycle.Event.ON_RESUME) {- val chatState = latestChatState- if (- chatState.hasRequestedModelDownload &&- !chatState.isModelDownloaded &&- !chatState.isDownloading &&- !chatState.isGenerating- ) {- latestStore.startModelDownload(userInitiated = false)- }+ latestStore.refreshModelDownloadInfo()}}lifecycleOwner.lifecycle.addObserver(observer)diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.ktindex 54e3b096bb..cb116f5d4a 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt@@ -104,24 +104,6 @@ fun ChatView(}}- val shouldAutoDownload by remember(- chatState.hasRequestedModelDownload,- chatState.isDownloading,- chatState.isGenerating- ) {- derivedStateOf {- chatState.hasRequestedModelDownload &&- !chatState.isDownloading &&- !chatState.isGenerating- }- }-- LaunchedEffect(chatState.isModelDownloaded, shouldAutoDownload) {- if (!chatState.isModelDownloaded && shouldAutoDownload) {- onStartDownload(false)- }- }-val sessionKey = chatState.currentSessionId ?: "new-session"val editingMessage by remember(chatState.editingMessageId, chatState.messages) {diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/modelsettings/ModelSettingsScreen.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/modelsettings/ModelSettingsScreen.ktindex 664891c0f4..2d852e39d6 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/modelsettings/ModelSettingsScreen.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/modelsettings/ModelSettingsScreen.kt@@ -63,10 +63,10 @@ fun ModelSettingsScreen(mmproj = "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/mmproj-LFM2.5-VL-1.6b-Q8_0.gguf"),ModelChoice(- id = "qwen-2b",- title = "Qwen 3.5 2B (Q8_0)",- url = "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/Qwen3.5-2B-Q8_0.gguf?download=true",- mmproj = "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/mmproj-F16.gguf"+ id = "qwen-0.8b",+ title = "Qwen 3.5 0.8B (Q4_K_M)",+ url = "https://huggingface.co/unsloth/Qwen3.5-0.8B-GGUF/resolve/main/Qwen3.5-0.8B-Q4_K_M.gguf?download=true",+ mmproj = "https://huggingface.co/unsloth/Qwen3.5-0.8B-GGUF/resolve/main/mmproj-F16.gguf"),ModelChoice(id = CUSTOM_OPTION_ID,diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/SessionPreferencesDataStore.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/SessionPreferencesDataStore.ktindex 61e09bcfd0..6023722fcc 100644--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/SessionPreferencesDataStore.kt+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/SessionPreferencesDataStore.kt@@ -3,6 +3,7 @@ package io.ente.ensu.dataimport android.content.Contextimport androidx.datastore.core.DataStoreimport androidx.datastore.preferences.core.Preferences+import androidx.datastore.preferences.core.booleanPreferencesKeyimport androidx.datastore.preferences.core.editimport androidx.datastore.preferences.core.stringPreferencesKeyimport androidx.datastore.preferences.preferencesDataStoreFile@@ -13,9 +14,7 @@ import kotlinx.coroutines.flow.mapimport org.json.JSONObjectclass SessionPreferencesDataStore(context: Context) : SessionPreferences {- private val dataStore: DataStore<Preferences> = PreferenceDataStoreFactory.create {- context.preferencesDataStoreFile("ensu_session_prefs")- }+ private val dataStore: DataStore<Preferences> = getDataStore(context.applicationContext)override val selectedSessionId: Flow<String?> = dataStore.data.map { preferences ->preferences[Keys.SELECTED_SESSION_ID]@@ -25,6 +24,10 @@ class SessionPreferencesDataStore(context: Context) : SessionPreferences {decodeSessionSummaries(preferences[Keys.SESSION_SUMMARIES])}+ override val modelDownloadRequested: Flow<Boolean> = dataStore.data.map { preferences ->+ preferences[Keys.MODEL_DOWNLOAD_REQUESTED] ?: false+ }+override suspend fun setSelectedSessionId(sessionId: String?) {dataStore.edit { preferences ->if (sessionId == null) {@@ -47,6 +50,12 @@ class SessionPreferencesDataStore(context: Context) : SessionPreferences {}}+ override suspend fun setModelDownloadRequested(requested: Boolean) {+ dataStore.edit { preferences ->+ preferences[Keys.MODEL_DOWNLOAD_REQUESTED] = requested+ }+ }+private fun decodeSessionSummaries(raw: String?): Map<String, String> {if (raw.isNullOrBlank()) return emptyMap()return runCatching {@@ -75,5 +84,21 @@ class SessionPreferencesDataStore(context: Context) : SessionPreferences {private object Keys {val SELECTED_SESSION_ID = stringPreferencesKey("selected_session_id")val SESSION_SUMMARIES = stringPreferencesKey("session_summaries")+ val MODEL_DOWNLOAD_REQUESTED = booleanPreferencesKey("model_download_requested")+ }++ companion object {+ @Volatile+ private var instance: DataStore<Preferences>? = null++ private fun getDataStore(context: Context): DataStore<Preferences> {+ return instance ?: synchronized(this) {+ instance ?: PreferenceDataStoreFactory.create {+ context.preferencesDataStoreFile("ensu_session_prefs")+ }.also { created ->+ instance = created+ }+ }+ }}}diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/SessionPreferencesExt.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/SessionPreferencesExt.ktindex ff7340120b..d8d452a0d3 100644--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/SessionPreferencesExt.kt+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/SessionPreferencesExt.kt@@ -15,3 +15,7 @@ fun SessionPreferences.getSelectedSessionIdSync(): String? = runBlocking {fun SessionPreferences.getSessionSummariesSync(): Map<String, String> = runBlocking {sessionSummaries.first()}++fun SessionPreferences.getModelDownloadRequestedSync(): Boolean = runBlocking {+ modelDownloadRequested.first()+}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 8d6ab49971..7043ce4b43 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@@ -1,11 +1,14 @@package io.ente.ensu.data.llm+import android.app.DownloadManager+import android.content.Context+import android.net.Uri+import android.os.Environmentimport io.ente.ensu.domain.llm.DownloadProgressimport io.ente.ensu.domain.llm.GenerationSummaryimport io.ente.ensu.domain.llm.LlmMessageimport io.ente.ensu.domain.llm.LlmModelTargetimport io.ente.ensu.domain.llm.LlmProvider-import io.ente.ensu.domain.util.formatBytesimport io.ente.labs.inference_rs.ContextHandleimport io.ente.labs.inference_rs.ContextParamsimport io.ente.labs.inference_rs.GenerateChatRequest@@ -22,19 +25,20 @@ import io.ente.labs.inference_rs.cancelimport io.ente.labs.inference_rs.uniffiEnsureInitializedimport io.ente.labs.inference_rs.InferenceExceptionimport kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delayimport kotlinx.coroutines.withContext+import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Jsonimport okhttp3.OkHttpClient-import okhttp3.Request-import okhttp3.Callimport java.io.File-import java.io.FileOutputStreamimport java.io.IOException-import java.security.MessageDigest-import java.util.concurrent.atomic.AtomicBooleanimport kotlin.math.maxclass InferenceRsProvider(+ context: Context,private val modelDir: File,+ private val legacyModelDir: File? = null,private val ioDispatcher: kotlinx.coroutines.CoroutineDispatcher = Dispatchers.IO) : LlmProvider {private data class LoadedModelKey(@@ -42,9 +46,31 @@ class InferenceRsProvider(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 downloadCancelled = AtomicBoolean(false)- @Volatile private var downloadCall: Call? = null+ private val appContext = context.applicationContext+ private val externalDownloadsRoot =+ appContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+ private val downloadManager =+ appContext.getSystemService(DownloadManager::class.java)+ ?: error("DownloadManager unavailable")+ private val downloadPrefs =+ appContext.getSharedPreferences("ensu.system.downloads", Context.MODE_PRIVATE)+ private val json = Json { ignoreUnknownKeys = true }@Volatile private var modelHandle: ModelHandle? = null@Volatile private var contextHandle: ContextHandle? = null@@ -55,6 +81,7 @@ class InferenceRsProvider(init {uniffiEnsureInitialized()+ modelDir.mkdirs()}override suspend fun ensureModelReady(@@ -74,68 +101,10 @@ class InferenceRsProvider(unloadModel()- val modelFile = modelPathFor(target)- val mmprojFile = mmprojPathFor(target)- val mmprojUrl = target.mmprojUrl-- val expectedTargets = mutableListOf<DownloadTarget>()- expectedTargets.add(DownloadTarget("Model", target.url, modelFile))- if (mmprojFile != null && !mmprojUrl.isNullOrBlank()) {- expectedTargets.add(DownloadTarget("Mmproj", mmprojUrl, mmprojFile))- }-- val downloads = expectedTargets.filterNot { it.destination.exists() }-- if (downloads.isNotEmpty()) {- downloadCancelled.set(false)- modelFile.parentFile?.mkdirs()- mmprojFile?.parentFile?.mkdirs()-- val lengths = expectedTargets.map { download ->- download.destination.length().takeIf { it > 0 } ?: fetchContentLength(download.url)- }- val totalBytes = lengths.filterNotNull().sum()- val hasTotal = lengths.all { it != null } && totalBytes > 0- var downloadedSoFar = expectedTargets.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(- initialPercent,- "Downloading... ${formatBytes(downloadedSoFar)} / ${formatBytes(totalBytes)}"- )- )- } else {- onProgress(DownloadProgress(0, "Starting download..."))- }-- downloads.forEach { download ->- val expectedIndex = expectedTargets.indexOfFirst { it.destination == download.destination }- val fileTotal = lengths.getOrNull(expectedIndex)- val existingBytesForFile = existingDownloadBytes(download.destination)- // downloadedSoFar already includes any resumed bytes for this file.- val bytesBeforeFile = downloadedSoFar - existingBytesForFile- downloadFile(download.url, download.destination) { downloaded, total ->- val overallDownloaded = bytesBeforeFile + downloaded- val percent = if (hasTotal) {- ((overallDownloaded * 100) / totalBytes).toInt()- } else {- val step = 100f / expectedTargets.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.coerceIn(0, 99), status))- }- downloadedSoFar = bytesBeforeFile + (fileTotal ?: existingDownloadBytes(download.destination))- }+ migrateLegacyDownloads(target)+ val modelFile = ModelDownloadSupport.modelPathFor(modelDir, target)+ if (!ModelDownloadSupport.isTargetDownloaded(modelDir, target)) {+ awaitBackgroundDownload(target, onProgress)}onProgress(DownloadProgress(100, "Loading model..."))@@ -154,7 +123,11 @@ class InferenceRsProvider(): GenerationSummary = withContext(ioDispatcher) {val context = contextHandle ?: throw IllegalStateException("Model context not loaded")currentJobId = null- val mmprojPath = if (imageFiles.isEmpty()) null else mmprojPathFor(target)?.absolutePath+ val mmprojPath = if (imageFiles.isEmpty()) {+ null+ } else {+ ModelDownloadSupport.mmprojPathFor(modelDir, target)?.absolutePath+ }val clampedTemperature = temperature.coerceIn(0.35f, 0.7f)val request = GenerateChatRequest(@@ -183,27 +156,24 @@ class InferenceRsProvider(}override fun isModelDownloaded(target: LlmModelTarget): Boolean {- val modelFile = modelPathFor(target)- if (!modelFile.exists()) return false- val mmprojFile = mmprojPathFor(target)- if (mmprojFile != null && !mmprojFile.exists()) return false- return true+ migrateLegacyDownloads(target)+ return isDownloadComplete(target)}override suspend fun estimateModelDownloadSize(target: LlmModelTarget): Long? = withContext(ioDispatcher) {- val modelFile = modelPathFor(target)- val mmprojFile = mmprojPathFor(target)+ val modelFile = ModelDownloadSupport.modelPathFor(modelDir, target)+ val mmprojFile = ModelDownloadSupport.mmprojPathFor(modelDir, target)val mmprojUrl = target.mmprojUrlval modelSize = if (modelFile.exists()) {modelFile.length().takeIf { it > 0 }} else {- fetchContentLength(target.url)+ ModelDownloadSupport.fetchContentLength(httpClient, target.url)}val mmprojSize = if (mmprojFile != null && !mmprojUrl.isNullOrBlank()) {if (mmprojFile.exists()) {mmprojFile.length().takeIf { it > 0 }} else {- fetchContentLength(mmprojUrl)+ ModelDownloadSupport.fetchContentLength(httpClient, mmprojUrl)}} else {null@@ -212,6 +182,96 @@ class InferenceRsProvider(if (sizes.isEmpty()) null else sizes.sum()}+ override 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)+ return@withContext DownloadProgress(-1, "${download.label} download is invalid")+ }+ }++ DownloadManager.STATUS_FAILED -> {+ clearDownloadRecords(target)+ return@withContext DownloadProgress(-1, userFacingDownloadFailure(row.reason))+ }+ }+ }++ 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.domain.util.formatBytes(downloadedBytes)} / ${io.ente.ensu.domain.util.formatBytes(totalBytes)}"+ } else {+ "Downloading model..."+ }+ DownloadProgress(percent = percent, status = status)+ }+override fun loadedContextLength(target: LlmModelTarget): Int? {val modelKey = LoadedModelKey(target.id, target.contextLength)return if (currentModelKey == modelKey && contextHandle != null && modelHandle != null) {@@ -242,8 +302,11 @@ class InferenceRsProvider(}override fun cancelDownload() {- downloadCancelled.set(true)- downloadCall?.cancel()+ val ids = loadAllDownloadRecords().map { it.downloadId }.distinct()+ if (ids.isNotEmpty()) {+ downloadManager.remove(*ids.toLongArray())+ }+ clearAllDownloadRecords()}private fun LlmMessage.roleString(): String {@@ -299,158 +362,216 @@ class InferenceRsProvider(throw lastError ?: IllegalStateException("Failed to load model")}- private fun downloadFile(- url: String,- dest: File,- onProgress: (Long, Long?) -> Unit+ private suspend fun awaitBackgroundDownload(+ target: LlmModelTarget,+ onProgress: (DownloadProgress) -> 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- }-+ ensureDownloadsEnqueued(target)+ var emptyPollCount = 0while (true) {- val requestBuilder = Request.Builder().url(url)- if (existing > 0) {- requestBuilder.header("Range", "bytes=$existing-")+ val progress = currentDownloadProgress(target)+ if (progress == null) {+ if (isDownloadComplete(target)) {+ clearDownloadRecords(target)+ return+ }+ emptyPollCount += 1+ if (emptyPollCount >= 3) {+ ensureDownloadsEnqueued(target)+ }+ } else {+ emptyPollCount = 0+ if (progress.percent < 0) {+ throw IOException(progress.status)+ }+ onProgress(progress)}- val call = httpClient.newCall(requestBuilder.build())- downloadCall = call+ delay(500)+ }+ }- val response = call.execute()- if (!response.isSuccessful) {- response.close()- throw IOException("Download failed: HTTP ${response.code}")- }+ private fun ensureDownloadsEnqueued(target: LlmModelTarget) {+ 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>()- if (existing > 0 && response.code == 200) {- response.close()- tmp.delete()- existing = 0L- continue+ expectedTargets.forEach { download ->+ if (download.destination.exists() && ModelDownloadSupport.looksLikeGguf(download.destination)) {+ return@forEach}- 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 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}- 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 (downloadCancelled.get()) {- 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)- }- }+ if (download.destination.exists() && !ModelDownloadSupport.looksLikeGguf(download.destination)) {+ download.destination.delete()}- response.close()- if (totalBytes != null && downloaded < totalBytes) {- tmp.delete()- throw IOException("Download incomplete")- }+ 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 = downloadManager.enqueue(request)+ updatedRecords += DownloadRecord(+ downloadId = id,+ label = download.label,+ url = download.url,+ destinationPath = download.destination.absolutePath+ )+ }++ saveDownloadRecords(target, updatedRecords)+ }- if (!looksLikeGguf(tmp)) {- tmp.delete()- throw IOException("Downloaded file is not GGUF")+ private fun queryDownloadRows(ids: Collection<Long>): Map<Long, DownloadRow> {+ if (ids.isEmpty()) return emptyMap()+ val query = DownloadManager.Query().setFilterById(*ids.toLongArray())+ val rows = mutableMapOf<Long, DownloadRow>()+ downloadManager.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)+ )}- if (dest.exists()) dest.delete()- tmp.renameTo(dest)- return}+ return rows}- 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 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 fetchContentLength(url: String): Long? {- val request = Request.Builder().url(url).head().build()- return try {- httpClient.newCall(request).execute().use { response ->- if (!response.isSuccessful) return null- response.body?.contentLength()?.takeIf { it > 0 }- ?: response.header("Content-Length")?.toLongOrNull()- }- } catch (_: IOException) {- null+ 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 data class DownloadTarget(- val label: String,- val url: String,- val destination: File- )+ private fun clearDownloadRecords(target: LlmModelTarget) {+ downloadPrefs.edit().remove(downloadPrefsKey(target)).apply()+ }- private fun modelPathFor(target: LlmModelTarget): File {- return pathForUrl(target, target.url, fallback = "model.gguf")+ 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 mmprojPathFor(target: LlmModelTarget): File? {- val url = target.mmprojUrl ?: return null- return pathForUrl(target, url, fallback = "mmproj.gguf")+ private fun clearAllDownloadRecords() {+ val editor = downloadPrefs.edit()+ downloadPrefs.all.keys+ .filter { it.startsWith(DOWNLOAD_PREF_PREFIX) }+ .forEach(editor::remove)+ editor.apply()}- private 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+ 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 pathForUrl(target: LlmModelTarget, url: String, fallback: String): File {- val baseDir = File(modelDir, "models")- val filename = filenameForUrl(url, fallback)- return if (target.id.startsWith("custom:")) {- val customDir = File(baseDir, "custom")- File(customDir, "${hash(url)}_$filename")- } else {- File(baseDir, filename)+ 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 filenameForUrl(url: String, fallback: String): String {- val withoutQuery = url.substringBefore('?').substringBefore('#')- return withoutQuery.substringAfterLast('/').ifBlank { fallback }+ private fun migrateLegacyDownloads(target: LlmModelTarget) {+ val legacyDir = legacyModelDir ?: return+ if (legacyDir.absolutePath == modelDir.absolutePath) return++ val oldTargets = ModelDownloadSupport.expectedTargets(legacyDir, target)+ val newTargets = ModelDownloadSupport.expectedTargets(modelDir, target)+ oldTargets.zip(newTargets).forEach { (oldTarget, newTarget) ->+ if (!ModelDownloadSupport.looksLikeGguf(oldTarget.destination)) {+ return@forEach+ }+ if (newTarget.destination.exists()) {+ return@forEach+ }++ newTarget.destination.parentFile?.mkdirs()+ val moved = oldTarget.destination.renameTo(newTarget.destination)+ if (!moved) {+ runCatching {+ oldTarget.destination.copyTo(newTarget.destination, overwrite = false)+ oldTarget.destination.delete()+ }+ }+ }}- private fun looksLikeGguf(file: File): Boolean {- if (!file.exists() || file.length() < 4) return false- val header = ByteArray(4)- file.inputStream().use { input ->- if (input.read(header) != 4) return false+ 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."}- return header.contentEquals("GGUF".toByteArray())}- private fun hash(value: String): String {- val digest = MessageDigest.getInstance("SHA-256").digest(value.toByteArray())- return digest.joinToString("") { "%02x".format(it) }+ companion object {+ private const val DOWNLOAD_PREF_PREFIX = "target."}private fun generateStreamWithCallback(diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/ModelDownloadSupport.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/ModelDownloadSupport.ktnew file mode 100644index 0000000000..da2691f20a--- /dev/null+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/ModelDownloadSupport.kt@@ -0,0 +1,247 @@+package io.ente.ensu.data.llm++import io.ente.ensu.domain.llm.DownloadProgress+import io.ente.ensu.domain.llm.LlmModelTarget+import io.ente.ensu.domain.util.formatBytes+import okhttp3.OkHttpClient+import okhttp3.Request+import java.io.File+import java.io.FileOutputStream+import java.io.IOException+import java.security.MessageDigest++internal object ModelDownloadSupport {+ data class DownloadTarget(+ val label: String,+ val url: String,+ val destination: File+ )++ fun expectedTargets(modelDir: File, target: LlmModelTarget): List<DownloadTarget> {+ val targets = mutableListOf(+ DownloadTarget("Model", target.url, modelPathFor(modelDir, target))+ )+ val mmprojUrl = target.mmprojUrl+ val mmprojPath = mmprojPathFor(modelDir, target)+ if (!mmprojUrl.isNullOrBlank() && mmprojPath != null) {+ targets += DownloadTarget("Mmproj", mmprojUrl, mmprojPath)+ }+ return targets+ }++ fun isTargetDownloaded(modelDir: File, target: LlmModelTarget): Boolean {+ return expectedTargets(modelDir, target).all {+ it.destination.exists() && looksLikeGguf(it.destination)+ }+ }++ fun modelPathFor(modelDir: File, target: LlmModelTarget): File {+ return pathForUrl(modelDir, target, target.url, fallback = "model.gguf")+ }++ fun mmprojPathFor(modelDir: File, target: LlmModelTarget): File? {+ val url = target.mmprojUrl ?: return null+ 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 {+ httpClient.newCall(request).execute().use { response ->+ if (!response.isSuccessful) return null+ response.body?.contentLength()?.takeIf { it > 0 }+ ?: response.header("Content-Length")?.toLongOrNull()+ }+ } catch (_: IOException) {+ null+ }+ }++ 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 false+ val header = ByteArray(4)+ file.inputStream().use { input ->+ if (input.read(header) != 4) return false+ }+ 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()+ tmp.renameTo(dest)+ 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)+ return if (target.id.startsWith("custom:")) {+ val customDir = File(baseDir, "custom")+ File(customDir, "${hash(url)}_$filename")+ } else {+ File(baseDir, filename)+ }+ }++ private fun filenameForUrl(url: String, fallback: String): String {+ val withoutQuery = url.substringBefore('?').substringBefore('#')+ return withoutQuery.substringAfterLast('/').ifBlank { fallback }+ }++ private fun hash(value: String): String {+ val digest = MessageDigest.getInstance("SHA-256").digest(value.toByteArray())+ return digest.joinToString("") { "%02x".format(it) }+ }+}diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/llm/LlmProvider.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/llm/LlmProvider.ktindex 04010d3022..5d3d6a887e 100644--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/llm/LlmProvider.kt+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/llm/LlmProvider.kt@@ -51,6 +51,7 @@ interface LlmProvider {fun isModelDownloaded(target: LlmModelTarget): Booleansuspend fun estimateModelDownloadSize(target: LlmModelTarget): Long?+ suspend fun currentDownloadProgress(target: LlmModelTarget): DownloadProgress?fun loadedContextLength(target: LlmModelTarget): Int?fun stopGeneration()diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/preferences/SessionPreferences.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/preferences/SessionPreferences.ktindex 1c8a6c3e57..e7f96febfb 100644--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/preferences/SessionPreferences.kt+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/preferences/SessionPreferences.kt@@ -5,6 +5,8 @@ import kotlinx.coroutines.flow.Flowinterface SessionPreferences {val selectedSessionId: Flow<String?>val sessionSummaries: Flow<Map<String, String>>+ val modelDownloadRequested: Flow<Boolean>suspend fun setSelectedSessionId(sessionId: String?)suspend fun setSessionSummary(sessionId: String, summary: String?)+ suspend fun setModelDownloadRequested(requested: Boolean)}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.ktindex 5116e36829..6cdb96f261 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@@ -29,7 +29,7 @@ class AppStore(private val messageStore = mutableMapOf<String, MutableList<ChatMessage>>()private val attachmentActions = AttachmentStoreActions(_state, chatSyncRepository, messageStore)- private val modelSettingsActions = ModelSettingsActions(_state, llmProvider, logRepository)+ private val modelSettingsActions = ModelSettingsActions(_state, sessionPreferences, llmProvider, logRepository)private val syncActions = SyncStoreActions(_state, chatSyncRepository, logRepository)private val chatActions = ChatStoreActions(state = _state,@@ -60,6 +60,17 @@ class AppStore(modelSettingsActions.refreshModelDownloadInfo()}+ fun hydrateModelDownloadRequested(requested: Boolean) {+ if (!requested) return+ _state.value = _state.value.copy(+ chat = _state.value.chat.copy(+ hasRequestedModelDownload = true,+ isDownloading = true,+ downloadStatus = "Resuming download..."+ )+ )+ }+fun createNewSession(): String = chatActions.createNewSession()fun startNewSessionDraft() = chatActions.startNewSessionDraft()@@ -92,6 +103,8 @@ class AppStore(fun startModelDownload(userInitiated: Boolean = true) =modelSettingsActions.startModelDownload(userInitiated)+ fun refreshModelDownloadInfo() = modelSettingsActions.refreshModelDownloadInfo()+fun cancelDownload() {chatActions.cancelGenerationForDownload()modelSettingsActions.cancelModelDownload()diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ModelSettingsActions.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ModelSettingsActions.ktindex 3956c13c1a..1b5ee3a355 100644--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ModelSettingsActions.kt+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ModelSettingsActions.kt@@ -4,6 +4,7 @@ import io.ente.ensu.domain.llm.LlmModelTargetimport io.ente.ensu.domain.llm.LlmProviderimport io.ente.ensu.domain.logging.LogRepositoryimport io.ente.ensu.domain.model.LogLevel+import io.ente.ensu.domain.preferences.SessionPreferencesimport io.ente.ensu.domain.state.AppStateimport io.ente.ensu.domain.state.ModelSettingsStateimport kotlinx.coroutines.CoroutineScope@@ -12,14 +13,17 @@ import kotlinx.coroutines.Jobimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.updateimport kotlinx.coroutines.launch+import kotlinx.coroutines.isActiveinternal class ModelSettingsActions(private val state: MutableStateFlow<AppState>,+ private val sessionPreferences: SessionPreferences,private val llmProvider: LlmProvider,private val logRepository: LogRepository) {private var scope: CoroutineScope? = nullprivate var modelDownloadJob: Job? = null+ private var downloadProgressMonitorJob: Job? = nullfun setScope(scope: CoroutineScope) {this.scope = scope@@ -42,28 +46,66 @@ internal class ModelSettingsActions(fun refreshModelDownloadInfo() {val target = resolveTarget(state.value.modelSettings)val isDownloaded = llmProvider.isModelDownloaded(target)+ if (isDownloaded) {+ downloadProgressMonitorJob?.cancel()+ persistModelDownloadRequested(false)+ }state.update { appState ->appState.copy(chat = appState.chat.copy(isModelDownloaded = isDownloaded,+ isDownloading = if (isDownloaded) false else appState.chat.isDownloading,+ downloadPercent = if (isDownloaded) null else appState.chat.downloadPercent,+ downloadStatus = if (isDownloaded) null else appState.chat.downloadStatus,modelDownloadSizeBytes = if (isDownloaded) null else appState.chat.modelDownloadSizeBytes,hasRequestedModelDownload = appState.chat.hasRequestedModelDownload || isDownloaded))}- if (!isDownloaded) {- val scope = scope ?: return- scope.launch {- val size = llmProvider.estimateModelDownloadSize(target)+ if (isDownloaded) return++ val scope = scope ?: return+ scope.launch {+ val progress = llmProvider.currentDownloadProgress(target)+ if (progress != null) {+ val isFailure = progress.percent < 0+ persistModelDownloadRequested(!isFailure)state.update { appState ->appState.copy(chat = appState.chat.copy(- modelDownloadSizeBytes = size ?: appState.chat.modelDownloadSizeBytes+ isDownloading = !isFailure,+ downloadPercent = progress.percent.takeIf { it >= 0 },+ downloadStatus = progress.status,+ hasRequestedModelDownload = if (isFailure) false else true+ )+ )+ }+ if (!isFailure) {+ startDownloadProgressMonitor(target)+ }+ } else {+ persistModelDownloadRequested(false)+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isDownloading = false,+ downloadPercent = null,+ downloadStatus = null,+ hasRequestedModelDownload = false))}}++ val size = llmProvider.estimateModelDownloadSize(target)+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ modelDownloadSizeBytes = size ?: appState.chat.modelDownloadSizeBytes+ )+ )+ }}}@@ -90,6 +132,7 @@ internal class ModelSettingsActions(modelDownloadJob?.cancel()if (!isDownloaded) {+ persistModelDownloadRequested(true)logRepository.log(LogLevel.Info,"Model download started",@@ -110,6 +153,7 @@ 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..."@@ -169,6 +213,7 @@ internal class ModelSettingsActions())}+ persistModelDownloadRequested(false)if (cancelled) {if (!isDownloaded) {logRepository.log(LogLevel.Info, "Model download cancelled", tag = "Model")@@ -192,7 +237,9 @@ internal class ModelSettingsActions(fun cancelModelDownload() {modelDownloadJob?.cancel()modelDownloadJob = null+ downloadProgressMonitorJob?.cancel()llmProvider.cancelDownload()+ persistModelDownloadRequested(false)state.update { appState ->appState.copy(chat = appState.chat.copy(@@ -206,6 +253,55 @@ internal class ModelSettingsActions(refreshModelDownloadInfo()}+ private fun startDownloadProgressMonitor(target: LlmModelTarget) {+ val scope = scope ?: return+ downloadProgressMonitorJob?.cancel()+ downloadProgressMonitorJob = scope.launch {+ while (isActive) {+ val progress = llmProvider.currentDownloadProgress(target)+ if (progress == null) {+ break+ }+ val isFailure = progress.percent < 0+ if (isFailure) {+ persistModelDownloadRequested(false)+ }+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isDownloading = !isFailure,+ downloadPercent = progress.percent.takeIf { it >= 0 },+ downloadStatus = progress.status,+ hasRequestedModelDownload = if (isFailure) false else appState.chat.hasRequestedModelDownload+ )+ )+ }+ if (isFailure) {+ break+ }+ delay(500)+ }+ downloadProgressMonitorJob = null+ refreshModelDownloadInfo()+ }+ }++ private fun persistModelDownloadRequested(requested: Boolean) {+ scope?.launch {+ runCatching {+ sessionPreferences.setModelDownloadRequested(requested)+ }.onFailure { error ->+ logRepository.log(+ LogLevel.Error,+ "Failed to persist model download state",+ details = error.message,+ tag = "Model",+ throwable = error+ )+ }+ }+ }+fun resolveTarget(settings: ModelSettingsState): LlmModelTarget {val useCustom = settings.useCustomModel && settings.modelUrl.isNotBlank()val url = if (useCustom) settings.modelUrl else DEFAULT_MODEL_URLdiff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swiftindex 14aae5f5ef..d4c9f1de9f 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift@@ -6,6 +6,7 @@ struct ChatView: View {@Binding var isShowingAuth: Bool@EnvironmentObject private var appState: EnsuAppState+ @Environment(\.scenePhase) private var scenePhase@ObservedObject private var modelSettings = ModelSettingsStore.shared@StateObject private var viewState = ChatViewState()@@ -140,6 +141,11 @@ struct ChatView: View {.onChange(of: modelSettingsSignature) { _ inviewModel.refreshModelDownloadInfo()}+ .onChange(of: scenePhase) { newValue in+ if newValue == .active {+ viewModel.refreshModelDownloadInfo()+ }+ }}.sheet(isPresented: $viewState.showSettings) {SettingsView(diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swiftindex 1359b13fbf..ab0938e7df 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift@@ -488,6 +488,7 @@ final class ChatViewModel: ObservableObject {private let rootId = UUID(uuidString: "00000000-0000-0000-0000-000000000000")!private var generationTask: Task<Void, Never>?private var modelDownloadTask: Task<Void, Never>?+ private var downloadProgressMonitorTask: Task<Void, Never>?private var sharedModelReadyTask: Task<Void, Error>?private var sharedModelReadyTaskId: UUID?private var sharedModelReadyKey: ModelReadyKey?@@ -1193,6 +1194,8 @@ final class ChatViewModel: ObservableObject {let target = modelSettings.currentTarget()isModelDownloaded = provider.isModelDownloaded(target: target)if isModelDownloaded {+ downloadProgressMonitorTask?.cancel()+ downloadProgressMonitorTask = nilclearDownloadProgressMemory()modelDownloadSizeBytes = nilreturn@@ -1200,8 +1203,20 @@ final class ChatViewModel: ObservableObject {Task { [weak self] inguard let self else { return }+ let progress = await provider.currentDownloadProgress(target: target)let size = await provider.estimatedDownloadSize(target: target)await MainActor.run {+ guard self.modelReadyKey(for: self.modelSettings.currentTarget()) == self.modelReadyKey(for: target) else {+ return+ }+ if let progress {+ self.handleProgress(progress)+ self.startDownloadProgressMonitor(target: target)+ } else if self.downloadToast?.phase == .downloading || self.downloadToast?.phase == .loading {+ self.downloadToast = nil+ self.isDownloading = false+ self.clearDownloadProgressMemory()+ }self.modelDownloadSizeBytes = size ?? self.modelDownloadSizeBytes}}@@ -1292,6 +1307,7 @@ final class ChatViewModel: ObservableObject {logger.info("Model download started", details: "model=\(target.id)")modelDownloadTask?.cancel()+ startDownloadProgressMonitor(target: target)modelDownloadTask = Task {do {try await self.ensureModelReadyShared(target: target)@@ -1355,6 +1371,8 @@ final class ChatViewModel: ObservableObject {resetGenerationState(stopRequested: true)modelDownloadTask?.cancel()modelDownloadTask = nil+ downloadProgressMonitorTask?.cancel()+ downloadProgressMonitorTask = nilsharedModelReadyTask?.cancel()clearSharedModelReadyTask()provider.cancelDownload()@@ -1741,6 +1759,44 @@ final class ChatViewModel: ObservableObject {isDownloading = visiblePercent >= 0 && visiblePercent < 100}+ private func startDownloadProgressMonitor(target: InferenceModelTarget) {+ downloadProgressMonitorTask?.cancel()+ let targetKey = modelReadyKey(for: target)++ downloadProgressMonitorTask = Task { [weak self] in+ guard let self else { return }+ var emptyPollCount = 0++ while !Task.isCancelled {+ guard self.modelReadyKey(for: self.modelSettings.currentTarget()) == targetKey else {+ return+ }++ let progress = await self.provider.currentDownloadProgress(target: target)+ let isDownloaded = self.provider.isModelDownloaded(target: target)++ if let progress {+ emptyPollCount = 0+ self.handleProgress(progress)+ } else {+ emptyPollCount += 1+ }++ if isDownloaded {+ self.refreshModelDownloadInfo()+ return+ }++ if emptyPollCount >= 6 {+ self.refreshModelDownloadInfo()+ return+ }++ try? await Task.sleep(nanoseconds: 500_000_000)+ }+ }+ }+private func buildSyncAuth() -> SyncAuth? {guard CredentialStore.shared.hasConfiguredAccount,let token = CredentialStore.shared.token,diff --git a/mobile/native/darwin/Apps/ensu/ensu/EnsuApp.swift b/mobile/native/darwin/Apps/ensu/ensu/EnsuApp.swiftindex 6ad9c91054..7870166786 100644--- a/mobile/native/darwin/Apps/ensu/ensu/EnsuApp.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/EnsuApp.swift@@ -4,6 +4,9 @@ import SwiftUIstruct EnsuApp: App {@StateObject private var appState = EnsuAppState()@StateObject private var deepLinkRouter = DeepLinkRouter()+ #if os(iOS)+ @UIApplicationDelegateAdaptor(EnsuAppDelegate.self) private var appDelegate+ #endifinit() {EnsuLogging.shared.start()diff --git a/mobile/native/darwin/Apps/ensu/ensu/EnsuAppDelegate.swift b/mobile/native/darwin/Apps/ensu/ensu/EnsuAppDelegate.swiftnew file mode 100644index 0000000000..80dd3941dc--- /dev/null+++ b/mobile/native/darwin/Apps/ensu/ensu/EnsuAppDelegate.swift@@ -0,0 +1,13 @@+#if os(iOS)+import UIKit++final class EnsuAppDelegate: NSObject, UIApplicationDelegate {+ func application(+ _ application: UIApplication,+ handleEventsForBackgroundURLSession identifier: String,+ completionHandler: @escaping () -> Void+ ) {+ ModelDownloadManager.shared.setBackgroundCompletionHandler(completionHandler)+ }+}+#endifdiff --git a/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swift b/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swiftindex 0f06d71b5a..939a4c1beb 100644--- a/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swift@@ -41,10 +41,10 @@ struct ModelSettingsView: View {mmproj: "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/mmproj-LFM2.5-VL-1.6b-Q8_0.gguf"),ModelChoice(- id: "qwen-2b",- name: "Qwen 3.5 2B (Q8_0)",- url: "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/Qwen3.5-2B-Q8_0.gguf?download=true",- mmproj: "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/mmproj-F16.gguf"+ id: "qwen-0.8b",+ name: "Qwen 3.5 0.8B (Q4_K_M)",+ url: "https://huggingface.co/unsloth/Qwen3.5-0.8B-GGUF/resolve/main/Qwen3.5-0.8B-Q4_K_M.gguf?download=true",+ mmproj: "https://huggingface.co/unsloth/Qwen3.5-0.8B-GGUF/resolve/main/mmproj-F16.gguf"),ModelChoice(id: Self.customOptionId,diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swiftindex 76d3ae1eef..54025ad11a 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift@@ -52,14 +52,19 @@ final class InferenceRsProvider {let requestedContextLength: Int?}+ private struct DownloadTarget {+ let label: String+ let url: String+ let destination: URL+ }+private let modelDir: URL+ private let downloadManager = ModelDownloadManager.sharedprivate var modelHandle: ModelHandle?private var contextHandle: ContextHandle?private var currentModelKey: LoadedModelKey?private var currentContextLength: Int?private var backendInitialized = false- private var downloadCancelled = false- private var currentDownloadTask: URLSessionTask?private var currentJobId: Int64?init(modelDir: URL) {@@ -103,7 +108,7 @@ final class InferenceRsProvider {}expectedTargets.append(DownloadTarget(label: "Model", url: target.url, destination: modelPath))- if let mmprojUrl = target.mmprojUrl, let mmprojPath {+ if let mmprojUrl = target.mmprojUrl, !mmprojUrl.isEmpty, let mmprojPath {let mmprojExistsAtStart = FileManager.default.fileExists(atPath: mmprojPath.path)if shouldRedownloadExistingFile(at: mmprojPath) || !mmprojExistsAtStart {if mmprojExistsAtStart {@@ -116,64 +121,9 @@ final class InferenceRsProvider {let downloads = expectedTargets.filter { !FileManager.default.fileExists(atPath: $0.destination.path) }if !downloads.isEmpty {- downloadCancelled = false- var lengths: [Int64?] = []- for download in expectedTargets {- if FileManager.default.fileExists(atPath: download.destination.path) {- lengths.append(fileSize(download.destination))- } else {- lengths.append(await fetchContentLength(for: download.url))- }- }-- let totalBytes = lengths.compactMap { $0 }.reduce(0, +)- let hasTotal = lengths.allSatisfy { $0 != nil } && totalBytes > 0- var downloadedSoFar: Int64 = zip(expectedTargets, lengths).reduce(0) { partial, pair in- let existing = existingDownloadBytes(at: pair.0.destination)- let capped = min(existing, pair.1 ?? existing)- return partial + capped- }-- if hasTotal, downloadedSoFar > 0 {- let initialPercent = min(99, max(0, Int((Double(downloadedSoFar) / Double(totalBytes)) * 100.0)))- onProgress(- InferenceDownloadProgress(- percent: initialPercent,- status: "Downloading... \(downloadedSoFar.formattedFileSize) / \(totalBytes.formattedFileSize)"- )- )- } else {- onProgress(InferenceDownloadProgress(percent: 0, status: "Starting download..."))- }-- for download in downloads {- let expectedIndex = expectedTargets.firstIndex(where: { $0.destination == download.destination }) ?? 0- let fileTotal = lengths[expectedIndex]- let existingBytesForFile = existingDownloadBytes(at: download.destination)- // downloadedSoFar already includes any resumed bytes for this file.- let bytesBeforeFile = downloadedSoFar - existingBytesForFile- try await downloadFile(from: download.url, to: download.destination) { [self] downloaded, total in- let overallDownloaded = bytesBeforeFile + downloaded- let percent: Int- if hasTotal {- percent = Int((Double(overallDownloaded) / Double(totalBytes)) * 100.0)- } else {- let step = 100.0 / Double(expectedTargets.count)- let filePercent = total.map { Double(downloaded) / Double($0) } ?? 0- percent = Int((Double(expectedIndex) * step) + (filePercent * step))- }-- let status = if hasTotal {- "Downloading... \(overallDownloaded.formattedFileSize) / \(totalBytes.formattedFileSize)"- } else {- "Downloading \(download.label.lowercased())... \(downloaded.formattedFileSize)"- }-- onProgress(InferenceDownloadProgress(percent: min(99, max(0, percent)), status: status))- }- let finishedBytes = fileTotal ?? existingDownloadBytes(at: download.destination)- downloadedSoFar = bytesBeforeFile + finishedBytes- }+ onProgress(InferenceDownloadProgress(percent: 0, status: "Starting download..."))+ await downloadManager.enqueueDownloads(downloads.map(downloadTarget(for:)))+ try await waitForDownloads(expectedTargets, onProgress: onProgress)}onProgress(InferenceDownloadProgress(percent: 100, status: "Loading model..."))@@ -289,8 +239,9 @@ final class InferenceRsProvider {}func cancelDownload() {- downloadCancelled = true- currentDownloadTask?.cancel()+ Task {+ await downloadManager.cancelAllDownloads()+ }}func isModelDownloaded(target: InferenceModelTarget) -> Bool {@@ -335,6 +286,10 @@ final class InferenceRsProvider {return sizes.reduce(0, +)}+ func currentDownloadProgress(target: InferenceModelTarget) async -> InferenceDownloadProgress? {+ await downloadManager.progress(for: expectedTargets(for: target).map(downloadTarget(for:)))+ }+func loadedContextLength(target: InferenceModelTarget) -> Int? {let modelKey = LoadedModelKey(id: target.id, requestedContextLength: target.contextLength)guard currentModelKey == modelKey, modelHandle != nil, contextHandle != nil else {@@ -373,156 +328,6 @@ final class InferenceRsProvider {throw NSError(domain: "InferenceRsProvider", code: -5, userInfo: [NSLocalizedDescriptionKey: "Failed to create context"])}- private func downloadFile(- from urlString: String,- to destination: URL,- onProgress: @escaping (Int64, Int64?) -> Void- ) async throws {- guard let url = URL(string: urlString) else {- throw NSError(domain: "InferenceRsProvider", code: -7, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])- }-- let tmp = destination.appendingPathExtension("tmp")- var existing = fileSize(tmp)- if existing > 0, !looksLikeGguf(file: tmp) {- try? FileManager.default.removeItem(at: tmp)- existing = 0- }-- var shouldResume = existing > 0-- while true {- var request = URLRequest(url: url)- request.httpMethod = "GET"- if shouldResume {- request.setValue("bytes=\(existing)-", forHTTPHeaderField: "Range")- }-- let (bytes, response) = try await URLSession.shared.bytes(for: request)- currentDownloadTask = bytes.task-- let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 0- if shouldResume, statusCode == 200 {- try? FileManager.default.removeItem(at: tmp)- existing = 0- shouldResume = false- continue- }-- if !(200...299).contains(statusCode) {- throw NSError(- domain: "InferenceRsProvider",- code: -9,- userInfo: [NSLocalizedDescriptionKey: "Download failed (HTTP \(statusCode))"]- )- }-- var totalBytes: Int64?- if shouldResume, statusCode == 206,- let contentRange = (response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Content-Range") {- totalBytes = parseTotalBytes(from: contentRange)- }-- if totalBytes == nil {- let expected = response.expectedContentLength- if expected > 0 {- totalBytes = shouldResume && statusCode == 206 ? expected + existing : expected- }- }-- if let totalBytes, totalBytes <= existing {- try? FileManager.default.removeItem(at: tmp)- existing = 0- shouldResume = false- continue- }-- try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil)-- let handle: FileHandle- if shouldResume, statusCode == 206, FileManager.default.fileExists(atPath: tmp.path) {- handle = try FileHandle(forWritingTo: tmp)- try handle.seekToEnd()- } else {- if FileManager.default.fileExists(atPath: tmp.path) {- try FileManager.default.removeItem(at: tmp)- }- FileManager.default.createFile(atPath: tmp.path, contents: nil)- handle = try FileHandle(forWritingTo: tmp)- }-- var buffer = [UInt8]()- buffer.reserveCapacity(64 * 1024)- var downloaded: Int64 = existing- var lastProgressUpdate: Int64 = existing- let updateThreshold: Int64 = 512 * 1024-- defer {- currentDownloadTask = nil- }-- for try await byte in bytes {- if downloadCancelled {- try? handle.close()- try? FileManager.default.removeItem(at: tmp)- throw CancellationError()- }-- buffer.append(byte)- downloaded += 1-- if buffer.count >= 64 * 1024 {- handle.write(Data(buffer))- buffer.removeAll(keepingCapacity: true)- }-- if downloaded - lastProgressUpdate >= updateThreshold {- lastProgressUpdate = downloaded- onProgress(downloaded, totalBytes)- }- }-- if !buffer.isEmpty {- handle.write(Data(buffer))- }- try handle.close()- onProgress(downloaded, totalBytes)-- if let totalBytes, downloaded < totalBytes {- try? FileManager.default.removeItem(at: tmp)- throw NSError(domain: "InferenceRsProvider", code: -10, userInfo: [NSLocalizedDescriptionKey: "Download incomplete"])- }-- if !looksLikeGguf(file: tmp) {- try? FileManager.default.removeItem(at: tmp)- throw NSError(domain: "InferenceRsProvider", code: -6, userInfo: [NSLocalizedDescriptionKey: "Downloaded file is not GGUF"])- }-- if FileManager.default.fileExists(atPath: destination.path) {- try FileManager.default.removeItem(at: destination)- }- try FileManager.default.moveItem(at: tmp, to: destination)- return- }- }-- private func parseTotalBytes(from contentRange: String) -> Int64? {- let parts = contentRange.split(separator: "/")- guard parts.count == 2 else { return nil }- return Int64(parts[1])- }-- private func existingDownloadBytes(at destination: URL) -> Int64 {- if FileManager.default.fileExists(atPath: destination.path) {- return fileSize(destination)- }- let tmp = destination.appendingPathExtension("tmp")- if FileManager.default.fileExists(atPath: tmp.path) {- return fileSize(tmp)- }- return 0- }-private func fetchContentLength(for urlString: String) async -> Int64? {guard let url = URL(string: urlString) else { return nil }var request = URLRequest(url: url)@@ -574,12 +379,6 @@ final class InferenceRsProvider {return removedAny}- private struct DownloadTarget {- let label: String- let url: String- let destination: URL- }-private func looksLikeGguf(file: URL) -> Bool {guard let handle = try? FileHandle(forReadingFrom: file) else { return false }let data = handle.readData(ofLength: 4)@@ -615,6 +414,49 @@ final class InferenceRsProvider {let hashed = SHA256.hash(data: data)return hashed.map { String(format: "%02x", $0) }.joined()}++ private func expectedTargets(for target: InferenceModelTarget) -> [DownloadTarget] {+ let modelPath = modelPathFor(target: target)+ let mmprojPath = mmprojPathFor(target: target)+ var targets = [DownloadTarget(label: "Model", url: target.url, destination: modelPath)]++ if let mmprojUrl = target.mmprojUrl, !mmprojUrl.isEmpty, let mmprojPath {+ targets.append(DownloadTarget(label: "Mmproj", url: mmprojUrl, destination: mmprojPath))+ }++ return targets+ }++ private func downloadTarget(for target: DownloadTarget) -> ModelDownloadTarget {+ ModelDownloadTarget(label: target.label, url: target.url, destination: target.destination)+ }++ private func waitForDownloads(+ _ expectedTargets: [DownloadTarget],+ onProgress: @escaping (InferenceDownloadProgress) -> Void+ ) async throws {+ let managerTargets = expectedTargets.map(downloadTarget(for:))++ while true {+ try Task.checkCancellation()+ if expectedTargets.allSatisfy({ FileManager.default.fileExists(atPath: $0.destination.path) }) {+ return+ }++ if let progress = await downloadManager.progress(for: managerTargets) {+ if progress.percent == -1 {+ throw NSError(+ domain: "InferenceRsProvider",+ code: -9,+ userInfo: [NSLocalizedDescriptionKey: progress.status]+ )+ }+ onProgress(progress)+ }++ try await Task.sleep(nanoseconds: 500_000_000)+ }+ }}private final class CallbackSink: GenerateEventCallback, @unchecked Sendable {@@ -676,6 +518,11 @@ final class InferenceRsProvider {return nil}+ func currentDownloadProgress(target: InferenceModelTarget) async -> InferenceDownloadProgress? {+ _ = target+ return nil+ }+func loadedContextLength(target: InferenceModelTarget) -> Int? {_ = targetreturn nildiff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/ModelDownloadManager.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/ModelDownloadManager.swiftnew file mode 100644index 0000000000..e6e1737b25--- /dev/null+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/ModelDownloadManager.swift@@ -0,0 +1,306 @@+import Foundation+import CryptoKit++struct ModelDownloadTarget: Equatable {+ let label: String+ let url: String+ let destination: URL+}++final class ModelDownloadManager: NSObject {+ static let shared = ModelDownloadManager()++ private struct DownloadRecord: Codable {+ enum State: String, Codable {+ case queued+ case downloading+ case failed+ }++ let id: String+ let label: String+ let url: String+ let destinationPath: String+ var state: State+ var errorMessage: String?+ }++ private let recordsKey = "ensu.model.download.records"+ private let syncQueue = DispatchQueue(label: "io.ente.ensu.model-download-manager")+ private lazy var session: URLSession = {+ let configuration: URLSessionConfiguration+ #if os(iOS)+ configuration = URLSessionConfiguration.background(withIdentifier: "io.ente.ensu.model-downloads")+ configuration.sessionSendsLaunchEvents = true+ configuration.isDiscretionary = false+ #else+ configuration = URLSessionConfiguration.default+ #endif+ configuration.waitsForConnectivity = true+ return URLSession(configuration: configuration, delegate: self, delegateQueue: nil)+ }()++ private var backgroundCompletionHandler: (() -> Void)?++ func setBackgroundCompletionHandler(_ completionHandler: @escaping () -> Void) {+ syncQueue.async {+ self.backgroundCompletionHandler = completionHandler+ }+ }++ func enqueueDownloads(_ targets: [ModelDownloadTarget]) async {+ let tasks = await allTasks()+ let activeIds = Set(tasks.compactMap(\.taskDescription))++ for target in targets where !FileManager.default.fileExists(atPath: target.destination.path) {+ let id = recordId(for: target.destination)+ if activeIds.contains(id) {+ continue+ }++ let record = DownloadRecord(+ id: id,+ label: target.label,+ url: target.url,+ destinationPath: target.destination.path,+ state: .queued,+ errorMessage: nil+ )+ saveRecord(record)++ guard let url = URL(string: target.url) else {+ markFailed(id: id, message: "Invalid URL")+ continue+ }++ let task = session.downloadTask(with: URLRequest(url: url))+ task.taskDescription = id+ task.resume()+ }+ }++ func progress(for targets: [ModelDownloadTarget]) async -> InferenceDownloadProgress? {+ if targets.allSatisfy({ FileManager.default.fileExists(atPath: $0.destination.path) }) {+ clearRecords(for: targets)+ return nil+ }++ let tasks = await allTasks()+ let ids = Set(targets.map { recordId(for: $0.destination) })+ let relevantTasks = tasks.filter { task in+ guard let taskId = task.taskDescription else { return false }+ return ids.contains(taskId)+ }++ if relevantTasks.isEmpty {+ if let failure = firstFailure(for: targets) {+ return InferenceDownloadProgress(percent: -1, status: failure)+ }+ return nil+ }++ var downloaded: Int64 = 0+ var total: Int64 = 0+ var hasKnownTotal = true++ for target in targets {+ let id = recordId(for: target.destination)+ if FileManager.default.fileExists(atPath: target.destination.path) {+ let size = fileSize(target.destination)+ downloaded += size+ total += size+ continue+ }++ if let task = relevantTasks.first(where: { $0.taskDescription == id }) {+ downloaded += max(0, task.countOfBytesReceived)+ let expected = task.countOfBytesExpectedToReceive+ if expected > 0 {+ total += expected+ } else {+ hasKnownTotal = false+ }+ } else {+ hasKnownTotal = false+ }+ }++ let percent: Int+ let status: String+ if hasKnownTotal && total > 0 {+ percent = min(99, max(0, Int((Double(downloaded) / Double(total)) * 100.0)))+ status = "Downloading... \(downloaded.formattedFileSize) / \(total.formattedFileSize)"+ } else {+ percent = 0+ status = "Downloading model..."+ }+ return InferenceDownloadProgress(percent: percent, status: status)+ }++ func cancelAllDownloads() async {+ let tasks = await allTasks()+ tasks.forEach { $0.cancel() }+ clearAllRecords()+ }++ private func allTasks() async -> [URLSessionTask] {+ await withCheckedContinuation { continuation in+ session.getAllTasks { tasks in+ continuation.resume(returning: tasks)+ }+ }+ }++ private func recordId(for destination: URL) -> String {+ destination.path.sha256()+ }++ private func fileSize(_ url: URL) -> Int64 {+ let attrs = try? FileManager.default.attributesOfItem(atPath: url.path)+ return (attrs?[.size] as? NSNumber)?.int64Value ?? 0+ }++ private func firstFailure(for targets: [ModelDownloadTarget]) -> String? {+ let ids = Set(targets.map { recordId(for: $0.destination) })+ return loadRecords().values.first(where: { ids.contains($0.id) && $0.state == .failed })?.errorMessage+ }++ private func loadRecords() -> [String: DownloadRecord] {+ syncQueue.sync {+ guard let data = UserDefaults.standard.data(forKey: recordsKey),+ let decoded = try? JSONDecoder().decode([String: DownloadRecord].self, from: data) else {+ return [:]+ }+ return decoded+ }+ }++ private func saveRecords(_ records: [String: DownloadRecord]) {+ syncQueue.sync {+ let data = try? JSONEncoder().encode(records)+ UserDefaults.standard.set(data, forKey: recordsKey)+ }+ }++ private func saveRecord(_ record: DownloadRecord) {+ var records = loadRecords()+ records[record.id] = record+ saveRecords(records)+ }++ private func updateRecord(id: String, mutate: (inout DownloadRecord) -> Void) {+ var records = loadRecords()+ guard var record = records[id] else { return }+ mutate(&record)+ records[id] = record+ saveRecords(records)+ }++ private func clearRecords(for targets: [ModelDownloadTarget]) {+ var records = loadRecords()+ let ids = targets.map { recordId(for: $0.destination) }+ ids.forEach { records.removeValue(forKey: $0) }+ saveRecords(records)+ }++ private func clearAllRecords() {+ saveRecords([:])+ }++ private func markFailed(id: String, message: String) {+ updateRecord(id: id) { record in+ record.state = .failed+ record.errorMessage = message+ }+ }++ private func markActive(id: String) {+ updateRecord(id: id) { record in+ record.state = .downloading+ record.errorMessage = nil+ }+ }++ private func clearRecord(id: String) {+ var records = loadRecords()+ records.removeValue(forKey: id)+ saveRecords(records)+ }+}++extension ModelDownloadManager: URLSessionDownloadDelegate, URLSessionTaskDelegate {+ func urlSession(+ _ session: URLSession,+ downloadTask: URLSessionDownloadTask,+ didWriteData bytesWritten: Int64,+ totalBytesWritten: Int64,+ totalBytesExpectedToWrite: Int64+ ) {+ guard let id = downloadTask.taskDescription else { return }+ markActive(id: id)+ }++ func urlSession(+ _ session: URLSession,+ downloadTask: URLSessionDownloadTask,+ didFinishDownloadingTo location: URL+ ) {+ guard let id = downloadTask.taskDescription else { return }+ guard let record = loadRecords()[id] else { return }++ let destination = URL(fileURLWithPath: record.destinationPath)+ do {+ try FileManager.default.createDirectory(+ at: destination.deletingLastPathComponent(),+ withIntermediateDirectories: true,+ attributes: nil+ )+ if FileManager.default.fileExists(atPath: destination.path) {+ try FileManager.default.removeItem(at: destination)+ }+ try FileManager.default.moveItem(at: location, to: destination)+ if !destination.looksLikeGgufFile {+ try? FileManager.default.removeItem(at: destination)+ markFailed(id: id, message: "Downloaded file is not GGUF")+ return+ }+ clearRecord(id: id)+ } catch {+ markFailed(id: id, message: error.localizedDescription)+ }+ }++ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {+ guard let id = task.taskDescription else { return }+ if let error, (error as NSError).code != NSURLErrorCancelled {+ markFailed(id: id, message: error.localizedDescription)+ }+ }++ func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {+ syncQueue.async {+ let completion = self.backgroundCompletionHandler+ self.backgroundCompletionHandler = nil+ DispatchQueue.main.async {+ completion?()+ }+ }+ }+}++private extension URL {+ var looksLikeGgufFile: Bool {+ guard let handle = try? FileHandle(forReadingFrom: self) else { return false }+ let data = handle.readData(ofLength: 4)+ try? handle.close()+ guard data.count == 4 else { return false }+ return String(decoding: data, as: UTF8.self) == "GGUF"+ }+}++private extension String {+ func sha256() -> String {+ let data = Data(utf8)+ return SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()+ }+}