diff --git a/core/localization/src/androidMain/res/values-de/strings.xml b/core/localization/src/androidMain/res/values-de/strings.xml
index 042f09abd..4fb9e3dfd 100644
--- a/core/localization/src/androidMain/res/values-de/strings.xml
+++ b/core/localization/src/androidMain/res/values-de/strings.xml
@@ -729,9 +729,16 @@
Ein 512×512-Bild, PNDM, CFG 7,5, 1–50 Schritte. CPU oder Metal.
MNN-Backend
MNN-Modelle
- Modellkatalog wird geladen
Modelle konnten nicht geladen werden
Prüfe die Verbindung und versuche es erneut. Deine lokalen Modelle bleiben verfügbar.
Keine Modelle verfügbar
Versuche später, den Katalog erneut zu laden.
+ Alle herunterladen
+ Alle Downloads abbrechen
+ Downloads wechseln?
+ Ein anderer Anbieter lädt Modelle herunter. Beim Wechsel werden diese Downloads gestoppt und die Modelle dieses Anbieters geladen. Fertige Modelle bleiben erhalten.
+ Wechseln
+ Laden
+ Download abgeschlossen 🤩
+ Download fehlgeschlagen 😞
diff --git a/core/localization/src/androidMain/res/values-ru/strings.xml b/core/localization/src/androidMain/res/values-ru/strings.xml
index 8a7b25704..1874dd494 100644
--- a/core/localization/src/androidMain/res/values-ru/strings.xml
+++ b/core/localization/src/androidMain/res/values-ru/strings.xml
@@ -692,9 +692,16 @@
Одно изображение 512×512, PNDM, CFG 7.5, 1–50 шагов. CPU или Metal.
Движок MNN
Модели MNN
- Загрузка каталога моделей
Не удалось загрузить модели
Проверьте подключение и повторите попытку. Локальные модели остаются доступны.
Нет доступных моделей
Попробуйте обновить каталог позже.
+ Скачать все
+ Отменить все загрузки
+ Переключить загрузки?
+ Сейчас загружаются модели другого провайдера. Переключение остановит их загрузку и запустит загрузку моделей этого провайдера. Готовые модели сохранятся.
+ Переключить
+ Загрузка
+ Загрузка завершена 🤩
+ Не удалось загрузить 😞
diff --git a/core/localization/src/androidMain/res/values-tr/strings.xml b/core/localization/src/androidMain/res/values-tr/strings.xml
index 905b5c7a2..1f0ac45b9 100644
--- a/core/localization/src/androidMain/res/values-tr/strings.xml
+++ b/core/localization/src/androidMain/res/values-tr/strings.xml
@@ -692,9 +692,16 @@
Bir 512×512 görsel, PNDM, CFG 7.5, 1–50 adım. CPU veya Metal.
MNN arka ucu
MNN modelleri
- Model kataloğu yükleniyor
Modeller yüklenemedi
Bağlantınızı kontrol edip yeniden deneyin. Yerel modelleriniz kullanılabilir durumda.
Kullanılabilir model yok
Kataloğu daha sonra yeniden yenilemeyi deneyin.
+ Tümünü indir
+ Tüm indirmeleri iptal et
+ İndirmeler değiştirilsin mi?
+ Başka bir sağlayıcının modelleri indiriliyor. Değiştirmek bu indirmeleri durdurur ve bu sağlayıcının modellerini indirmeye başlar. Tamamlanan modeller korunur.
+ Değiştir
+ Yükleniyor
+ İndirme tamamlandı 🤩
+ İndirme başarısız 😞
diff --git a/core/localization/src/androidMain/res/values-uk/strings.xml b/core/localization/src/androidMain/res/values-uk/strings.xml
index 5695e3e8c..432e2d8c7 100644
--- a/core/localization/src/androidMain/res/values-uk/strings.xml
+++ b/core/localization/src/androidMain/res/values-uk/strings.xml
@@ -692,9 +692,16 @@
Одне зображення 512×512, PNDM, CFG 7.5, 1–50 кроків. CPU або Metal.
Рушій MNN
Моделі MNN
- Завантаження каталогу моделей
Не вдалося завантажити моделі
Перевірте з’єднання та спробуйте знову. Локальні моделі залишаються доступними.
Немає доступних моделей
Спробуйте оновити каталог пізніше.
+ Завантажити всі
+ Скасувати всі завантаження
+ Перемкнути завантаження?
+ Зараз завантажуються моделі іншого провайдера. Перемикання зупинить їх завантаження та почне завантаження моделей цього провайдера. Готові моделі збережуться.
+ Перемкнути
+ Завантаження
+ Завантаження завершено 🤩
+ Не вдалося завантажити 😞
diff --git a/core/localization/src/androidMain/res/values-zh/strings.xml b/core/localization/src/androidMain/res/values-zh/strings.xml
index f30181ee7..38ac75353 100644
--- a/core/localization/src/androidMain/res/values-zh/strings.xml
+++ b/core/localization/src/androidMain/res/values-zh/strings.xml
@@ -744,9 +744,16 @@
单张512×512图像,PNDM,CFG 7.5,1–50步。CPU或Metal。
MNN 后端
MNN 模型
- 正在加载模型目录
无法加载模型
请检查网络连接后重试。本地模型仍可使用。
暂无可用模型
请稍后重试刷新目录。
+ 全部下载
+ 取消全部下载
+ 切换下载?
+ 正在下载其他提供商的模型。切换将停止这些下载,并开始下载此提供商的模型。已完成的模型会保留。
+ 切换
+ 加载中
+ 下载完成 🤩
+ 下载失败 😞
diff --git a/core/localization/src/androidMain/res/values/strings.xml b/core/localization/src/androidMain/res/values/strings.xml
index 4fa1078a9..e69b7980f 100755
--- a/core/localization/src/androidMain/res/values/strings.xml
+++ b/core/localization/src/androidMain/res/values/strings.xml
@@ -729,9 +729,16 @@
One 512×512 image, PNDM, CFG 7.5, 1–50 steps. CPU or Metal.
MNN backend
MNN models
- Loading model catalog
Unable to load models
Check your connection and try again. Your local models remain available.
No models available
Try refreshing the catalog again later.
+ Download all
+ Cancel all downloads
+ Switch downloads?
+ Another provider is downloading models. Switching stops those downloads and starts this provider. Completed models are kept.
+ Switch
+ Loading
+ Download complete 🤩
+ Download failed 😞
diff --git a/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/local/AndroidDownloadableModelFileStore.kt b/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/local/AndroidDownloadableModelFileStore.kt
index ec6a2e7fd..a7a422952 100644
--- a/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/local/AndroidDownloadableModelFileStore.kt
+++ b/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/local/AndroidDownloadableModelFileStore.kt
@@ -26,47 +26,50 @@ internal class AndroidDownloadableModelFileStore(
*
* @author Dmitriy Moroz
*/
- override fun isDownloaded(model: LocalAiModel): Boolean = try {
- when (model.id) {
- LocalAiModel.CustomMnn.id -> mnnModels.isDownloaded(model.id)
-
-
- LocalAiModel.CustomOnnx.id,
- LocalAiModel.CustomMediaPipe.id,
- LocalAiModel.CustomSdxl.id,
- LocalAiModel.CustomCoreMl.id,
- LocalAiModel.CustomBonsai.id,
- -> true
-
- else -> when (model.type) {
- LocalAiModel.Type.Mnn -> mnnModels.isDownloaded(model.id)
- LocalAiModel.Type.ONNX -> {
- val files = getLocalModelFiles(model.id).filter { it.isDirectory }
- files.size == 4
- }
-
- LocalAiModel.Type.MediaPipe -> {
- val files = getLocalModelFiles(model.id)
- files.isNotEmpty()
- }
-
- LocalAiModel.Type.Sdxl -> {
- val files = getLocalModelFiles(model.id)
- files.isNotEmpty()
- }
-
- LocalAiModel.Type.CoreMl -> {
- val files = getLocalModelFiles(model.id)
- files.isNotEmpty()
- }
-
- LocalAiModel.Type.Bonsai -> {
- getLocalModelDirectory(model.id).hasBonsaiModelLayout()
+ override fun isDownloaded(model: LocalAiModel): Boolean {
+ if (File(getLocalModelDirectory(model.id), ".download-in-progress").exists()) return false
+ return try {
+ when (model.id) {
+ LocalAiModel.CustomMnn.id -> mnnModels.isDownloaded(model.id)
+
+
+ LocalAiModel.CustomOnnx.id,
+ LocalAiModel.CustomMediaPipe.id,
+ LocalAiModel.CustomSdxl.id,
+ LocalAiModel.CustomCoreMl.id,
+ LocalAiModel.CustomBonsai.id,
+ -> true
+
+ else -> when (model.type) {
+ LocalAiModel.Type.Mnn -> mnnModels.isDownloaded(model.id)
+ LocalAiModel.Type.ONNX -> {
+ val files = getLocalModelFiles(model.id).filter { it.isDirectory }
+ files.size == 4
+ }
+
+ LocalAiModel.Type.MediaPipe -> {
+ val files = getLocalModelFiles(model.id)
+ files.isNotEmpty()
+ }
+
+ LocalAiModel.Type.Sdxl -> {
+ val files = getLocalModelFiles(model.id)
+ files.isNotEmpty()
+ }
+
+ LocalAiModel.Type.CoreMl -> {
+ val files = getLocalModelFiles(model.id)
+ files.isNotEmpty()
+ }
+
+ LocalAiModel.Type.Bonsai -> {
+ getLocalModelDirectory(model.id).hasBonsaiModelLayout()
+ }
}
}
+ } catch (_: Exception) {
+ false
}
- } catch (_: Exception) {
- false
}
/**
diff --git a/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/remote/AndroidDownloadableModelFileDownloader.kt b/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/remote/AndroidDownloadableModelFileDownloader.kt
index eba565838..34af9cc89 100644
--- a/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/remote/AndroidDownloadableModelFileDownloader.kt
+++ b/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/remote/AndroidDownloadableModelFileDownloader.kt
@@ -87,7 +87,9 @@ internal class AndroidDownloadableModelFileDownloader(
}
val dir = File("${fileProviderDescriptor.localModelDirPath}/$id")
if (dir.exists()) dir.deleteRecursively()
- dir.mkdirs()
+ check(dir.mkdirs()) { "Cannot create model directory" }
+ val pending = File(dir, ".download-in-progress")
+ check(pending.createNewFile()) { "Cannot mark incomplete model download" }
val destination = File(getDestinationPath(id, url))
@@ -102,6 +104,7 @@ internal class AndroidDownloadableModelFileDownloader(
complete.unzip()
complete.delete()
}
+ check(pending.delete()) { "Cannot finalize model download" }
emit(DownloadState.Complete(complete.path))
} catch (e: CancellationException) {
dir.deleteRecursively()
diff --git a/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/local/ModelDownloadMarkerTest.kt b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/local/ModelDownloadMarkerTest.kt
new file mode 100644
index 000000000..c5ad4b1ae
--- /dev/null
+++ b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/local/ModelDownloadMarkerTest.kt
@@ -0,0 +1,79 @@
+package com.shifthackz.aisdv1.data.local
+
+import com.shifthackz.aisdv1.core.common.file.FileProviderDescriptor
+import com.shifthackz.aisdv1.domain.entity.LocalAiModel
+import io.mockk.every
+import io.mockk.mockk
+import java.io.File
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+import org.junit.runner.RunWith
+import org.junit.runners.Parameterized
+
+/**
+ * Protects every legacy provider from treating interrupted app-owned payloads as installed models.
+ * @param type Provider whose complete layout is checked before and after activation.
+ * @author Dmitriy Moroz
+ */
+@RunWith(Parameterized::class)
+class ModelDownloadMarkerTest(private val type: LocalAiModel.Type) {
+ @get:Rule
+ val folder = TemporaryFolder()
+
+ @Test
+ fun `given owned model directory, interrupted marker accompanies complete looking files, expected model unavailable`() {
+ // Given
+ val model = LocalAiModel("catalog", type, "Model", "1 GB", emptyList())
+ val directory = folder.newFolder(model.id)
+ listOf(
+ "transformer-packed-mflux",
+ "text_encoder-mlx-4bit",
+ "tokenizer",
+ "vae"
+ ).forEach { File(directory, it).mkdirs() }
+ File(directory, ".download-in-progress").createNewFile()
+ val descriptor =
+ mockk { every { localModelDirPath } returns folder.root.path }
+ val store = AndroidDownloadableModelFileStore(descriptor, mockk(relaxed = true))
+ // When
+ val isDownloaded = store.isDownloaded(model)
+ // Then
+ assertFalse(isDownloaded)
+ assertTrue(directory.exists())
+ }
+
+ @Test
+ fun `given owned model directory, activation removes pending marker, expected completed layout becomes available`() {
+ // Given
+ val model = LocalAiModel("catalog", type, "Model", "1 GB", emptyList())
+ val directory = folder.newFolder(model.id)
+ listOf(
+ "transformer-packed-mflux",
+ "text_encoder-mlx-4bit",
+ "tokenizer",
+ "vae"
+ ).forEach { File(directory, it).mkdirs() }
+ File(directory, "transformer-packed-mflux/quantization_config.json").writeText("{}")
+ if (type == LocalAiModel.Type.Bonsai) File(directory, "scheduler").mkdirs()
+ val pending = File(directory, ".download-in-progress").apply { createNewFile() }
+ val descriptor =
+ mockk { every { localModelDirPath } returns folder.root.path }
+ val store = AndroidDownloadableModelFileStore(descriptor, mockk(relaxed = true))
+ // When
+ pending.delete()
+ val isDownloaded = store.isDownloaded(model)
+ // Then
+ assertTrue(isDownloaded)
+ }
+
+ companion object {
+ /** Supplies providers that activate their downloads in the shared app-private model directory. */
+ @JvmStatic
+ @Parameterized.Parameters(name = "{0}")
+ fun providers() =
+ LocalAiModel.Type.entries.filterNot { it == LocalAiModel.Type.Mnn }.map { arrayOf(it) }
+ }
+}
diff --git a/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/remote/AndroidModelDownloadLifecycleTest.kt b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/remote/AndroidModelDownloadLifecycleTest.kt
new file mode 100644
index 000000000..1c64c62bb
--- /dev/null
+++ b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/remote/AndroidModelDownloadLifecycleTest.kt
@@ -0,0 +1,113 @@
+package com.shifthackz.aisdv1.data.remote
+
+import com.shifthackz.aisdv1.core.common.file.FileProviderDescriptor
+import io.mockk.every
+import io.mockk.mockk
+import io.mockk.mockkConstructor
+import io.mockk.unmockkConstructor
+import java.io.File
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.flow.toList
+import kotlinx.coroutines.test.runTest
+import okhttp3.Call
+import okhttp3.OkHttpClient
+import okhttp3.Protocol
+import okhttp3.Request
+import okhttp3.Response
+import okhttp3.ResponseBody.Companion.toResponseBody
+import com.shifthackz.aisdv1.domain.entity.DownloadState
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+
+/**
+ * Exercises real file activation and cleanup while isolating HTTP transport at the downloader boundary.
+ * @author Dmitriy Moroz
+ */
+class AndroidModelDownloadLifecycleTest {
+ @get:Rule
+ val folder = TemporaryFolder()
+ private val client = mockk()
+ private val call = mockk()
+ private val url = "https://models/model.bin"
+
+ @Before
+ fun initialize() {
+ mockkConstructor(OkHttpClient.Builder::class)
+ every { anyConstructed().build() } returns client
+ every { client.newCall(any()) } returns call
+ }
+
+ @After
+ fun releaseTransport() {
+ unmockkConstructor(OkHttpClient.Builder::class)
+ }
+
+ @Test
+ fun `given owned model download, transfer completes, expected pending marker removed before Complete`() =
+ runTest {
+ // Given
+ every { call.execute() } answers {
+ assertTrue(File(folder.root, "model/.download-in-progress").isFile)
+ response(200)
+ }
+ val downloader = downloader()
+ // When
+ val states = downloader.download("model", url).toList()
+ // Then
+ assertTrue(states.last() is DownloadState.Complete)
+ assertFalse(File(folder.root, "model/.download-in-progress").exists())
+ assertEquals("model bytes", File(folder.root, "model/model.bin").readText())
+ }
+
+ @Test
+ fun `given owned model download, server rejects archive, expected Error and partial directory removed`() =
+ runTest {
+ // Given
+ every { call.execute() } returns response(503)
+ val downloader = downloader()
+ // When
+ val states = downloader.download("model", url).toList()
+ // Then
+ assertTrue(states.last() is DownloadState.Error)
+ assertFalse(File(folder.root, "model").exists())
+ }
+
+ @Test
+ fun `given owned model download, transport is cancelled, expected cancellation and private partial cleanup only`() =
+ runTest {
+ // Given
+ val cancellation = CancellationException("cancelled")
+ every { call.execute() } throws cancellation
+ val source = folder.newFile("user-model.bin").apply { writeText("original") }
+ val downloader = downloader()
+ // When
+ val actual =
+ runCatching { downloader.download("model", url).toList() }.exceptionOrNull()
+ // Then
+ assertTrue(actual is CancellationException)
+ assertEquals(cancellation.message, actual?.message)
+ assertFalse(File(folder.root, "model").exists())
+ assertEquals("original", source.readText())
+ }
+
+ /** Builds the real downloader with a private temporary model root and isolated accounting. */
+ private fun downloader() = AndroidDownloadableModelFileDownloader(
+ mockk { every { localModelDirPath } returns folder.root.path },
+ mockk(relaxed = true), mockk(relaxed = true),
+ )
+
+ /**
+ * Creates a bounded unit transport response; no network server or app flow is substituted.
+ * @param code HTTP outcome supplied by the isolated transport boundary.
+ * @author Dmitriy Moroz
+ */
+ private fun response(code: Int) = Response.Builder().request(Request.Builder().url(url).build())
+ .protocol(Protocol.HTTP_1_1).code(code).message("unit response")
+ .body("model bytes".toResponseBody()).build()
+}
diff --git a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/entity/ModelDownloadBatchTest.kt b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/entity/ModelDownloadBatchTest.kt
new file mode 100644
index 000000000..00388f181
--- /dev/null
+++ b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/entity/ModelDownloadBatchTest.kt
@@ -0,0 +1,72 @@
+package com.shifthackz.aisdv1.domain.entity
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.Parameterized
+
+/**
+ * Verifies aggregate progress at model handoff, activation and empty-catalog boundaries.
+ * @param snapshot Work snapshot whose visible aggregate progress is evaluated.
+ * @param expected Whole-download percentage expected in the notification.
+ * @author Dmitriy Moroz
+ */
+@RunWith(Parameterized::class)
+class ModelDownloadBatchTest(private val snapshot: ModelDownloadBatch, private val expected: Int) {
+ @Test
+ fun `given download progress, active model or completed count changes, expected bounded equal model shares`() {
+ // Given
+ val state = snapshot
+ // When
+ val actual = state.totalProgress
+ // Then
+ assertEquals(expected, actual)
+ }
+
+ companion object {
+ /** Supplies initial, mid-model, handoff, final and out-of-range progress boundaries. */
+ @JvmStatic
+ @Parameterized.Parameters(name = "{0} -> {1}")
+ fun snapshots(): List> {
+ val batch = ModelDownloadBatch(LocalAiModel.Type.ONNX, totalModelCount = 4)
+ return listOf(
+ arrayOf(batch, 0),
+ arrayOf(batch.copy(progress = DownloadState.Downloading(50)), 12),
+ arrayOf(batch.copy(completedIds = listOf("first")), 25),
+ arrayOf(
+ batch.copy(
+ completedIds = listOf("first"),
+ progress = DownloadState.Downloading(50)
+ ), 37
+ ),
+ arrayOf(
+ batch.copy(
+ completedIds = listOf("first"),
+ progress = DownloadState.Complete("/owned/first")
+ ), 25
+ ),
+ arrayOf(
+ batch.copy(completedIds = listOf("a", "b", "c", "d"), isRunning = false),
+ 100
+ ),
+ arrayOf(batch.copy(progress = DownloadState.Downloading(-100)), 0),
+ arrayOf(batch.copy(progress = DownloadState.Downloading(900)), 100),
+ arrayOf(batch.copy(totalModelCount = 0), 0),
+ arrayOf(batch.copy(totalModelCount = 0, isRunning = false), 100),
+ arrayOf(
+ batch.copy(
+ totalModelCount = 1,
+ isBatch = false,
+ progress = DownloadState.Downloading(45)
+ ), 45
+ ),
+ arrayOf(
+ batch.copy(
+ completedIds = listOf("first"),
+ progress = DownloadState.Error(IllegalStateException("offline"))
+ ), 25
+ ),
+ )
+ }
+ }
+}
diff --git a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/entity/ModelDownloadRequestTest.kt b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/entity/ModelDownloadRequestTest.kt
new file mode 100644
index 000000000..385ca5365
--- /dev/null
+++ b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/entity/ModelDownloadRequestTest.kt
@@ -0,0 +1,57 @@
+package com.shifthackz.aisdv1.domain.entity
+
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Prevents ambiguous persisted requests that identify a single model without its selected archive.
+ * @author Dmitriy Moroz
+ */
+class ModelDownloadRequestTest {
+ @Test
+ fun `given provider download request, no archive is selected, expected batch mode`() {
+ // Given
+ val type = LocalAiModel.Type.ONNX
+ // When
+ val request = ModelDownloadRequest(type)
+ // Then
+ assertTrue(request.isBatch)
+ }
+
+ @Test
+ fun `given provider download request, model and mirror are selected, expected single mode`() {
+ // Given
+ val type = LocalAiModel.Type.MediaPipe
+ // When
+ val request = ModelDownloadRequest(type, "model", "https://models/model")
+ // Then
+ assertFalse(request.isBatch)
+ }
+
+ @Test
+ fun `given provider download request, mirror is absent for selected model, expected invalid request rejected`() {
+ // Given
+ val type = LocalAiModel.Type.ONNX
+ // When
+ val failure =
+ runCatching { ModelDownloadRequest(type, modelId = "model") }.exceptionOrNull()
+ // Then
+ assertTrue(failure is IllegalArgumentException)
+ }
+
+ @Test
+ fun `given provider download request, model is absent for selected mirror, expected invalid request rejected`() {
+ // Given
+ val type = LocalAiModel.Type.ONNX
+ // When
+ val failure = runCatching {
+ ModelDownloadRequest(
+ type,
+ sourceUrl = "https://models/model"
+ )
+ }.exceptionOrNull()
+ // Then
+ assertTrue(failure is IllegalArgumentException)
+ }
+}
diff --git a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelUseCaseImplTest.kt b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelUseCaseImplTest.kt
index 16084533e..2e7d565df 100644
--- a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelUseCaseImplTest.kt
+++ b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelUseCaseImplTest.kt
@@ -4,137 +4,171 @@ import com.shifthackz.aisdv1.domain.entity.DownloadState
import com.shifthackz.aisdv1.domain.repository.DownloadableModelRepository
import io.mockk.every
import io.mockk.mockk
+import io.mockk.verify
+import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
-import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.NonCancellable
+import kotlinx.coroutines.awaitCancellation
+import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
-import kotlinx.coroutines.flow.take
+import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
+import kotlinx.coroutines.withContext
import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
import org.junit.Assert.assertSame
-import org.junit.Before
+import org.junit.Assert.assertTrue
import org.junit.Test
+/**
+ * Verifies faithful repository streaming and per-model ownership through cancellation cleanup.
+ * @author Dmitriy Moroz
+ */
@OptIn(ExperimentalCoroutinesApi::class)
class DownloadModelUseCaseImplTest {
-
- private val stubFilePath = "/storage/emulated/0/file.dat"
- private val stubException = Throwable("Error downloading file.")
- private val stubTerminateException = Throwable("Unexpected Flow termination.")
- private val stubDownloadStatus = MutableSharedFlow()
- private val stubRepository = mockk()
-
- private val useCase = DownloadModelUseCaseImpl(stubRepository)
-
- @Before
- fun initialize() {
- every {
- stubRepository.download(any(), any())
- } returns stubDownloadStatus
- }
+ private val repository = mockk()
+ private val useCase = DownloadModelUseCaseImpl(repository)
@Test
- fun `given download running, then finishes successfully, expected final state is Complete`() = runTest {
- val values = mutableListOf()
- val job = launch {
- useCase("5598", "https://moroz.cc/stub.zip")
- .take(4)
- .toList(values)
- }
- runCurrent()
-
- stubDownloadStatus.emit(DownloadState.Unknown)
- stubDownloadStatus.emit(DownloadState.Downloading(33))
- stubDownloadStatus.emit(DownloadState.Downloading(100))
- stubDownloadStatus.emit(DownloadState.Complete(stubFilePath))
- job.join()
-
- assertEquals(
- listOf(
+ fun `given model download, repository reports progress and activation, expected states and selected mirror preserved`() =
+ runTest {
+ // Given
+ val states = listOf(
DownloadState.Unknown,
DownloadState.Downloading(33),
- DownloadState.Downloading(100),
- DownloadState.Complete(stubFilePath),
- ),
- values,
- )
- }
+ DownloadState.Complete("/owned/model")
+ )
+ every {
+ repository.download(
+ "model",
+ "https://mirror/model"
+ )
+ } returns flowOf(*states.toTypedArray())
+ // When
+ val actual = useCase("model", "https://mirror/model").toList()
+ // Then
+ assertEquals(states, actual)
+ verify(exactly = 1) { repository.download("model", "https://mirror/model") }
+ }
@Test
- fun `given download running, then fails, expected final state is Error`() = runTest {
- val values = mutableListOf()
- val job = launch {
- useCase("5598", "https://moroz.cc/stub.zip")
- .take(4)
- .toList(values)
+ fun `given model download, repository emits failure state, expected same error without fallback`() =
+ runTest {
+ // Given
+ val failure = IllegalStateException("offline")
+ every { repository.download(any(), any()) } returns flowOf(DownloadState.Error(failure))
+ // When
+ val actual = useCase("model", "https://mirror/model").toList().single()
+ // Then
+ assertSame(failure, (actual as DownloadState.Error).error)
}
- runCurrent()
-
- stubDownloadStatus.emit(DownloadState.Unknown)
- stubDownloadStatus.emit(DownloadState.Downloading(33))
- stubDownloadStatus.emit(DownloadState.Downloading(100))
- stubDownloadStatus.emit(DownloadState.Error(stubException))
- job.join()
-
- assertEquals(
- listOf(
- DownloadState.Unknown,
- DownloadState.Downloading(33),
- DownloadState.Downloading(100),
- DownloadState.Error(stubException),
- ),
- values,
- )
- }
@Test
- fun `given download running, then fails, then user restarts download, then completes, expected state Error on 1st try, final state is Complete`() = runTest {
- val values = mutableListOf()
- val job = launch {
- useCase("5598", "https://moroz.cc/stub.zip")
- .take(8)
- .toList(values)
+ fun `given model download, repository throws then retry succeeds, expected original failure and released model ownership`() =
+ runTest {
+ // Given
+ val failure = IllegalStateException("transport closed")
+ every { repository.download(any(), any()) } returnsMany listOf(
+ flow { throw failure },
+ flowOf(DownloadState.Complete("/owned/model"))
+ )
+ // When
+ val actual =
+ runCatching { useCase("model", "https://mirror/model").collect() }.exceptionOrNull()
+ val retry = useCase("model", "https://mirror/model").toList()
+ // Then
+ assertSame(failure, actual)
+ assertEquals(listOf(DownloadState.Complete("/owned/model")), retry)
}
- runCurrent()
-
- stubDownloadStatus.emit(DownloadState.Unknown)
- stubDownloadStatus.emit(DownloadState.Downloading(33))
- stubDownloadStatus.emit(DownloadState.Downloading(100))
- stubDownloadStatus.emit(DownloadState.Error(stubException))
- stubDownloadStatus.emit(DownloadState.Unknown)
- stubDownloadStatus.emit(DownloadState.Downloading(33))
- stubDownloadStatus.emit(DownloadState.Downloading(100))
- stubDownloadStatus.emit(DownloadState.Complete(stubFilePath))
- job.join()
-
- assertEquals(
- listOf(
- DownloadState.Unknown,
- DownloadState.Downloading(33),
- DownloadState.Downloading(100),
- DownloadState.Error(stubException),
- DownloadState.Unknown,
- DownloadState.Downloading(33),
- DownloadState.Downloading(100),
- DownloadState.Complete(stubFilePath),
- ),
- values,
- )
- }
@Test
- fun `given flow terminated with unexpected error, expected error value`() = runTest {
- every {
- stubRepository.download(any(), any())
- } returns flow { throw stubTerminateException }
+ fun `given distinct model downloads, first transfer stays active, expected second transfer progresses concurrently`() =
+ runTest {
+ // Given
+ val started = mutableListOf()
+ every { repository.download(any(), any()) } answers {
+ val id = firstArg()
+ flow { started += id; emit(DownloadState.Downloading(10)); awaitCancellation() }
+ }
+ // When
+ val first = launch { useCase("first", "https://mirror/first").collect() }
+ val second = launch { useCase("second", "https://mirror/second").collect() }
+ runCurrent()
+ val activeIds = started.toList()
+ first.cancelAndJoin()
+ val isSecondStillRunning = second.isActive
+ second.cancelAndJoin()
+ // Then
+ assertEquals(listOf("first", "second"), activeIds)
+ assertTrue(isSecondStillRunning)
+ }
- val actual = runCatching {
- useCase("5598", "https://moroz.cc/stub.zip").collect()
- }.exceptionOrNull()
+ @Test
+ fun `given same model replacement, cancelled archive cleanup is pending, expected replacement waits before writing`() =
+ runTest {
+ // Given
+ val cleanupStarted = CompletableDeferred()
+ val releaseCleanup = CompletableDeferred()
+ every { repository.download("model", "https://first") } returns flow {
+ try {
+ emit(DownloadState.Downloading(10)); awaitCancellation()
+ } finally {
+ withContext(NonCancellable) { cleanupStarted.complete(Unit); releaseCleanup.await() }
+ }
+ }
+ every { repository.download("model", "https://replacement") } returns flowOf(
+ DownloadState.Complete("/owned/model")
+ )
+ val result = mutableListOf()
+ val first = launch { useCase("model", "https://first").collect() }
+ runCurrent()
+ // When
+ first.cancel()
+ runCurrent()
+ cleanupStarted.await()
+ val replacement = launch { useCase("model", "https://replacement").toList(result) }
+ runCurrent()
+ val beforeCleanup = result.toList()
+ verify(exactly = 0) { repository.download("model", "https://replacement") }
+ releaseCleanup.complete(Unit)
+ first.join()
+ replacement.join()
+ // Then
+ assertTrue(beforeCleanup.isEmpty())
+ assertEquals(listOf(DownloadState.Complete("/owned/model")), result)
+ }
- assertSame(stubTerminateException, actual)
- }
+ @Test
+ fun `given same model queued download, waiter is cancelled, expected no repository work and later requests still succeed`() =
+ runTest {
+ // Given
+ every {
+ repository.download(
+ "model",
+ "https://first"
+ )
+ } returns flow { awaitCancellation() }
+ every {
+ repository.download(
+ "model",
+ "https://later"
+ )
+ } returns flowOf(DownloadState.Complete("/owned/model"))
+ val first = launch { useCase("model", "https://first").collect() }
+ runCurrent()
+ val waiter = launch { useCase("model", "https://cancelled").collect() }
+ runCurrent()
+ // When
+ waiter.cancelAndJoin()
+ first.cancelAndJoin()
+ val later = useCase("model", "https://later").toList()
+ // Then
+ assertFalse(waiter.isActive)
+ verify(exactly = 0) { repository.download("model", "https://cancelled") }
+ assertEquals(listOf(DownloadState.Complete("/owned/model")), later)
+ }
}
diff --git a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelsUseCaseImplTest.kt b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelsUseCaseImplTest.kt
new file mode 100644
index 000000000..26d2e6215
--- /dev/null
+++ b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelsUseCaseImplTest.kt
@@ -0,0 +1,320 @@
+package com.shifthackz.aisdv1.domain.usecase.downloadable
+
+import com.shifthackz.aisdv1.domain.entity.DownloadState
+import com.shifthackz.aisdv1.domain.entity.LocalAiModel
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadBatch
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadRequest
+import io.mockk.coEvery
+import io.mockk.coVerify
+import io.mockk.every
+import io.mockk.mockk
+import io.mockk.verify
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.collect
+import kotlinx.coroutines.flow.emptyFlow
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.toList
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertSame
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.Parameterized
+
+/**
+ * Applies selection, sequencing and failure contracts to every supported local model family.
+ * @param type Provider whose cached catalog and download ownership must be retained.
+ * @author Dmitriy Moroz
+ */
+@OptIn(ExperimentalCoroutinesApi::class)
+@RunWith(Parameterized::class)
+class DownloadModelsUseCaseImplTest(private val type: LocalAiModel.Type) {
+ private val catalog = mockk()
+ private val download = mockk()
+ private val useCase = DownloadModelsUseCaseImpl(catalog, download)
+ private val first = LocalAiModel(
+ "first",
+ type,
+ "First",
+ "1 GB",
+ listOf("https://models/first", "https://mirror/first")
+ )
+ private val second =
+ first.copy(id = "second", name = "Second", sources = listOf("https://models/second"))
+
+ @Test
+ fun `given provider batch, first archive remains active, expected next archive starts only after activation`() =
+ runTest {
+ // Given
+ val release = CompletableDeferred()
+ val started = mutableListOf()
+ val snapshots = mutableListOf()
+ coEvery { catalog(type) } returns listOf(first, second)
+ every { download(any(), any()) } answers {
+ val id = firstArg()
+ flow {
+ started += id
+ if (id == first.id) release.await()
+ emit(DownloadState.Complete("/owned/$id"))
+ }
+ }
+ // When
+ val job = launch { useCase(ModelDownloadRequest(type)).toList(snapshots) }
+ runCurrent()
+ val whileBlocked = started.toList()
+ release.complete(Unit)
+ job.join()
+ // Then
+ assertEquals(listOf(first.id), whileBlocked)
+ assertEquals(listOf(first.id, second.id), started)
+ assertEquals(listOf(first.id, second.id), snapshots.last().completedIds)
+ assertEquals(100, snapshots.last().totalProgress)
+ assertFalse(snapshots.last().isRunning)
+ assertEquals(type, snapshots.last().type)
+ verify(exactly = 1) { download(first.id, first.sources.first()) }
+ }
+
+ @Test
+ fun `given provider batch, installed and sourceless entries exist, expected only missing downloadable models counted`() =
+ runTest {
+ // Given
+ coEvery { catalog(type) } returns listOf(
+ first.copy(downloaded = true),
+ second,
+ first.copy(id = "custom", sources = emptyList())
+ )
+ every {
+ download(
+ second.id,
+ second.sources.first()
+ )
+ } returns flowOf(DownloadState.Complete("/owned/second"))
+ // When
+ val snapshots = useCase(ModelDownloadRequest(type)).toList()
+ // Then
+ assertTrue(snapshots.all { it.totalModelCount == 1 && it.isBatch })
+ assertEquals(listOf(second.id), snapshots.last().completedIds)
+ verify(exactly = 1) { download(any(), any()) }
+ }
+
+ @Test
+ fun `given single model request, alternative mirror is confirmed, expected only selected archive uses that mirror`() =
+ runTest {
+ // Given
+ coEvery { catalog(type) } returns listOf(first, second)
+ every {
+ download(
+ first.id,
+ first.sources.last()
+ )
+ } returns flowOf(DownloadState.Complete("/owned/first"))
+ // When
+ val snapshots =
+ useCase(ModelDownloadRequest(type, first.id, first.sources.last())).toList()
+ // Then
+ assertTrue(snapshots.all { !it.isBatch && it.totalModelCount == 1 })
+ assertEquals(listOf(first.id), snapshots.last().completedIds)
+ verify(exactly = 0) { download(second.id, any()) }
+ }
+
+ @Test
+ fun `given single model request, activation already exists, expected no transfer and completed empty selection`() =
+ runTest {
+ // Given
+ coEvery { catalog(type) } returns listOf(first.copy(downloaded = true))
+ // When
+ val result =
+ useCase(ModelDownloadRequest(type, first.id, first.sources.first())).toList()
+ .single()
+ // Then
+ assertFalse(result.isRunning)
+ assertEquals(100, result.totalProgress)
+ assertEquals(0, result.totalModelCount)
+ verify(exactly = 0) { download(any(), any()) }
+ }
+
+ @Test
+ fun `given single model request, identity is absent from catalog, expected rejection before any archive starts`() =
+ runTest {
+ // Given
+ coEvery { catalog(type) } returns listOf(second)
+ // When
+ val failure = runCatching {
+ useCase(
+ ModelDownloadRequest(
+ type,
+ first.id,
+ first.sources.first()
+ )
+ ).collect()
+ }.exceptionOrNull()
+ // Then
+ assertTrue(failure is IllegalArgumentException)
+ verify(exactly = 0) { download(any(), any()) }
+ }
+
+ @Test
+ fun `given provider batch, cache read fails, expected same failure and no download`() =
+ runTest {
+ // Given
+ val failure = IllegalStateException("cache unavailable")
+ coEvery { catalog(type) } throws failure
+ // When
+ val actual =
+ runCatching { useCase(ModelDownloadRequest(type)).collect() }.exceptionOrNull()
+ // Then
+ assertSame(failure, actual)
+ coVerify(exactly = 1) { catalog(type) }
+ verify(exactly = 0) { download(any(), any()) }
+ }
+
+ @Test
+ fun `given provider batch, archive emits error state, expected original error and remaining models untouched`() =
+ runTest {
+ // Given
+ val failure = IllegalStateException("network unavailable")
+ coEvery { catalog(type) } returns listOf(first, second)
+ every { download(first.id, any()) } returns flowOf(
+ DownloadState.Downloading(20),
+ DownloadState.Error(failure)
+ )
+ // When
+ val actual =
+ runCatching { useCase(ModelDownloadRequest(type)).collect() }.exceptionOrNull()
+ // Then
+ assertSame(failure, actual)
+ verify(exactly = 0) { download(second.id, any()) }
+ }
+
+ @Test
+ fun `given provider batch, transfer throws cancellation, expected same cancellation without next model or terminal success`() =
+ runTest {
+ // Given
+ val cancellation = CancellationException("cancelled by owner")
+ val snapshots = mutableListOf()
+ coEvery { catalog(type) } returns listOf(first, second)
+ every { download(first.id, any()) } returns flow { throw cancellation }
+ // When
+ val actual =
+ runCatching { useCase(ModelDownloadRequest(type)).toList(snapshots) }.exceptionOrNull()
+ // Then
+ assertSame(cancellation, actual)
+ assertTrue(snapshots.none { !it.isRunning })
+ verify(exactly = 0) { download(second.id, any()) }
+ }
+
+ @Test
+ fun `given provider batch, transfer ends without activation, expected failure without advancing queue`() =
+ runTest {
+ // Given
+ coEvery { catalog(type) } returns listOf(first, second)
+ every { download(first.id, any()) } returns emptyFlow()
+ // When
+ val failure =
+ runCatching { useCase(ModelDownloadRequest(type)).collect() }.exceptionOrNull()
+ // Then
+ assertTrue(failure is IllegalStateException)
+ verify(exactly = 0) { download(second.id, any()) }
+ }
+
+ @Test
+ fun `given provider batch, progress repeats before completion, expected distinct updates and one completed identity`() =
+ runTest {
+ // Given
+ coEvery { catalog(type) } returns listOf(first)
+ every { download(first.id, any()) } returns flowOf(
+ DownloadState.Downloading(25),
+ DownloadState.Downloading(25),
+ DownloadState.Complete("/owned/first"),
+ DownloadState.Complete("/owned/first")
+ )
+ // When
+ val snapshots = useCase(ModelDownloadRequest(type)).toList()
+ // Then
+ assertEquals(1, snapshots.count { it.progress == DownloadState.Downloading(25) })
+ assertEquals(listOf(first.id), snapshots.last().completedIds)
+ assertEquals(first.name, snapshots.last().modelName)
+ }
+
+ @Test
+ fun `given provider batch, catalog is empty, expected terminal success without transfer`() =
+ runTest {
+ // Given
+ coEvery { catalog(type) } returns emptyList()
+ // When
+ val result = useCase(ModelDownloadRequest(type)).toList().single()
+ // Then
+ assertFalse(result.isRunning)
+ assertEquals(100, result.totalProgress)
+ verify(exactly = 0) { download(any(), any()) }
+ }
+
+ @Test
+ fun `given single model request, selected catalog entry has no archive sources, expected rejection before transfer`() =
+ runTest {
+ // Given
+ coEvery { catalog(type) } returns listOf(first.copy(sources = emptyList()))
+ // When
+ val failure = runCatching {
+ useCase(
+ ModelDownloadRequest(
+ type,
+ first.id,
+ "https://models/first"
+ )
+ ).collect()
+ }.exceptionOrNull()
+ // Then
+ assertTrue(failure is IllegalArgumentException)
+ verify(exactly = 0) { download(any(), any()) }
+ }
+
+ @Test
+ fun `given interrupted provider batch, completed model is installed before retry, expected retry skips it and downloads remaining model`() =
+ runTest {
+ // Given
+ coEvery { catalog(type) } returnsMany listOf(
+ listOf(first, second),
+ listOf(first.copy(downloaded = true), second)
+ )
+ every {
+ download(
+ first.id,
+ any()
+ )
+ } returns flowOf(DownloadState.Complete("/owned/first"))
+ every {
+ download(
+ second.id,
+ any()
+ )
+ } returnsMany listOf(
+ flow { throw CancellationException("cancelled") },
+ flowOf(DownloadState.Complete("/owned/second"))
+ )
+ // When
+ val interruption =
+ runCatching { useCase(ModelDownloadRequest(type)).collect() }.exceptionOrNull()
+ val resumed = useCase(ModelDownloadRequest(type)).toList()
+ // Then
+ assertTrue(interruption is CancellationException)
+ assertEquals(1, resumed.last().totalModelCount)
+ assertEquals(listOf(second.id), resumed.last().completedIds)
+ verify(exactly = 1) { download(first.id, any()) }
+ verify(exactly = 2) { download(second.id, any()) }
+ }
+
+ companion object {
+ /** Supplies each provider family to the same shared download contracts. */
+ @JvmStatic
+ @Parameterized.Parameters(name = "{0}")
+ fun providers() = LocalAiModel.Type.entries.map { arrayOf(it) }
+ }
+}
diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/di/DomainCoreModule.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/di/DomainCoreModule.kt
index 874103e4a..148b31ada 100644
--- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/di/DomainCoreModule.kt
+++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/di/DomainCoreModule.kt
@@ -117,6 +117,8 @@ import com.shifthackz.aisdv1.domain.usecase.donate.FetchSupportersUseCaseImpl
import com.shifthackz.aisdv1.domain.usecase.downloadable.DeleteModelUseCase
import com.shifthackz.aisdv1.domain.usecase.downloadable.DeleteModelUseCaseImpl
import com.shifthackz.aisdv1.domain.usecase.downloadable.DownloadModelUseCase
+import com.shifthackz.aisdv1.domain.usecase.downloadable.DownloadModelsUseCase
+import com.shifthackz.aisdv1.domain.usecase.downloadable.DownloadModelsUseCaseImpl
import com.shifthackz.aisdv1.domain.usecase.downloadable.DownloadModelUseCaseImpl
import com.shifthackz.aisdv1.domain.usecase.downloadable.GetLocalBonsaiModelsUseCase
import com.shifthackz.aisdv1.domain.usecase.downloadable.GetLocalBonsaiModelsUseCaseImpl
@@ -439,7 +441,8 @@ val coreDomainModule = module {
factory {
GetLocalModelUseCaseImpl(localDataSource = get())
}
- factory {
+ factory { DownloadModelsUseCaseImpl(get(), get()) }
+ single {
DownloadModelUseCaseImpl(downloadableModelRepository = get())
}
factory {
diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/ModelDownloadBatch.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/ModelDownloadBatch.kt
new file mode 100644
index 000000000..b32cc9f0d
--- /dev/null
+++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/ModelDownloadBatch.kt
@@ -0,0 +1,38 @@
+package com.shifthackz.aisdv1.domain.entity
+
+/**
+ * Snapshot of a sequential provider download, retained while setup is closed.
+ *
+ * @param type Provider owning the batch.
+ * @param modelId Model currently transferring or most recently completed.
+ * @param progress Current transfer result; null before the first transfer.
+ * @param completedIds Models installed successfully in this batch.
+ * @param modelName Catalog name shown in background progress notifications.
+ * @param totalModelCount Number of missing models included at batch start; each contributes equally to total progress.
+ * @param isBatch Whether this work downloads a whole provider catalog or one selected model.
+ * @param isRunning Whether the worker still owns the batch.
+ * @param workId Platform work identity distinguishing retries of the same model.
+ * @author Dmitriy Moroz
+ */
+data class ModelDownloadBatch(
+ val type: LocalAiModel.Type,
+ val modelId: String? = null,
+ val progress: DownloadState? = null,
+ val completedIds: List = emptyList(),
+ val isRunning: Boolean = true,
+ val modelName: String? = null,
+ val totalModelCount: Int = 0,
+ val isBatch: Boolean = true,
+ val workId: String = "",
+) {
+ /**
+ * Whole-batch percent; completed installs plus the active model's fraction of an equal share.
+ * @author Dmitriy Moroz
+ */
+ val totalProgress: Int
+ get() {
+ if (totalModelCount == 0) return if (isRunning) 0 else 100
+ val activePercent = (progress as? DownloadState.Downloading)?.percent ?: 0
+ return ((completedIds.size * 100 + activePercent) / totalModelCount).coerceIn(0, 100)
+ }
+}
diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/ModelDownloadRequest.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/ModelDownloadRequest.kt
new file mode 100644
index 000000000..44d19c62e
--- /dev/null
+++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/ModelDownloadRequest.kt
@@ -0,0 +1,24 @@
+package com.shifthackz.aisdv1.domain.entity
+
+/**
+ * Selects one confirmed archive or all missing models from a provider catalog.
+ * @param type Provider owning the requested model files.
+ * @param modelId Confirmed single-model identity; null downloads the provider's missing catalog models.
+ * @param sourceUrl Mirror chosen for the single model; null lets batch downloads use their first mirror.
+ * @author Dmitriy Moroz
+ */
+data class ModelDownloadRequest(
+ val type: LocalAiModel.Type,
+ val modelId: String? = null,
+ val sourceUrl: String? = null,
+) {
+ init {
+ require((modelId == null) == (sourceUrl == null)) { "A single download requires both model identity and source URL" }
+ }
+
+ /**
+ * Whether the request covers all missing catalog models rather than one confirmed archive.
+ * @author Dmitriy Moroz
+ */
+ val isBatch: Boolean get() = modelId == null
+}
diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/feature/work/ModelDownloadManager.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/feature/work/ModelDownloadManager.kt
new file mode 100644
index 000000000..235e9fd08
--- /dev/null
+++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/feature/work/ModelDownloadManager.kt
@@ -0,0 +1,38 @@
+package com.shifthackz.aisdv1.domain.feature.work
+
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadRequest
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadBatch
+import com.shifthackz.aisdv1.domain.entity.LocalAiModel
+import kotlinx.coroutines.flow.Flow
+
+/**
+ * Owns single-model or provider-wide downloads independently of the setup screen lifetime.
+ * Android persists work; iOS grants finite background execution time.
+ *
+ * @author Dmitriy Moroz
+ */
+interface ModelDownloadManager {
+ /**
+ * Live and terminal snapshots for restoring setup progress.
+ * @author Dmitriy Moroz
+ */
+ val batches: Flow>
+
+ /**
+ * Starts the confirmed single-model mirror or a provider's missing-model batch.
+ * Distinct single models may transfer concurrently; a provider-wide batch runs exclusively.
+ * Duplicate model requests are retained unless replacement was explicitly requested.
+ * @param request Provider and optional single-model mirror to download.
+ * @param shouldReplace Whether to cancel existing work before scheduling this provider.
+ * @author Dmitriy Moroz
+ */
+ suspend fun start(request: ModelDownloadRequest, shouldReplace: Boolean = false)
+
+ /**
+ * Stops matching work, preserving models that finished activation.
+ * @param type Provider to stop; null stops all model work.
+ * @param modelId Single model to stop within the provider; null stops its whole group.
+ * @author Dmitriy Moroz
+ */
+ suspend fun cancel(type: LocalAiModel.Type? = null, modelId: String? = null)
+}
diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelUseCaseImpl.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelUseCaseImpl.kt
index 8fc77e0e5..e4b90453c 100644
--- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelUseCaseImpl.kt
+++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelUseCaseImpl.kt
@@ -1,27 +1,30 @@
package com.shifthackz.aisdv1.domain.usecase.downloadable
import com.shifthackz.aisdv1.domain.repository.DownloadableModelRepository
+import kotlinx.coroutines.flow.emitAll
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
/**
- * Implements `DownloadModelUseCase` behavior in the SDAI domain layer.
- *
+ * Allows independent installs concurrently while a replacement waits for the same model's cleanup.
+ * @param downloadableModelRepository Streams archives and activates complete owned payloads.
* @author Dmitriy Moroz
*/
internal class DownloadModelUseCaseImpl(
- /**
- * Exposes the `downloadableModelRepository` value used by the SDAI domain layer.
- *
- * @author Dmitriy Moroz
- */
private val downloadableModelRepository: DownloadableModelRepository,
) : DownloadModelUseCase {
+ private val registryMutex = Mutex()
+ private val transferMutexes = mutableMapOf()
/**
- * Executes the `invoke` step in the SDAI domain layer.
- *
- * @param id identifier of the target entity.
- * @param url remote URL used by the operation.
+ * Holds exclusive ownership of this model until activation or cancellation cleanup finishes.
+ * @param id Catalog identity naming the app-owned destination.
+ * @param url Selected catalog mirror for the archive.
* @author Dmitriy Moroz
*/
- override fun invoke(id: String, url: String) = downloadableModelRepository.download(id, url)
+ override fun invoke(id: String, url: String) = flow {
+ val transferMutex = registryMutex.withLock { transferMutexes.getOrPut(id) { Mutex() } }
+ transferMutex.withLock { emitAll(downloadableModelRepository.download(id, url)) }
+ }
}
diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelsUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelsUseCase.kt
new file mode 100644
index 000000000..ff673d750
--- /dev/null
+++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelsUseCase.kt
@@ -0,0 +1,18 @@
+package com.shifthackz.aisdv1.domain.usecase.downloadable
+
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadRequest
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadBatch
+import kotlinx.coroutines.flow.Flow
+
+/**
+ * Downloads one selected archive or missing catalog models in order, stopping at the first failure.
+ * @author Dmitriy Moroz
+ */
+interface DownloadModelsUseCase {
+ /**
+ * Rechecks installed files before downloading and excludes custom entries without sources.
+ * @param request Provider and optional single-model mirror confirmed by the caller.
+ * @author Dmitriy Moroz
+ */
+ operator fun invoke(request: ModelDownloadRequest): Flow
+}
diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelsUseCaseImpl.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelsUseCaseImpl.kt
new file mode 100644
index 000000000..a80448429
--- /dev/null
+++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelsUseCaseImpl.kt
@@ -0,0 +1,59 @@
+package com.shifthackz.aisdv1.domain.usecase.downloadable
+
+import com.shifthackz.aisdv1.domain.entity.DownloadState
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadRequest
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadBatch
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.flow.distinctUntilChanged
+
+/**
+ * Applies sequential download and fail-fast policy without hiding repository failures.
+ * @param catalog Reads current file-backed completion state.
+ * @param download Streams one model through the normal archive activation path.
+ * @author Dmitriy Moroz
+ */
+internal class DownloadModelsUseCaseImpl(
+ private val catalog: GetCachedLocalModelCatalogUseCase,
+ private val download: DownloadModelUseCase,
+) : DownloadModelsUseCase {
+ /**
+ * Skips installed models, activates missing archives serially and stops at the first failure.
+ * @param request Provider-wide selection or one confirmed model mirror.
+ * @author Dmitriy Moroz
+ */
+ override fun invoke(request: ModelDownloadRequest) = flow {
+ val catalogModels = catalog(request.type)
+ require(request.modelId == null || catalogModels.any { it.id == request.modelId && it.sources.isNotEmpty() }) {
+ "The requested downloadable model is unavailable"
+ }
+ val models = catalogModels.filter {
+ !it.downloaded && it.sources.isNotEmpty() && (request.modelId == null || request.modelId == it.id)
+ }
+ var snapshot = ModelDownloadBatch(
+ request.type,
+ totalModelCount = models.size,
+ isBatch = request.isBatch
+ )
+ for (model in models) {
+ snapshot = snapshot.copy(
+ modelId = model.id,
+ modelName = model.name,
+ progress = DownloadState.Downloading()
+ )
+ emit(snapshot)
+ var hasCompleted = false
+ download(model.id, request.sourceUrl ?: model.sources.first()).distinctUntilChanged()
+ .collect { progress ->
+ if (progress is DownloadState.Error) throw progress.error
+ if (progress is DownloadState.Complete) hasCompleted = true
+ snapshot = snapshot.copy(
+ progress = progress,
+ completedIds = if (progress is DownloadState.Complete) snapshot.completedIds + model.id else snapshot.completedIds,
+ )
+ emit(snapshot)
+ }
+ check(hasCompleted) { "Model download ended without installing ${model.id}" }
+ }
+ emit(snapshot.copy(isRunning = false))
+ }
+}
diff --git a/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/ModelDownloadManagerImpl.kt b/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/ModelDownloadManagerImpl.kt
new file mode 100644
index 000000000..057a6a5f9
--- /dev/null
+++ b/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/ModelDownloadManagerImpl.kt
@@ -0,0 +1,152 @@
+package com.shifthackz.aisdv1.work
+
+import androidx.work.ExistingWorkPolicy
+import androidx.work.OneTimeWorkRequestBuilder
+import androidx.work.WorkInfo
+import androidx.work.workDataOf
+import com.shifthackz.aisdv1.domain.entity.DownloadState
+import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider
+import com.shifthackz.aisdv1.domain.entity.LocalAiModel
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadBatch
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadRequest
+import com.shifthackz.aisdv1.domain.feature.work.ModelDownloadManager
+import com.shifthackz.aisdv1.work.di.WorkManagerProvider
+import com.shifthackz.aisdv1.work.task.DownloadModelsTask
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withContext
+
+/**
+ * Persists independent single downloads or one exclusive sequential provider batch.
+ * Each model has its own unique work and notification; duplicates retain the running transfer.
+ * @param workManager Application WorkManager bridge.
+ * @param dispatchersProvider Keeps durable scheduling and cancellation waits off the main thread.
+ * @author Dmitriy Moroz
+ */
+internal class ModelDownloadManagerImpl(
+ private val workManager: WorkManagerProvider,
+ private val dispatchersProvider: DispatchersProvider,
+) :
+ ModelDownloadManager {
+ private val scheduling = Mutex()
+
+ override val batches =
+ workManager().getWorkInfosByTagFlow(DownloadModelsTask.WORK_NAME).map { infos ->
+ infos.groupBy { info ->
+ info.tags.firstOrNull { it.startsWith("download:") } ?: info.id.toString()
+ }
+ .values.mapNotNull { group ->
+ val info =
+ group.firstOrNull { !it.state.isFinished } ?: group.maxBy { candidate ->
+ candidate.tags.firstOrNull { it.startsWith("enqueued:") }
+ ?.removePrefix("enqueued:")?.toLongOrNull() ?: 0L
+ }
+ val data = if (info.state.isFinished) info.outputData else info.progress
+ val type = data.getString("type")
+ ?: info.tags.firstOrNull { it.startsWith("provider:") }
+ ?.removePrefix("provider:") ?: return@mapNotNull null
+ val modelId =
+ data.getString("model") ?: info.tags.firstOrNull { it.startsWith("model:") }
+ ?.removePrefix("model:")
+ val progress = when {
+ info.state == WorkInfo.State.CANCELLED -> DownloadState.Unknown
+ data.getString("error") != null -> DownloadState.Error(
+ IllegalStateException(
+ data.getString("error")
+ )
+ )
+
+ info.state == WorkInfo.State.FAILED -> DownloadState.Error(
+ IllegalStateException("Model download failed")
+ )
+
+ data.getString("path") != null -> DownloadState.Complete(
+ data.getString("path").orEmpty()
+ )
+
+ !info.state.isFinished && modelId != null -> DownloadState.Downloading(
+ data.getInt(
+ "percent",
+ 0
+ )
+ )
+
+ else -> null
+ }
+ ModelDownloadBatch(
+ type = LocalAiModel.Type.parse(type),
+ modelId = modelId,
+ progress = progress,
+ completedIds = data.getStringArray("completed")?.toList().orEmpty(),
+ isRunning = !info.state.isFinished,
+ modelName = data.getString("name"),
+ totalModelCount = data.getInt("total_count", 0),
+ isBatch = "mode:single" !in info.tags,
+ workId = info.id.toString(),
+ )
+ }
+ }
+
+ /**
+ * Admits distinct single models concurrently or replaces all transfers with a confirmed batch.
+ * @param request Provider and optional model mirror captured by setup.
+ * @param shouldReplace Whether to cancel previous work before admitting this request.
+ * @author Dmitriy Moroz
+ */
+ override suspend fun start(request: ModelDownloadRequest, shouldReplace: Boolean) =
+ withContext(dispatchersProvider.io) {
+ scheduling.withLock {
+ val active =
+ workManager().getWorkInfosByTagFlow(DownloadModelsTask.WORK_NAME).first()
+ .filterNot { it.state.isFinished }
+ if (shouldReplace) {
+ workManager().cancelAllWorkByTag(DownloadModelsTask.WORK_NAME).result.get()
+ } else if (active.any { "mode:single" !in it.tags } || (request.isBatch && active.isNotEmpty())) {
+ return@withLock
+ }
+ val name =
+ "${DownloadModelsTask.WORK_NAME}:${request.type.key}:${request.modelId ?: "all"}"
+ workManager().enqueueUniqueWork(
+ name,
+ if (shouldReplace) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.KEEP,
+ OneTimeWorkRequestBuilder()
+ .addTag(DownloadModelsTask.WORK_NAME).addTag("download:$name")
+ .addTag("enqueued:${System.currentTimeMillis()}")
+ .addTag("provider:${request.type.key}")
+ .addTag(if (request.isBatch) "mode:all" else "mode:single")
+ .apply { request.modelId?.let { addTag("model:$it") } }
+ .setInputData(
+ workDataOf(
+ "type" to request.type.key,
+ "model" to request.modelId,
+ "url" to request.sourceUrl
+ )
+ )
+ .build()
+ ).result.get()
+ Unit
+ }
+ }
+
+ /**
+ * Cancels only matching requests; other concurrent model workers keep their progress.
+ * @param type Provider to cancel, or null to stop every model request.
+ * @param modelId Single model within that provider, or null for all its requests.
+ * @author Dmitriy Moroz
+ */
+ override suspend fun cancel(type: LocalAiModel.Type?, modelId: String?) =
+ withContext(dispatchersProvider.io) {
+ scheduling.withLock {
+ require(modelId == null || type != null)
+ if (modelId != null) {
+ workManager().cancelUniqueWork("${DownloadModelsTask.WORK_NAME}:${type?.key}:$modelId").result.get()
+ } else {
+ workManager().cancelAllWorkByTag(type?.let { "provider:${it.key}" }
+ ?: DownloadModelsTask.WORK_NAME).result.get()
+ }
+ Unit
+ }
+ }
+}
diff --git a/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/core/CoreGenerationWorker.kt b/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/core/CoreGenerationWorker.kt
index f17bb2337..9b8056274 100644
--- a/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/core/CoreGenerationWorker.kt
+++ b/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/core/CoreGenerationWorker.kt
@@ -97,7 +97,6 @@ internal abstract class CoreGenerationWorker(
*
* @author Dmitriy Moroz
*/
-
protected fun clearSubscriptions() {
coroutineScope.coroutineContext.cancelChildren()
}
@@ -152,7 +151,6 @@ internal abstract class CoreGenerationWorker(
*
* @author Dmitriy Moroz
*/
-
private fun listenNativeStatus(engine: NativeGenerationEngine) {
coroutineScope.launch {
combine(
@@ -190,7 +188,6 @@ internal abstract class CoreGenerationWorker(
*
* @author Dmitriy Moroz
*/
-
private fun stageText(stage: NativeGenerationStage): String = applicationContext.getString(
when (stage) {
NativeGenerationStage.PREPARING -> LocalizationR.string.native_generation_stage_preparing
@@ -207,7 +204,6 @@ internal abstract class CoreGenerationWorker(
*
* @author Dmitriy Moroz
*/
-
protected fun listenHordeStatus() {
coroutineScope.launch {
observeHordeProcessStatusUseCase()
@@ -250,7 +246,6 @@ internal abstract class CoreGenerationWorker(
*
* @author Dmitriy Moroz
*/
-
protected fun handleStart() {
if (!backgroundWorkObserver.publishForOwner(id.toString()) {}) return
val title = applicationContext.getString(LocalizationR.string.notification_started_title)
@@ -296,7 +291,6 @@ internal abstract class CoreGenerationWorker(
*
* @author Dmitriy Moroz
*/
-
protected fun handleSuccess(result: List) {
if (!backgroundWorkObserver.publishForOwner(id.toString()) {}) return
backgroundWorkObserver.refreshStatus()
@@ -318,7 +312,6 @@ internal abstract class CoreGenerationWorker(
*
* @author Dmitriy Moroz
*/
-
protected fun handleError(t: Throwable) {
if (!backgroundWorkObserver.publishForOwner(id.toString()) {}) return
backgroundWorkObserver.publishForOwner(id.toString()) {
diff --git a/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/core/NotificationWorker.kt b/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/core/NotificationWorker.kt
index 6344629f5..6e03585ad 100644
--- a/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/core/NotificationWorker.kt
+++ b/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/core/NotificationWorker.kt
@@ -1,5 +1,6 @@
package com.shifthackz.aisdv1.work.core
+import android.R
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
@@ -13,48 +14,44 @@ import androidx.work.WorkerParameters
import com.shifthackz.aisdv1.core.common.appbuild.ActivityIntentProvider
import com.shifthackz.aisdv1.core.common.extensions.isAppInForeground
import com.shifthackz.aisdv1.core.notification.PushNotificationManager
+import com.shifthackz.aisdv1.core.localization.Localization
/**
- * Coordinates `NotificationWorker` behavior in the SDAI background work feature layer.
+ * Shares app navigation and foreground notification appearance across long-running workers.
+ *
+ * @param context Application context supplied by WorkManager.
+ * @param workerParameters Persisted request input and cancellation lifetime.
+ * @param pushNotificationManager Creates notifications using the application channel and branding.
+ * @param activityIntentProvider Opens the application when the notification is tapped.
*
* @author Dmitriy Moroz
*/
internal abstract class NotificationWorker(
context: Context,
workerParameters: WorkerParameters,
- /**
- * Exposes the `pushNotificationManager` value used by the SDAI background work feature layer.
- *
- * @author Dmitriy Moroz
- */
private val pushNotificationManager: PushNotificationManager,
- /**
- * Exposes the `activityIntentProvider` value used by the SDAI background work feature layer.
- *
- * @author Dmitriy Moroz
- */
private val activityIntentProvider: ActivityIntentProvider,
) : CoroutineWorker(context, workerParameters) {
/**
- * Exposes the `notificationId` value used by the SDAI background work feature layer.
+ * Stable notification identity used while this worker runs in the foreground.
*
* @author Dmitriy Moroz
*/
abstract val notificationId: Int
/**
- * Exposes the `genericNotificationId` value used by the SDAI background work feature layer.
+ * Separate notification identity for dismissible completion or failure messages.
*
* @author Dmitriy Moroz
*/
abstract val genericNotificationId: Int
/**
- * Executes the `showGenericNotification` step in the SDAI background work feature layer.
+ * Posts a dismissible result message whose tap opens the application.
*
- * @param text text value consumed by the API.
- * @param body body value consumed by the API.
+ * @param text Localized notification title.
+ * @param body Optional detail shown below the title.
* @author Dmitriy Moroz
*/
fun showGenericNotification(text: String, body: String?) {
@@ -79,14 +76,16 @@ internal abstract class NotificationWorker(
}
/**
- * Executes the `setForegroundNotification` step in the SDAI background work feature layer.
+ * Updates the ongoing foreground notification and its optional worker cancellation action.
+ *
+ * @param title Localized operation title.
+ * @param body Current operation detail, such as a model name.
+ * @param subText Optional compact status rendered by the system.
+ * @param progress Completed units and total units; null displays an indeterminate bar.
+ * @param silent Whether progress updates suppress sound and vibration.
+ * @param canCancel Whether to expose cancellation for this WorkManager request.
+ * @param cancelText Localized label describing what the cancellation action stops.
*
- * @param title title value consumed by the API.
- * @param body body value consumed by the API.
- * @param subText sub text value consumed by the API.
- * @param progress progress value consumed by the API.
- * @param silent silent value consumed by the API.
- * @param canCancel can cancel value consumed by the API.
* @author Dmitriy Moroz
*/
fun setForegroundNotification(
@@ -96,6 +95,7 @@ internal abstract class NotificationWorker(
progress: Pair? = null,
silent: Boolean = false,
canCancel: Boolean = false,
+ cancelText: String = Localization.string("cancel"),
) {
pushNotificationManager.createNotificationChannel()
val notification = pushNotificationManager.createProgressNotification(title, body) {
@@ -114,7 +114,7 @@ internal abstract class NotificationWorker(
val intent = WorkManager
.getInstance(applicationContext)
.createCancelPendingIntent(id)
- addAction(android.R.drawable.ic_delete, "Cancel", intent)
+ addAction(R.drawable.ic_menu_close_clear_cancel, cancelText, intent)
}
setAutoCancel(false)
diff --git a/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/di/BackgroundWorkModule.kt b/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/di/BackgroundWorkModule.kt
index cb600aed1..1f17ac31e 100644
--- a/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/di/BackgroundWorkModule.kt
+++ b/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/di/BackgroundWorkModule.kt
@@ -19,13 +19,16 @@ import org.koin.core.module.dsl.singleOf
import org.koin.dsl.bind
import org.koin.dsl.binds
import org.koin.dsl.module
+import com.shifthackz.aisdv1.domain.feature.work.ModelDownloadManager
+import com.shifthackz.aisdv1.work.ModelDownloadManagerImpl
/**
- * Exposes the `backgroundWorkModule` value used by the SDAI background work feature layer.
+ * Binds platform task scheduling, progress observation and model download ownership.
*
* @author Dmitriy Moroz
*/
actual val backgroundWorkModule = module {
+ singleOf(::ModelDownloadManagerImpl) bind ModelDownloadManager::class
factory {
WorkManagerProvider { WorkManager.getInstance(androidApplication()) }
}
diff --git a/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/di/SdaiWorkerFactory.kt b/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/di/SdaiWorkerFactory.kt
index 312a58e36..c1f12b1ad 100644
--- a/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/di/SdaiWorkerFactory.kt
+++ b/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/di/SdaiWorkerFactory.kt
@@ -3,6 +3,8 @@ package com.shifthackz.aisdv1.work.di
import com.shifthackz.aisdv1.domain.usecase.easydiffusion.ObserveEasyDiffusionProgressUseCase
import android.content.Context
+import com.shifthackz.aisdv1.domain.usecase.downloadable.DownloadModelsUseCase
+import com.shifthackz.aisdv1.work.task.DownloadModelsTask
import com.shifthackz.aisdv1.work.GenerationWorkPayloadCleanup
import com.shifthackz.aisdv1.work.GenerationWorkPayloadStore
import com.shifthackz.aisdv1.domain.gateway.NativeGenerationGateway
@@ -38,6 +40,7 @@ import com.shifthackz.aisdv1.work.task.TextToImageTask
* @param activityIntentProvider Creates app navigation intents for notifications.
* @param payloads Reads immutable work files.
* @param nativeGateway Shared child-process status and cancellation gateway.
+ * @param downloadModels Sequential model download policy for foreground work.
* @param payloadCleanup Cleans terminal request files and retains retry input.
* @author Dmitriy Moroz
*/
@@ -54,6 +57,7 @@ class SdaiWorkerFactory(
private val payloads: GenerationWorkPayloadStore,
private val nativeGateway: NativeGenerationGateway,
private val payloadCleanup: GenerationWorkPayloadCleanup,
+ private val downloadModels: DownloadModelsUseCase,
) : WorkerFactory() {
/**
@@ -70,6 +74,14 @@ class SdaiWorkerFactory(
workerParameters: WorkerParameters
): ListenableWorker? {
return when (workerClassName) {
+ DownloadModelsTask::class.java.name -> DownloadModelsTask(
+ appContext,
+ workerParameters,
+ pushNotificationManager,
+ activityIntentProvider,
+ downloadModels
+ )
+
TextToImageTask::class.java.name -> TextToImageTask(
context = appContext,
payloads = payloads,
diff --git a/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/task/DownloadModelsTask.kt b/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/task/DownloadModelsTask.kt
new file mode 100644
index 000000000..0ca152109
--- /dev/null
+++ b/feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/task/DownloadModelsTask.kt
@@ -0,0 +1,91 @@
+package com.shifthackz.aisdv1.work.task
+
+import android.content.Context
+import androidx.work.WorkerParameters
+import androidx.work.workDataOf
+import com.shifthackz.aisdv1.core.common.appbuild.ActivityIntentProvider
+import com.shifthackz.aisdv1.core.localization.Localization
+import com.shifthackz.aisdv1.core.notification.PushNotificationManager
+import com.shifthackz.aisdv1.domain.entity.DownloadState
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadRequest
+import com.shifthackz.aisdv1.domain.entity.LocalAiModel
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadBatch
+import com.shifthackz.aisdv1.domain.usecase.downloadable.DownloadModelsUseCase
+import com.shifthackz.aisdv1.work.core.NotificationWorker
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.currentCoroutineContext
+import kotlinx.coroutines.ensureActive
+
+/**
+ * Runs catalog downloads serially as long-running foreground work with durable UI progress.
+ * @param context Application context owned by WorkManager.
+ * @param parameters Persisted provider identity and worker lifetime.
+ * @param notifications Existing app notification channel and appearance.
+ * @param activityIntentProvider Opens the app from the notification.
+ * @param downloadModels Sequential domain download policy.
+ * @author Dmitriy Moroz
+ */
+internal class DownloadModelsTask(
+ context: Context,
+ parameters: WorkerParameters,
+ notifications: PushNotificationManager,
+ activityIntentProvider: ActivityIntentProvider,
+ private val downloadModels: DownloadModelsUseCase,
+) : NotificationWorker(context, parameters, notifications, activityIntentProvider) {
+ override val notificationId = 0x10000000 or (id.hashCode() and 0x0fffffff)
+ override val genericNotificationId = 0x20000000 or (id.hashCode() and 0x0fffffff)
+
+ /**
+ * Downloads the captured selection and posts the generation-style result notification.
+ * Cancellation propagates without publishing a success or failure notification.
+ * @author Dmitriy Moroz
+ */
+ override suspend fun doWork(): Result {
+ val type = LocalAiModel.Type.parse(inputData.getString("type"))
+ val request =
+ ModelDownloadRequest(type, inputData.getString("model"), inputData.getString("url"))
+ var latest = ModelDownloadBatch(type, modelId = request.modelId, isBatch = request.isBatch)
+ try {
+ downloadModels(request).collect { snapshot ->
+ latest = snapshot
+ setProgress(snapshot.toData())
+ setForegroundNotification(
+ title = Localization.string(if (request.isBatch) "download_all" else "download"),
+ body = snapshot.modelName.orEmpty(),
+ progress = snapshot.totalProgress to 100,
+ silent = true,
+ canCancel = true,
+ cancelText = Localization.string(if (request.isBatch) "download_cancel_all" else "cancel"),
+ )
+ }
+ } catch (cancelled: CancellationException) {
+ throw cancelled
+ } catch (failure: Exception) {
+ latest = latest.copy(progress = DownloadState.Error(failure), isRunning = false)
+ }
+ currentCoroutineContext().ensureActive()
+ if (isStopped) throw CancellationException("Model download was stopped")
+ val hasFailed = latest.progress is DownloadState.Error
+ showGenericNotification(
+ Localization.string(if (hasFailed) "notification_download_fail_title" else "notification_download_finish_title"),
+ Localization.string("notification_fail_sub_title"),
+ )
+ return if (hasFailed) Result.failure(latest.toData()) else Result.success(latest.toData())
+ }
+
+ private fun ModelDownloadBatch.toData() = workDataOf(
+ "type" to type.key,
+ "model" to modelId,
+ "name" to modelName,
+ "total_count" to totalModelCount,
+ "percent" to ((progress as? DownloadState.Downloading)?.percent ?: 0),
+ "path" to (progress as? DownloadState.Complete)?.filePath,
+ "error" to (progress as? DownloadState.Error)?.error?.let { it.message ?: it.toString() }
+ ?.take(1000),
+ "completed" to completedIds.toTypedArray(),
+ )
+
+ companion object {
+ const val WORK_NAME = "download_all_models"
+ }
+}
diff --git a/feature/work/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/work/ModelDownloadManagerImplTest.kt b/feature/work/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/work/ModelDownloadManagerImplTest.kt
new file mode 100644
index 000000000..a2843df51
--- /dev/null
+++ b/feature/work/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/work/ModelDownloadManagerImplTest.kt
@@ -0,0 +1,359 @@
+package com.shifthackz.aisdv1.work
+
+import androidx.work.ExistingWorkPolicy
+import androidx.work.OneTimeWorkRequest
+import androidx.work.Operation
+import androidx.work.WorkInfo
+import androidx.work.WorkManager
+import androidx.work.workDataOf
+import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider
+import com.shifthackz.aisdv1.domain.entity.DownloadState
+import com.shifthackz.aisdv1.domain.entity.LocalAiModel
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadRequest
+import com.shifthackz.aisdv1.work.di.WorkManagerProvider
+import com.shifthackz.aisdv1.work.task.DownloadModelsTask
+import io.mockk.every
+import io.mockk.mockk
+import io.mockk.slot
+import io.mockk.verify
+import io.mockk.verifyOrder
+import java.util.UUID
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.test.StandardTestDispatcher
+import kotlinx.coroutines.test.runTest
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Verifies durable admission, targeted cancellation and progress reconstruction at the WorkManager boundary.
+ * @author Dmitriy Moroz
+ */
+@OptIn(ExperimentalCoroutinesApi::class)
+class ModelDownloadManagerImplTest {
+ private val workManager = mockk()
+ private val infos = MutableStateFlow>(emptyList())
+ private val operation = mockk(relaxed = true) {
+ every { result.get() } returns Operation.SUCCESS
+ }
+
+ @Test
+ fun `given single model admission, another single is active, expected unique concurrent work with confirmed input`() =
+ runTest {
+ // Given
+ infos.value = listOf(info(WorkInfo.State.RUNNING, "first"))
+ val request =
+ ModelDownloadRequest(LocalAiModel.Type.ONNX, "second", "https://models/second")
+ val queued = slot()
+ every { workManager.enqueueUniqueWork(any(), any(), capture(queued)) } returns operation
+ val manager = manager(StandardTestDispatcher(testScheduler))
+ // When
+ manager.start(request)
+ // Then
+ verify {
+ workManager.enqueueUniqueWork(
+ "download_all_models:onnx:second",
+ ExistingWorkPolicy.KEEP,
+ any()
+ )
+ }
+ assertEquals("second", queued.captured.workSpec.input.getString("model"))
+ assertEquals(request.sourceUrl, queued.captured.workSpec.input.getString("url"))
+ assertTrue("mode:single" in queued.captured.tags)
+ verify(exactly = 0) { workManager.cancelAllWorkByTag(any()) }
+ }
+
+ @Test
+ fun `given provider batch admission, a single model is active, expected existing work retained until confirmed switch`() =
+ runTest {
+ // Given
+ infos.value = listOf(info(WorkInfo.State.RUNNING, "first"))
+ val manager = manager(StandardTestDispatcher(testScheduler))
+ // When
+ manager.start(ModelDownloadRequest(LocalAiModel.Type.MediaPipe))
+ // Then
+ verify(exactly = 0) {
+ workManager.enqueueUniqueWork(
+ any(),
+ any(),
+ any()
+ )
+ }
+ verify(exactly = 0) { workManager.cancelAllWorkByTag(any()) }
+ }
+
+ @Test
+ fun `given exclusive provider batch, a single model is requested, expected no additional worker`() =
+ runTest {
+ // Given
+ infos.value = listOf(info(WorkInfo.State.RUNNING))
+ val manager = manager(StandardTestDispatcher(testScheduler))
+ // When
+ manager.start(
+ ModelDownloadRequest(
+ LocalAiModel.Type.ONNX,
+ "first",
+ "https://models/first"
+ )
+ )
+ // Then
+ verify(exactly = 0) {
+ workManager.enqueueUniqueWork(
+ any(),
+ any(),
+ any()
+ )
+ }
+ }
+
+ @Test
+ fun `given provider switch, replacement is confirmed, expected old work cancelled before new batch enqueued`() =
+ runTest {
+ // Given
+ infos.value = listOf(info(WorkInfo.State.RUNNING, "first"))
+ every { workManager.cancelAllWorkByTag(any()) } returns operation
+ every {
+ workManager.enqueueUniqueWork(
+ any(),
+ any(),
+ any()
+ )
+ } returns operation
+ val manager = manager(StandardTestDispatcher(testScheduler))
+ // When
+ manager.start(ModelDownloadRequest(LocalAiModel.Type.MediaPipe), shouldReplace = true)
+ // Then
+ verifyOrder {
+ workManager.cancelAllWorkByTag(DownloadModelsTask.WORK_NAME)
+ workManager.enqueueUniqueWork(
+ "download_all_models:mediapipe:all",
+ ExistingWorkPolicy.REPLACE,
+ any()
+ )
+ }
+ }
+
+ @Test
+ fun `given single model cancellation, other transfers exist, expected only selected unique request cancelled`() =
+ runTest {
+ // Given
+ every { workManager.cancelUniqueWork(any()) } returns operation
+ val manager = manager(StandardTestDispatcher(testScheduler))
+ // When
+ manager.cancel(LocalAiModel.Type.ONNX, "first")
+ // Then
+ verify(exactly = 1) { workManager.cancelUniqueWork("download_all_models:onnx:first") }
+ verify(exactly = 0) { workManager.cancelAllWorkByTag(any()) }
+ }
+
+ @Test
+ fun `given all model cancellation, no provider is selected, expected every model worker cancelled by shared tag`() =
+ runTest {
+ // Given
+ every { workManager.cancelAllWorkByTag(any()) } returns operation
+ val manager = manager(StandardTestDispatcher(testScheduler))
+ // When
+ manager.cancel()
+ // Then
+ verify(exactly = 1) { workManager.cancelAllWorkByTag(DownloadModelsTask.WORK_NAME) }
+ }
+
+ @Test
+ fun `given persisted work, active request follows newer terminal timestamp, expected running progress restored`() =
+ runTest {
+ // Given
+ val running = info(WorkInfo.State.RUNNING, "first", timestamp = 1)
+ val finished = info(WorkInfo.State.SUCCEEDED, "first", timestamp = 2)
+ infos.value = listOf(finished, running)
+ val manager = manager(StandardTestDispatcher(testScheduler))
+ // When
+ val snapshot = manager.batches.first().single()
+ // Then
+ assertTrue(snapshot.isRunning)
+ assertEquals(running.id.toString(), snapshot.workId)
+ assertEquals(DownloadState.Downloading(42), snapshot.progress)
+ assertFalse(snapshot.isBatch)
+ }
+
+ @Test
+ fun `given cancelled persisted work, output has no progress, expected cancelled state restored without error`() =
+ runTest {
+ // Given
+ infos.value = listOf(info(WorkInfo.State.CANCELLED, "first"))
+ val manager = manager(StandardTestDispatcher(testScheduler))
+ // When
+ val snapshot = manager.batches.first().single()
+ // Then
+ assertFalse(snapshot.isRunning)
+ assertEquals(DownloadState.Unknown, snapshot.progress)
+ assertEquals("first", snapshot.modelId)
+ }
+
+ @Test
+ fun `given failed persisted work, error output exists, expected failure restored without successful fallback`() =
+ runTest {
+ // Given
+ infos.value = listOf(info(WorkInfo.State.FAILED, "first"))
+ val manager = manager(StandardTestDispatcher(testScheduler))
+ // When
+ val snapshot = manager.batches.first().single()
+ // Then
+ assertFalse(snapshot.isRunning)
+ assertEquals("offline", (snapshot.progress as DownloadState.Error).error.message)
+ }
+
+ @Test
+ fun `given finished worker history, newer archive activation follows an old failure, expected latest successful ownership restored`() =
+ runTest {
+ // Given
+ val old = info(WorkInfo.State.FAILED, "first", timestamp = 1)
+ val latest = info(WorkInfo.State.SUCCEEDED, "first", timestamp = 2)
+ every { latest.outputData } returns workDataOf(
+ "type" to "onnx",
+ "model" to "first",
+ "path" to "/owned/first",
+ "completed" to arrayOf("first"),
+ "total_count" to 1
+ )
+ infos.value = listOf(old, latest)
+ val manager = manager(StandardTestDispatcher(testScheduler))
+ // When
+ val result = manager.batches.first().single()
+ // Then
+ assertEquals(latest.id.toString(), result.workId)
+ assertEquals(DownloadState.Complete("/owned/first"), result.progress)
+ assertEquals(listOf("first"), result.completedIds)
+ assertFalse(result.isRunning)
+ }
+
+ @Test
+ fun `given failed worker without error payload, scheduler reports failure, expected explicit failure rather than success`() =
+ runTest {
+ // Given
+ val failed = info(WorkInfo.State.FAILED, "first")
+ every { failed.outputData } returns workDataOf()
+ infos.value = listOf(failed)
+ val manager = manager(StandardTestDispatcher(testScheduler))
+ // When
+ val result = manager.batches.first().single()
+ // Then
+ assertEquals(
+ "Model download failed",
+ (result.progress as DownloadState.Error).error.message
+ )
+ }
+
+ @Test
+ fun `given newly queued provider batch, no active model is known, expected running batch with pending progress`() =
+ runTest {
+ // Given
+ infos.value = listOf(info(WorkInfo.State.ENQUEUED))
+ val manager = manager(StandardTestDispatcher(testScheduler))
+ // When
+ val result = manager.batches.first().single()
+ // Then
+ assertTrue(result.isRunning && result.isBatch)
+ assertEquals(null, result.modelId)
+ assertEquals(null, result.progress)
+ }
+
+ @Test
+ fun `given persisted record without provider metadata, work is observed, expected malformed record omitted`() =
+ runTest {
+ // Given
+ val malformed = info(WorkInfo.State.ENQUEUED)
+ every { malformed.tags } returns setOf(DownloadModelsTask.WORK_NAME)
+ infos.value = listOf(malformed)
+ val manager = manager(StandardTestDispatcher(testScheduler))
+ // When
+ val result = manager.batches.first()
+ // Then
+ assertTrue(result.isEmpty())
+ }
+
+ @Test
+ fun `given idle provider batch request, no workers exist, expected unique batch enqueued with keep policy`() =
+ runTest {
+ // Given
+ every {
+ workManager.enqueueUniqueWork(
+ any(),
+ any(),
+ any()
+ )
+ } returns operation
+ val manager = manager(StandardTestDispatcher(testScheduler))
+ // When
+ manager.start(ModelDownloadRequest(LocalAiModel.Type.ONNX))
+ // Then
+ verify(exactly = 1) {
+ workManager.enqueueUniqueWork(
+ "download_all_models:onnx:all",
+ ExistingWorkPolicy.KEEP,
+ any()
+ )
+ }
+ }
+
+ @Test
+ fun `given provider cancellation, other providers may be active, expected only requested provider tag cancelled`() =
+ runTest {
+ // Given
+ every { workManager.cancelAllWorkByTag(any()) } returns operation
+ val manager = manager(StandardTestDispatcher(testScheduler))
+ // When
+ manager.cancel(LocalAiModel.Type.ONNX)
+ // Then
+ verify(exactly = 1) { workManager.cancelAllWorkByTag("provider:onnx") }
+ verify(exactly = 0) { workManager.cancelUniqueWork(any()) }
+ }
+
+ @Test
+ fun `given single model cancellation, owning provider is absent, expected ambiguous cancellation rejected`() =
+ runTest {
+ // Given
+ val manager = manager(StandardTestDispatcher(testScheduler))
+ // When
+ val failure = runCatching { manager.cancel(null, "first") }.exceptionOrNull()
+ // Then
+ assertTrue(failure is IllegalArgumentException)
+ verify(exactly = 0) { workManager.cancelAllWorkByTag(any()) }
+ verify(exactly = 0) { workManager.cancelUniqueWork(any()) }
+ }
+
+ /**
+ * Binds scheduling to virtual time while retaining production request construction and admission policy.
+ * @param dispatcher Scheduler shared with the owning coroutine test.
+ * @author Dmitriy Moroz
+ */
+ private fun manager(dispatcher: CoroutineDispatcher): ModelDownloadManagerImpl {
+ every { workManager.getWorkInfosByTagFlow(DownloadModelsTask.WORK_NAME) } returns infos
+ val dispatchers = mockk { every { io } returns dispatcher }
+ return ModelDownloadManagerImpl(WorkManagerProvider { workManager }, dispatchers)
+ }
+
+ /**
+ * Supplies a persisted WorkInfo record with real worker tags and independent progress/output data.
+ * @param state Persisted scheduler lifecycle.
+ * @param model Single-model identity, or null for an exclusive provider batch.
+ * @param timestamp Enqueue ordering used to choose terminal history.
+ * @author Dmitriy Moroz
+ */
+ private fun info(state: WorkInfo.State, model: String? = null, timestamp: Long = 1): WorkInfo =
+ mockk {
+ every { id } returns UUID.randomUUID()
+ every { this@mockk.state } returns state
+ every { tags } returns buildSet {
+ add("provider:onnx"); add("download:onnx:${model ?: "all"}"); add("enqueued:$timestamp")
+ if (model != null) {
+ add("mode:single"); add("model:$model")
+ }
+ }
+ every { progress } returns workDataOf("percent" to 42, "total_count" to 1)
+ every { outputData } returns workDataOf("error" to "offline")
+ }
+}
diff --git a/feature/work/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/work/core/ModelDownloadNotificationTest.kt b/feature/work/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/work/core/ModelDownloadNotificationTest.kt
new file mode 100644
index 000000000..4f6e0d528
--- /dev/null
+++ b/feature/work/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/work/core/ModelDownloadNotificationTest.kt
@@ -0,0 +1,157 @@
+package com.shifthackz.aisdv1.work.core
+
+import android.R as AndroidR
+import android.app.Activity
+import android.app.Notification
+import android.app.PendingIntent
+import android.content.Intent
+import androidx.core.app.NotificationCompat
+import androidx.work.ForegroundInfo
+import androidx.work.WorkManager
+import androidx.work.WorkerParameters
+import com.shifthackz.aisdv1.core.common.appbuild.ActivityIntentProvider
+import com.shifthackz.aisdv1.core.notification.PushNotificationManager
+import com.shifthackz.aisdv1.work.task.DownloadModelsTask
+import io.mockk.Runs
+import io.mockk.every
+import io.mockk.just
+import io.mockk.mockk
+import io.mockk.mockkObject
+import io.mockk.slot
+import io.mockk.spyk
+import io.mockk.unmockkObject
+import io.mockk.verify
+import java.util.UUID
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertSame
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+import org.robolectric.annotation.Config
+
+/**
+ * Inspects real Android notification objects built by the helper shared with generation workers.
+ * @author Dmitriy Moroz
+ */
+@RunWith(RobolectricTestRunner::class)
+@Config(manifest = Config.NONE, sdk = [28])
+class ModelDownloadNotificationTest {
+ private val context get() = RuntimeEnvironment.getApplication()
+ private val notifications = mockk(relaxed = true)
+ private val foreground = slot()
+ private val workManager = mockk()
+ private val ownerId = UUID.randomUUID()
+ private lateinit var worker: DownloadModelsTask
+
+ @Before
+ fun initialize() {
+ mockkObject(WorkManager.Companion)
+ every { WorkManager.getInstance(any()) } returns workManager
+ every { notifications.createProgressNotification(any(), any(), any()) } answers {
+ buildNotification(firstArg(), secondArg(), thirdArg())
+ }
+ every { notifications.createNotification(any(), any(), any()) } answers {
+ buildNotification(firstArg(), secondArg(), thirdArg())
+ }
+ val parameters = mockk(relaxed = true) { every { id } returns ownerId }
+ worker = spyk(
+ DownloadModelsTask(
+ context,
+ parameters,
+ notifications,
+ ActivityIntentProvider { Intent(context, Activity::class.java) },
+ mockk()
+ )
+ )
+ every { worker.setForegroundAsync(capture(foreground)) } returns mockk()
+ every { notifications.show(any(), any()) } just Runs
+ }
+
+ @After
+ fun releaseWorkManager() {
+ unmockkObject(WorkManager.Companion)
+ }
+
+ @Test
+ fun `given batch progress notification, cancellation is enabled, expected aggregate bar and exact worker cancel action`() {
+ // Given
+ val cancel = PendingIntent.getBroadcast(
+ context,
+ 1,
+ Intent("cancel-download"),
+ PendingIntent.FLAG_IMMUTABLE
+ )
+ every { workManager.createCancelPendingIntent(ownerId) } returns cancel
+ // When
+ worker.setForegroundNotification(
+ "Download all",
+ "Second model",
+ progress = 37 to 100,
+ canCancel = true,
+ cancelText = "Cancel all downloads"
+ )
+ // Then
+ val notification = foreground.captured.notification
+ assertEquals(37, notification.extras.getInt(Notification.EXTRA_PROGRESS))
+ assertEquals(100, notification.extras.getInt(Notification.EXTRA_PROGRESS_MAX))
+ assertFalse(notification.extras.getBoolean(Notification.EXTRA_PROGRESS_INDETERMINATE))
+ assertEquals("Cancel all downloads", notification.actions.single().title.toString())
+ assertSame(cancel, notification.actions.single().actionIntent)
+ assertTrue(notification.flags and Notification.FLAG_ONGOING_EVENT != 0)
+ verify(exactly = 1) { workManager.createCancelPendingIntent(ownerId) }
+ }
+
+ @Test
+ fun `given progress notification, cancellation is disabled, expected indeterminate bar without action`() {
+ // Given
+ val title = "Download"
+ // When
+ worker.setForegroundNotification(title, "Preparing")
+ // Then
+ val notification = foreground.captured.notification
+ assertTrue(notification.extras.getBoolean(Notification.EXTRA_PROGRESS_INDETERMINATE))
+ assertTrue(notification.actions.isNullOrEmpty())
+ verify(exactly = 0) { workManager.createCancelPendingIntent(any()) }
+ }
+
+ @Test
+ fun `given terminal download notification, result is published, expected dismissible app navigation matching generation helper`() {
+ // Given
+ val result = slot()
+ val resultId = worker.genericNotificationId
+ every { notifications.show(resultId, capture(result)) } just Runs
+ // When
+ worker.showGenericNotification("Download complete 🤩", "Click here to open the application.")
+ // Then
+ assertEquals(
+ "Download complete 🤩",
+ result.captured.extras.getString(Notification.EXTRA_TITLE)
+ )
+ assertNotNull(result.captured.contentIntent)
+ assertTrue(result.captured.flags and Notification.FLAG_AUTO_CANCEL != 0)
+ assertFalse(result.captured.flags and Notification.FLAG_ONGOING_EVENT != 0)
+ assertTrue(result.captured.actions.isNullOrEmpty())
+ }
+
+ /**
+ * Applies the production customization block to an actual platform-compatible notification builder.
+ * @param title Notification title supplied by the worker.
+ * @param body Notification detail supplied by the worker.
+ * @param block Production helper's appearance, navigation and cancellation customization.
+ * @author Dmitriy Moroz
+ */
+ private fun buildNotification(
+ title: String,
+ body: String?,
+ block: NotificationCompat.Builder.() -> Unit
+ ): Notification =
+ NotificationCompat.Builder(context, "downloads")
+ .setSmallIcon(AndroidR.drawable.ic_menu_save)
+ .setContentTitle(title).setContentText(body).apply(block).build()
+}
diff --git a/feature/work/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/work/task/DownloadModelsTaskTest.kt b/feature/work/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/work/task/DownloadModelsTaskTest.kt
new file mode 100644
index 000000000..01dc56881
--- /dev/null
+++ b/feature/work/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/work/task/DownloadModelsTaskTest.kt
@@ -0,0 +1,237 @@
+package com.shifthackz.aisdv1.work.task
+
+import androidx.work.ListenableWorker.Result
+import androidx.work.WorkerParameters
+import androidx.work.workDataOf
+import com.shifthackz.aisdv1.domain.entity.DownloadState
+import com.shifthackz.aisdv1.domain.entity.LocalAiModel
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadBatch
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadRequest
+import com.shifthackz.aisdv1.domain.usecase.downloadable.DownloadModelsUseCase
+import io.mockk.Runs
+import io.mockk.coEvery
+import io.mockk.every
+import io.mockk.just
+import io.mockk.mockk
+import io.mockk.spyk
+import io.mockk.verify
+import java.util.UUID
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.test.runTest
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotEquals
+import org.junit.Assert.assertSame
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+import org.robolectric.annotation.Config
+
+/**
+ * Exercises production worker inputs, progress and terminal decisions with notification delivery isolated.
+ * Android notification appearance is verified separately through the real application.
+ * @author Dmitriy Moroz
+ */
+@RunWith(RobolectricTestRunner::class)
+@Config(manifest = Config.NONE, sdk = [28])
+class DownloadModelsTaskTest {
+ private val download = mockk()
+ private val type = LocalAiModel.Type.ONNX
+
+ @Test
+ fun `given single model worker, selected archive activates, expected captured mirror and completion notification`() =
+ runTest {
+ // Given
+ val request = ModelDownloadRequest(type, "model", "https://models/selected")
+ every { download(request) } returns flowOf(
+ ModelDownloadBatch(
+ type,
+ "model",
+ DownloadState.Complete("/owned/model"),
+ listOf("model"),
+ false,
+ "Model",
+ 1,
+ false
+ )
+ )
+ val worker = worker(request)
+ // When
+ val result = worker.doWork()
+ // Then
+ assertTrue(result is Result.Success)
+ verify(exactly = 1) { download(request) }
+ verify(exactly = 1) {
+ worker.showGenericNotification(
+ "Download complete 🤩",
+ "Click here to open the application."
+ )
+ }
+ assertEquals("/owned/model", (result as Result.Success).outputData.getString("path"))
+ assertEquals(listOf("model"), result.outputData.getStringArray("completed")?.toList())
+ }
+
+ @Test
+ fun `given provider batch worker, second model is half downloaded, expected total progress and cancel all label`() =
+ runTest {
+ // Given
+ val request = ModelDownloadRequest(type)
+ every { download(request) } returns flowOf(
+ ModelDownloadBatch(
+ type,
+ "second",
+ DownloadState.Downloading(50),
+ listOf("first"),
+ modelName = "Second",
+ totalModelCount = 4
+ ),
+ ModelDownloadBatch(
+ type,
+ isRunning = false,
+ totalModelCount = 4,
+ completedIds = listOf("first", "second", "third", "fourth")
+ ),
+ )
+ val worker = worker(request)
+ // When
+ worker.doWork()
+ // Then
+ verify {
+ worker.setForegroundNotification(
+ "Download all",
+ "Second",
+ null,
+ 37 to 100,
+ true,
+ true,
+ "Cancel all downloads"
+ )
+ }
+ verify(exactly = 1) { worker.showGenericNotification("Download complete 🤩", any()) }
+ }
+
+ @Test
+ fun `given single model worker, download fails, expected failure output and failed notification without success`() =
+ runTest {
+ // Given
+ val request = ModelDownloadRequest(type, "model", "https://models/model")
+ every { download(request) } returns flow { throw IllegalStateException("offline") }
+ val worker = worker(request)
+ // When
+ val result = worker.doWork()
+ // Then
+ assertTrue(result is Result.Failure)
+ assertEquals("offline", (result as Result.Failure).outputData.getString("error"))
+ verify(exactly = 1) {
+ worker.showGenericNotification(
+ "Download failed 😞",
+ "Click here to open the application."
+ )
+ }
+ verify(exactly = 0) { worker.showGenericNotification("Download complete 🤩", any()) }
+ }
+
+ @Test
+ fun `given provider worker, cancellation propagates, expected no terminal notification`() =
+ runTest {
+ // Given
+ val request = ModelDownloadRequest(type)
+ val cancellation = CancellationException("cancelled")
+ every { download(request) } returns flow { throw cancellation }
+ val worker = worker(request)
+ // When
+ val actual = runCatching { worker.doWork() }.exceptionOrNull()
+ // Then
+ assertSame(cancellation, actual)
+ verify(exactly = 0) { worker.showGenericNotification(any(), any()) }
+ }
+
+ @Test
+ fun `given concurrent model workers, requests have distinct identities, expected independent foreground and result notifications`() {
+ // Given
+ val request = ModelDownloadRequest(type)
+ // When
+ val first = worker(request)
+ val second = worker(request)
+ // Then
+ assertNotEquals(first.notificationId, second.notificationId)
+ assertNotEquals(first.genericNotificationId, second.genericNotificationId)
+ assertNotEquals(first.notificationId, second.genericNotificationId)
+ assertNotEquals(first.notificationId, first.genericNotificationId)
+ }
+
+ @Test
+ fun `given download worker, stop races with activation completion, expected no terminal notification`() =
+ runTest {
+ // Given
+ val request = ModelDownloadRequest(type)
+ every { download(request) } returns flowOf(ModelDownloadBatch(type, isRunning = false))
+ val worker = worker(request)
+ every { worker.isStopped } returns true
+ // When
+ val actual = runCatching { worker.doWork() }.exceptionOrNull()
+ // Then
+ assertTrue(actual is CancellationException)
+ verify(exactly = 0) { worker.showGenericNotification(any(), any()) }
+ }
+
+ @Test
+ fun `given failed download worker, exception has no message, expected bounded diagnostic text in failure output`() =
+ runTest {
+ // Given
+ val request = ModelDownloadRequest(type)
+ val failure = IllegalStateException()
+ every { download(request) } returns flow { throw failure }
+ val worker = worker(request)
+ // When
+ val result = worker.doWork()
+ // Then
+ assertEquals(
+ failure.toString(),
+ (result as Result.Failure).outputData.getString("error")
+ )
+ verify(exactly = 1) { worker.showGenericNotification("Download failed 😞", any()) }
+ }
+
+ /**
+ * Supplies normal WorkManager request data while preventing platform service/notification side effects.
+ * @param request Captured provider and optional model/mirror to place in worker input.
+ * @author Dmitriy Moroz
+ */
+ private fun worker(request: ModelDownloadRequest): DownloadModelsTask {
+ val parameters = mockk(relaxed = true) {
+ every { id } returns UUID.randomUUID()
+ every { inputData } returns workDataOf(
+ "type" to request.type.key,
+ "model" to request.modelId,
+ "url" to request.sourceUrl
+ )
+ }
+ return spyk(
+ DownloadModelsTask(
+ RuntimeEnvironment.getApplication(),
+ parameters,
+ mockk(),
+ mockk(),
+ download
+ )
+ ).also { worker ->
+ coEvery { worker.setProgress(any()) } returns Unit
+ every {
+ worker.setForegroundNotification(
+ any(),
+ any(),
+ any(),
+ any(),
+ any(),
+ any(),
+ any()
+ )
+ } just Runs
+ every { worker.showGenericNotification(any(), any()) } just Runs
+ }
+ }
+}
diff --git a/feature/work/src/iosMain/kotlin/com/shifthackz/aisdv1/work/ModelDownloadManagerImpl.kt b/feature/work/src/iosMain/kotlin/com/shifthackz/aisdv1/work/ModelDownloadManagerImpl.kt
new file mode 100644
index 000000000..5f6d518d8
--- /dev/null
+++ b/feature/work/src/iosMain/kotlin/com/shifthackz/aisdv1/work/ModelDownloadManagerImpl.kt
@@ -0,0 +1,119 @@
+package com.shifthackz.aisdv1.work
+
+import com.shifthackz.aisdv1.domain.entity.DownloadState
+import com.shifthackz.aisdv1.domain.entity.LocalAiModel
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadBatch
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadRequest
+import com.shifthackz.aisdv1.domain.feature.work.ModelDownloadManager
+import com.shifthackz.aisdv1.domain.usecase.downloadable.DownloadModelsUseCase
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.CoroutineStart
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.cancelAndJoin
+import kotlinx.coroutines.currentCoroutineContext
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import platform.Foundation.NSUUID
+
+/**
+ * Owns concurrent single downloads or an exclusive batch across setup navigation.
+ * Each job receives finite iOS execution time, without durable background transfers.
+ * @param downloadModels Sequential policy within each batch or single model.
+ * @param scope Application-owned scope that outlives setup view models.
+ * @author Dmitriy Moroz
+ */
+internal class ModelDownloadManagerImpl(
+ private val downloadModels: DownloadModelsUseCase,
+ private val scope: CoroutineScope,
+) : ModelDownloadManager {
+ private val state = MutableStateFlow>(emptyList())
+ override val batches = state.asStateFlow()
+ private val jobs = mutableMapOf, Job>()
+ private val lifecycleMutex = Mutex()
+
+ /**
+ * Starts independent model work or joins cancelled jobs before a confirmed provider replacement.
+ * @param request Captured provider and optional single-model mirror.
+ * @param shouldReplace Whether the user confirmed stopping existing transfers.
+ * @author Dmitriy Moroz
+ */
+ override suspend fun start(request: ModelDownloadRequest, shouldReplace: Boolean) =
+ lifecycleMutex.withLock {
+ val key = request.type to request.modelId
+ val active = state.value.filter { it.isRunning }
+ if (shouldReplace) {
+ jobs.values.forEach { it.cancelAndJoin() }
+ } else if (active.any { it.isBatch } || (request.isBatch && active.isNotEmpty()) || jobs[key]?.isCompleted == false) {
+ return@withLock
+ }
+ jobs.entries.removeAll { it.value.isCompleted }
+ val workId = NSUUID().UUIDString
+ state.update { snapshots ->
+ snapshots.filterNot { it.type == request.type && (if (request.isBatch) it.isBatch else !it.isBatch && it.modelId == request.modelId) } +
+ ModelDownloadBatch(
+ request.type,
+ modelId = request.modelId,
+ isBatch = request.isBatch,
+ workId = workId
+ )
+ }
+ val job = scope.launch(start = CoroutineStart.LAZY) {
+ val activeJob = currentCoroutineContext()[Job]
+ val background = IosBackgroundExecution("Model downloads") { activeJob }
+ try {
+ background.begin()
+ downloadModels(request).collect { snapshot ->
+ state.update { snapshots ->
+ snapshots.map {
+ if (it.workId == workId) snapshot.copy(
+ workId = workId
+ ) else it
+ }
+ }
+ }
+ } catch (cancelled: CancellationException) {
+ state.update { snapshots ->
+ snapshots.map {
+ if (it.workId == workId) it.copy(
+ progress = DownloadState.Unknown,
+ isRunning = false
+ ) else it
+ }
+ }
+ throw cancelled
+ } catch (failure: Exception) {
+ state.update { snapshots ->
+ snapshots.map {
+ if (it.workId == workId) it.copy(
+ progress = DownloadState.Error(failure),
+ isRunning = false
+ ) else it
+ }
+ }
+ } finally {
+ background.end()
+ }
+ }
+ jobs[key] = job
+ job.start()
+ Unit
+ }
+
+ /**
+ * Cancels matching jobs without affecting other models' transfers or installed files.
+ * @param type Provider to cancel, or null for every model request.
+ * @param modelId Model within that provider, or null for all its requests.
+ * @author Dmitriy Moroz
+ */
+ override suspend fun cancel(type: LocalAiModel.Type?, modelId: String?) =
+ lifecycleMutex.withLock {
+ require(modelId == null || type != null)
+ jobs.filterKeys { (provider, id) -> (type == null || provider == type) && (modelId == null || id == modelId) }
+ .values.forEach { it.cancel() }
+ }
+}
diff --git a/feature/work/src/iosMain/kotlin/com/shifthackz/aisdv1/work/di/BackgroundWorkModule.kt b/feature/work/src/iosMain/kotlin/com/shifthackz/aisdv1/work/di/BackgroundWorkModule.kt
index 8026781ee..5f01b5eb4 100644
--- a/feature/work/src/iosMain/kotlin/com/shifthackz/aisdv1/work/di/BackgroundWorkModule.kt
+++ b/feature/work/src/iosMain/kotlin/com/shifthackz/aisdv1/work/di/BackgroundWorkModule.kt
@@ -6,14 +6,25 @@ import com.shifthackz.aisdv1.work.BackgroundTaskManagerImpl
import com.shifthackz.aisdv1.work.BackgroundWorkObserverImpl
import org.koin.core.module.dsl.singleOf
import org.koin.dsl.bind
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.Dispatchers
import org.koin.dsl.module
+import com.shifthackz.aisdv1.domain.feature.work.ModelDownloadManager
+import com.shifthackz.aisdv1.work.ModelDownloadManagerImpl
/**
- * Exposes the `backgroundWorkModule` value used by the SDAI background work feature layer.
+ * Binds platform task scheduling, progress observation and model download ownership.
*
* @author Dmitriy Moroz
*/
actual val backgroundWorkModule = module {
+ single {
+ ModelDownloadManagerImpl(
+ get(),
+ CoroutineScope(SupervisorJob() + Dispatchers.Main)
+ )
+ }
singleOf(::BackgroundWorkObserverImpl) bind BackgroundWorkObserver::class
singleOf(::BackgroundTaskManagerImpl) bind BackgroundTaskManager::class
}
diff --git a/presentation/app/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/app/di/PresentationModule.kt b/presentation/app/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/app/di/PresentationModule.kt
index 6e512e530..52324aee3 100644
--- a/presentation/app/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/app/di/PresentationModule.kt
+++ b/presentation/app/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/app/di/PresentationModule.kt
@@ -1,7 +1,6 @@
package com.shifthackz.aisdv1.presentation.app.di
import com.shifthackz.aisdv1.presentation.benchmark.di.benchmarkUiUtilsModule
-import com.shifthackz.aisdv1.presentation.configuration.di.configurationUiUtilsModule
import com.shifthackz.aisdv1.presentation.logger.di.loggerUiUtilsModule
import com.shifthackz.aisdv1.presentation.gallery.di.galleryUiUtilsModule
import com.shifthackz.aisdv1.presentation.components.di.componentsUiUtilsModule
@@ -14,7 +13,6 @@ import com.shifthackz.aisdv1.presentation.debug.di.debugUiUtilsModule
*/
val presentationModule = arrayOf(
benchmarkUiUtilsModule,
- configurationUiUtilsModule,
loggerUiUtilsModule,
galleryUiUtilsModule,
componentsUiUtilsModule,
diff --git a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/di/PresentationCoreModule.kt b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/di/PresentationCoreModule.kt
index ff3fc4457..fa243edaa 100644
--- a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/di/PresentationCoreModule.kt
+++ b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/di/PresentationCoreModule.kt
@@ -5,7 +5,6 @@ import com.shifthackz.aisdv1.presentation.benchmark.di.benchmarkViewModelModule
import com.shifthackz.aisdv1.presentation.statistics.di.statisticsViewModelModule
import com.shifthackz.aisdv1.presentation.settings.di.settingsCoreModule
import com.shifthackz.aisdv1.presentation.settings.di.settingsViewModelModule
-import com.shifthackz.aisdv1.presentation.configuration.di.configurationCoreModule
import com.shifthackz.aisdv1.presentation.configuration.di.configurationViewModelModule
import com.shifthackz.aisdv1.presentation.splash.di.splashViewModelModule
import com.shifthackz.aisdv1.presentation.donate.di.donateViewModelModule
@@ -37,7 +36,6 @@ val corePresentationModule = module {
statisticsViewModelModule,
settingsCoreModule,
settingsViewModelModule,
- configurationCoreModule,
configurationViewModelModule,
splashViewModelModule,
donateViewModelModule,
diff --git a/presentation/configuration/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/di/ConfigurationUiUtilsModule.kt b/presentation/configuration/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/di/ConfigurationUiUtilsModule.kt
deleted file mode 100644
index 7b8743cb8..000000000
--- a/presentation/configuration/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/di/ConfigurationUiUtilsModule.kt
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.shifthackz.aisdv1.presentation.configuration.di
-
-import com.shifthackz.aisdv1.presentation.configuration.setup.platform.AndroidServerSetupDownloadGuard
-import com.shifthackz.aisdv1.presentation.configuration.setup.platform.ServerSetupDownloadGuard
-import org.koin.core.module.dsl.factoryOf
-import org.koin.dsl.bind
-import org.koin.dsl.module
-
-
-/**
- * Supplies the Android download-guard factory used to enforce platform download prerequisites.
- *
- * @author Dmitriy Moroz
- */
-val configurationUiUtilsModule = module {
- factoryOf(::AndroidServerSetupDownloadGuard) bind ServerSetupDownloadGuard::class
-}
diff --git a/presentation/configuration/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/platform/AndroidServerSetupDownloadGuard.kt b/presentation/configuration/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/platform/AndroidServerSetupDownloadGuard.kt
deleted file mode 100644
index 01d306ddc..000000000
--- a/presentation/configuration/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/platform/AndroidServerSetupDownloadGuard.kt
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.shifthackz.aisdv1.presentation.configuration.setup.platform
-
-import com.shifthackz.aisdv1.domain.interactor.wakelock.WakeLockInterActor
-
-internal class AndroidServerSetupDownloadGuard(
- private val wakeLockInterActor: WakeLockInterActor,
-) : ServerSetupDownloadGuard {
-
- override suspend fun withDownload(block: suspend () -> T): T {
- wakeLockInterActor.acquireWakelockUseCase()
- try {
- return block()
- } finally {
- wakeLockInterActor.releaseWakeLockUseCase()
- }
- }
-}
diff --git a/presentation/configuration/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupCatalogRefreshTest.kt b/presentation/configuration/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupCatalogRefreshTest.kt
index beed2fb7c..ce368df4e 100644
--- a/presentation/configuration/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupCatalogRefreshTest.kt
+++ b/presentation/configuration/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupCatalogRefreshTest.kt
@@ -13,13 +13,9 @@ import com.shifthackz.aisdv1.domain.entity.ServerSource
import com.shifthackz.aisdv1.domain.feature.openaioauth.OpenAiOAuthGateway
import com.shifthackz.aisdv1.domain.preference.PreferenceManager
import com.shifthackz.aisdv1.domain.usecase.downloadable.GetCachedLocalModelCatalogUseCase
-import com.shifthackz.aisdv1.domain.usecase.downloadable.DownloadModelUseCase
import com.shifthackz.aisdv1.domain.usecase.downloadable.DeleteModelUseCase
import com.shifthackz.aisdv1.domain.entity.DownloadState
-import com.shifthackz.aisdv1.presentation.configuration.setup.platform.NoOpServerSetupDownloadGuard
import com.shifthackz.aisdv1.presentation.components.service.storage.StorageUsageObserver
-import kotlinx.coroutines.awaitCancellation
-import kotlinx.coroutines.flow.flow
import com.shifthackz.aisdv1.domain.usecase.downloadable.RefreshLocalModelCatalogUseCase
import com.shifthackz.aisdv1.domain.usecase.settings.ConnectToMnnUseCase
import com.shifthackz.aisdv1.domain.usecase.settings.GetConfigurationUseCase
@@ -35,6 +31,10 @@ import io.mockk.verify
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.ExperimentalCoroutinesApi
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadBatch
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadRequest
+import com.shifthackz.aisdv1.domain.feature.work.ModelDownloadManager
+import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
@@ -54,7 +54,8 @@ import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class ServerSetupCatalogRefreshTest {
private val getCachedLocalModelCatalogUseCase = mockk()
- private val downloadModelUseCase = mockk()
+ private val batches = MutableStateFlow>(emptyList())
+ private val modelDownloadManager = mockk(relaxed = true)
private val deleteModelUseCase = mockk()
private val refreshLocalModelCatalogUseCase = mockk()
private val getConfigurationUseCase = mockk()
@@ -79,6 +80,32 @@ class ServerSetupCatalogRefreshTest {
localMnnModelId = LocalAiModel.CustomMnn.id,
localMnnModelPath = "/custom/bundle",
)
+ batches.value = emptyList()
+ every { modelDownloadManager.batches } returns batches
+ coEvery { modelDownloadManager.start(any(), any()) } coAnswers {
+ val request = firstArg()
+ val shouldReplace = secondArg()
+ batches.value =
+ batches.value.filterNot { shouldReplace || it.type == request.type && it.modelId == request.modelId } + listOf(
+ ModelDownloadBatch(
+ request.type,
+ request.modelId,
+ DownloadState.Downloading(50),
+ isBatch = request.isBatch,
+ workId = request.modelId.orEmpty(),
+ )
+ )
+ }
+ coEvery { modelDownloadManager.cancel(any(), any()) } coAnswers {
+ val type = firstArg()
+ val id = secondArg()
+ batches.value = batches.value.map {
+ if ((type == null || it.type == type) && (id == null || it.modelId == id)) it.copy(
+ progress = DownloadState.Unknown,
+ isRunning = false
+ ) else it
+ }
+ }
every { openAiOAuthGateway.observeIdentity() } returns flowOf(null)
coEvery { openAiOAuthGateway.currentIdentity() } returns null
coEvery { getCachedLocalModelCatalogUseCase(any()) } returns emptyList()
@@ -210,12 +237,6 @@ class ServerSetupCatalogRefreshTest {
coEvery { refreshLocalModelCatalogUseCase(LocalAiModel.Type.Mnn) } returns LocalModelCatalogResult(
listOf(LocalAiModel.CustomMnn, catalog)
)
- val completion = CompletableDeferred()
- coEvery { downloadModelUseCase(catalog.id, any()) } returns flow {
- emit(DownloadState.Downloading(50))
- completion.await()
- emit(DownloadState.Complete("/owned/mnn"))
- }
val model = createViewModel()
advanceUntilIdle()
// When
@@ -231,7 +252,19 @@ class ServerSetupCatalogRefreshTest {
val oldProgressRow = model.state.value.localMnnModels.first { it.id == catalog.id }
model.processIntent(ServerSetupIntent.AllowLocalCustomModel(true))
model.processIntent(ServerSetupIntent.UpdateServerMode(ServerSource.LOCAL_MICROSOFT_ONNX))
- completion.complete(Unit)
+ coEvery { refreshLocalModelCatalogUseCase(LocalAiModel.Type.Mnn) } returns LocalModelCatalogResult(
+ listOf(LocalAiModel.CustomMnn, catalog.copy(downloaded = true))
+ )
+ coEvery { getCachedLocalModelCatalogUseCase(LocalAiModel.Type.Mnn) } returns listOf(
+ LocalAiModel.CustomMnn, catalog.copy(downloaded = true)
+ )
+ batches.value = batches.value.map {
+ it.copy(
+ progress = DownloadState.Complete("/owned/mnn"),
+ completedIds = listOf(catalog.id),
+ isRunning = false,
+ )
+ }
advanceUntilIdle()
// Then
val result = model.state.value.localMnnModels.first { it.id == catalog.id }
@@ -253,7 +286,7 @@ class ServerSetupCatalogRefreshTest {
}
@Test
- fun `given active model transfer, cancellation starts before provider switches, expected cleanup stays with owning catalog`() =
+ fun `given single model worker, cancellation starts before provider switches, expected cancellation stays with owning catalog`() =
runTest {
// Given
val catalog = LocalAiModel.CustomMnn.copy(
@@ -263,10 +296,6 @@ class ServerSetupCatalogRefreshTest {
coEvery { refreshLocalModelCatalogUseCase(LocalAiModel.Type.Mnn) } returns LocalModelCatalogResult(
listOf(catalog)
)
- coEvery { downloadModelUseCase(catalog.id, any()) } returns flow {
- emit(DownloadState.Downloading(50))
- awaitCancellation()
- }
val model = createViewModel()
advanceUntilIdle()
model.processIntent(
@@ -278,6 +307,9 @@ class ServerSetupCatalogRefreshTest {
)
runCurrent()
val row = model.state.value.localMnnModels.single()
+ coEvery { getCachedLocalModelCatalogUseCase(LocalAiModel.Type.Mnn) } returns listOf(
+ catalog
+ )
// When
model.processIntent(ServerSetupIntent.LocalModel.ClickReduce(row))
@@ -285,7 +317,8 @@ class ServerSetupCatalogRefreshTest {
advanceUntilIdle()
// Then
- coVerify(exactly = 1) { deleteModelUseCase(catalog.id) }
+ coVerify(exactly = 1) { modelDownloadManager.cancel(LocalAiModel.Type.Mnn, catalog.id) }
+ coVerify(exactly = 0) { deleteModelUseCase(catalog.id) }
assertEquals(false, model.state.value.localMnnModels.single().downloaded)
assertEquals(
DownloadState.Unknown,
@@ -296,7 +329,7 @@ class ServerSetupCatalogRefreshTest {
}
@Test
- fun `given transfer cancellation, joined producer has already installed model, expected recovered install and storage notification`() =
+ fun `given single model worker cancellation, activation already finished, expected recovered install and storage notification`() =
runTest {
// Given
val catalog = LocalAiModel.CustomMnn.copy(
@@ -306,10 +339,6 @@ class ServerSetupCatalogRefreshTest {
coEvery { refreshLocalModelCatalogUseCase(LocalAiModel.Type.Mnn) } returns LocalModelCatalogResult(
listOf(catalog)
)
- coEvery { downloadModelUseCase(catalog.id, any()) } returns flow {
- emit(DownloadState.Downloading(99))
- awaitCancellation()
- }
val model = createViewModel()
advanceUntilIdle()
model.processIntent(
@@ -324,6 +353,9 @@ class ServerSetupCatalogRefreshTest {
coEvery { getCachedLocalModelCatalogUseCase(LocalAiModel.Type.Mnn) } returns listOf(
catalog.copy(downloaded = true)
)
+ coEvery { refreshLocalModelCatalogUseCase(LocalAiModel.Type.Mnn) } returns LocalModelCatalogResult(
+ listOf(catalog.copy(downloaded = true))
+ )
// When
model.processIntent(ServerSetupIntent.LocalModel.ClickReduce(row))
@@ -339,6 +371,205 @@ class ServerSetupCatalogRefreshTest {
verify(exactly = 1) { storageUsageObserver.notifyChanged() }
}
+ @Test
+ fun `given download all action, no provider work is active, expected current provider batch scheduled`() =
+ runTest {
+ // Given
+ val model = createViewModel()
+ advanceUntilIdle()
+ // When
+ model.processIntent(ServerSetupIntent.DownloadAllModels)
+ advanceUntilIdle()
+ // Then
+ coVerify(exactly = 1) {
+ modelDownloadManager.start(
+ ModelDownloadRequest(LocalAiModel.Type.Mnn),
+ false
+ )
+ }
+ }
+
+ @Test
+ fun `given other provider download, download all is clicked then dialog closed, expected existing worker unchanged`() =
+ runTest {
+ // Given
+ val work = ModelDownloadBatch(
+ LocalAiModel.Type.ONNX,
+ "first",
+ DownloadState.Downloading(30),
+ isBatch = false,
+ workId = "other"
+ )
+ batches.value = listOf(work)
+ val model = createViewModel()
+ advanceUntilIdle()
+ // When
+ model.processIntent(ServerSetupIntent.DownloadAllModels)
+ val dialog = model.state.value.modal
+ model.processIntent(ServerSetupIntent.DismissDialog)
+ advanceUntilIdle()
+ // Then
+ assertEquals(ServerSetupState.Modal.SwitchModelDownloads(LocalAiModel.Type.Mnn), dialog)
+ assertEquals(ServerSetupState.Modal.None, model.state.value.modal)
+ assertEquals(listOf(work), batches.value)
+ coVerify(exactly = 0) { modelDownloadManager.start(any(), any()) }
+ coVerify(exactly = 0) { modelDownloadManager.cancel(any(), any()) }
+ }
+
+ @Test
+ fun `given other provider download, switch is confirmed, expected captured destination replaces existing work`() =
+ runTest {
+ // Given
+ batches.value = listOf(ModelDownloadBatch(LocalAiModel.Type.ONNX, workId = "other"))
+ val model = createViewModel()
+ advanceUntilIdle()
+ model.processIntent(ServerSetupIntent.DownloadAllModels)
+ // When
+ model.processIntent(ServerSetupIntent.ConfirmModelDownloadSwitch)
+ advanceUntilIdle()
+ // Then
+ coVerify(exactly = 1) {
+ modelDownloadManager.start(
+ ModelDownloadRequest(LocalAiModel.Type.Mnn),
+ true
+ )
+ }
+ assertEquals(ServerSetupState.Modal.None, model.state.value.modal)
+ }
+
+ @Test
+ fun `given current provider single download, download all intent arrives, expected active transfer retained`() =
+ runTest {
+ // Given
+ batches.value = listOf(
+ ModelDownloadBatch(
+ LocalAiModel.Type.Mnn,
+ "first",
+ isBatch = false,
+ workId = "single"
+ )
+ )
+ val model = createViewModel()
+ advanceUntilIdle()
+ // When
+ model.processIntent(ServerSetupIntent.DownloadAllModels)
+ advanceUntilIdle()
+ // Then
+ coVerify(exactly = 0) { modelDownloadManager.start(any(), any()) }
+ coVerify(exactly = 0) { modelDownloadManager.cancel(any(), any()) }
+ }
+
+ @Test
+ fun `given concurrent single model downloads, one row is cancelled, expected other row continues without network catalog reload`() =
+ runTest {
+ // Given
+ val first = LocalAiModel(
+ "first",
+ LocalAiModel.Type.Mnn,
+ "First",
+ "1 GB",
+ listOf("https://models/first")
+ )
+ val second = first.copy(id = "second", sources = listOf("https://models/second"))
+ coEvery { refreshLocalModelCatalogUseCase(LocalAiModel.Type.Mnn) } returns LocalModelCatalogResult(
+ listOf(first, second)
+ )
+ coEvery { getCachedLocalModelCatalogUseCase(LocalAiModel.Type.Mnn) } returns listOf(
+ first,
+ second
+ )
+ val model = createViewModel()
+ advanceUntilIdle()
+ model.processIntent(
+ ServerSetupIntent.LocalModel.DownloadConfirm(
+ first.id,
+ first.sources.single(),
+ first.type
+ )
+ )
+ runCurrent()
+ model.processIntent(
+ ServerSetupIntent.LocalModel.DownloadConfirm(
+ second.id,
+ second.sources.single(),
+ second.type
+ )
+ )
+ runCurrent()
+ val row = model.state.value.localMnnModels.first { it.id == first.id }
+ // When
+ model.processIntent(ServerSetupIntent.LocalModel.ClickReduce(row))
+ advanceUntilIdle()
+ // Then
+ coVerify(exactly = 1) { modelDownloadManager.cancel(first.type, first.id) }
+ coVerify(exactly = 1) { refreshLocalModelCatalogUseCase(LocalAiModel.Type.Mnn) }
+ assertEquals(
+ DownloadState.Unknown,
+ model.state.value.localMnnModels.first { it.id == first.id }.downloadState
+ )
+ assertEquals(
+ DownloadState.Downloading(50),
+ model.state.value.localMnnModels.first { it.id == second.id }.downloadState
+ )
+ assertEquals(
+ LocalCatalogStatus.READY,
+ model.state.value.localCatalogStatuses[first.type]
+ )
+ assertEquals(emptySet(), model.state.value.refreshingLocalCatalogs)
+ }
+
+ @Test
+ fun `given failed catalog, retry remains pending, expected error card status retained with refreshing flag`() =
+ runTest {
+ // Given
+ val failure = IllegalStateException("offline")
+ coEvery { refreshLocalModelCatalogUseCase(LocalAiModel.Type.Mnn) } returns LocalModelCatalogResult(
+ listOf(LocalAiModel.CustomMnn),
+ failure
+ )
+ val model = createViewModel()
+ advanceUntilIdle()
+ val pending = CompletableDeferred()
+ coEvery { refreshLocalModelCatalogUseCase(LocalAiModel.Type.Mnn) } coAnswers { pending.await() }
+ // When
+ model.processIntent(ServerSetupIntent.RetryLocalCatalog(ServerSource.LOCAL_MNN))
+ runCurrent()
+ val during = model.state.value
+ pending.complete(LocalModelCatalogResult(listOf(LocalAiModel.CustomMnn), failure))
+ advanceUntilIdle()
+ // Then
+ assertEquals(
+ LocalCatalogStatus.ERROR,
+ during.localCatalogStatuses[LocalAiModel.Type.Mnn]
+ )
+ assertEquals(setOf(LocalAiModel.Type.Mnn), during.refreshingLocalCatalogs)
+ assertEquals(
+ LocalCatalogStatus.ERROR,
+ model.state.value.localCatalogStatuses[LocalAiModel.Type.Mnn]
+ )
+ assertEquals(emptySet(), model.state.value.refreshingLocalCatalogs)
+ }
+
+ @Test
+ fun `given persisted terminal failure, setup opens after work ended, expected no historical error dialog replay`() =
+ runTest {
+ // Given
+ batches.value = listOf(
+ ModelDownloadBatch(
+ LocalAiModel.Type.Mnn,
+ progress = DownloadState.Error(IllegalStateException("old failure")),
+ isRunning = false,
+ workId = "history"
+ )
+ )
+ // When
+ val model = createViewModel()
+ advanceUntilIdle()
+ // Then
+ assertEquals(ServerSetupState.Modal.None, model.state.value.modal)
+ verify(exactly = 0) { storageUsageObserver.notifyChanged() }
+ }
+
/**
* Binds the production setup reducer to one virtual scheduler and its real lifecycle cancellation.
*
@@ -379,9 +610,8 @@ class ServerSetupCatalogRefreshTest {
connectToStabilityAiUseCase = mockk(relaxed = true),
connectToFalAiUseCase = mockk(relaxed = true),
connectToArliAiUseCase = mockk(relaxed = true),
- downloadModelUseCase = downloadModelUseCase,
+ modelDownloadManager = modelDownloadManager,
deleteModelUseCase = deleteModelUseCase,
- downloadGuard = NoOpServerSetupDownloadGuard,
storageUsageObserver = storageUsageObserver,
linksProvider = mockk(relaxed = true),
preferenceManager = preferenceManager,
diff --git a/presentation/configuration/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupDownloadBatchStateTest.kt b/presentation/configuration/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupDownloadBatchStateTest.kt
new file mode 100644
index 000000000..5fc820aed
--- /dev/null
+++ b/presentation/configuration/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupDownloadBatchStateTest.kt
@@ -0,0 +1,145 @@
+package com.shifthackz.aisdv1.presentation.configuration.setup
+
+import com.shifthackz.aisdv1.domain.entity.DownloadState
+import com.shifthackz.aisdv1.domain.entity.LocalAiModel
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadBatch
+import com.shifthackz.aisdv1.domain.entity.ServerSource
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.Parameterized
+
+/**
+ * Verifies independent row ownership and conservative terminal replay for every local catalog family.
+ * @param type Owning provider to update even when setup displays a remote provider.
+ * @author Dmitriy Moroz
+ */
+@RunWith(Parameterized::class)
+class ServerSetupDownloadBatchStateTest(private val type: LocalAiModel.Type) {
+ private val first = LocalAiModel(
+ "first",
+ type,
+ "First",
+ "1 GB",
+ listOf("https://models/first"),
+ selected = true
+ )
+ private val second = first.copy(id = "second", selected = false)
+ private val initial
+ get() = ServerSetupState(mode = ServerSource.AUTOMATIC1111)
+ .withCatalogResult(type, listOf(first, second), LocalCatalogStatus.READY)
+ private val firstWork
+ get() = ModelDownloadBatch(
+ type,
+ first.id,
+ DownloadState.Downloading(30),
+ isBatch = false,
+ workId = "first-work"
+ )
+ private val secondWork
+ get() = ModelDownloadBatch(
+ type,
+ second.id,
+ DownloadState.Downloading(60),
+ isBatch = false,
+ workId = "second-work"
+ )
+
+ @Test
+ fun `given concurrent model progress, both snapshots arrive, expected separate rows and setup selection preserved`() {
+ // Given
+ val state = initial
+ // When
+ val result = state.withModelDownloadBatches(listOf(firstWork, secondWork))
+ // Then
+ assertEquals(
+ listOf(DownloadState.Downloading(30), DownloadState.Downloading(60)),
+ result.catalogModels(type).map { it.downloadState })
+ assertEquals(setOf(first.id, second.id), result.localCatalogActiveDownloads[type])
+ assertTrue(result.catalogModels(type).first().selected)
+ assertEquals(ServerSource.AUTOMATIC1111, result.mode)
+ }
+
+ @Test
+ fun `given concurrent model progress, one worker is cancelled, expected other row continues without catalog loading`() {
+ // Given
+ val state = initial.withModelDownloadBatches(listOf(firstWork, secondWork))
+ // When
+ val result = state.withModelDownloadBatches(
+ listOf(
+ firstWork.copy(
+ progress = DownloadState.Unknown,
+ isRunning = false
+ ), secondWork.copy(progress = DownloadState.Downloading(70))
+ )
+ )
+ // Then
+ assertEquals(
+ listOf(DownloadState.Unknown, DownloadState.Downloading(70)),
+ result.catalogModels(type).map { it.downloadState })
+ assertEquals(setOf(second.id), result.localCatalogActiveDownloads[type])
+ assertEquals(LocalCatalogStatus.READY, result.localCatalogStatuses[type])
+ }
+
+ @Test
+ fun `given provider batch, next model starts after first activation, expected first owned and second transferring`() {
+ // Given
+ val batch = ModelDownloadBatch(
+ type,
+ second.id,
+ DownloadState.Downloading(5),
+ listOf(first.id),
+ totalModelCount = 2
+ )
+ // When
+ val result = initial.withModelDownloadBatches(listOf(batch))
+ // Then
+ assertTrue(result.catalogModels(type).first().downloaded)
+ assertFalse(result.catalogModels(type).last().downloaded)
+ assertEquals(DownloadState.Downloading(5), result.catalogModels(type).last().downloadState)
+ }
+
+ @Test
+ fun `given deleted local model, historical worker success replays, expected current ownership remains deleted`() {
+ // Given
+ val state = initial.withDeletedLocalModel(initial.catalogModels(type).first(), type)
+ val history = firstWork.copy(
+ progress = DownloadState.Complete("/owned/old"),
+ completedIds = listOf(first.id),
+ isRunning = false
+ )
+ // When
+ val result = state.withModelDownloadBatches(listOf(history))
+ // Then
+ assertFalse(result.catalogModels(type).first().downloaded)
+ assertEquals(DownloadState.Unknown, result.catalogModels(type).first().downloadState)
+ }
+
+ @Test
+ fun `given active worker, metadata refresh reports partial directory as owned, expected worker progress overrides cache`() {
+ // Given
+ val state = initial.withModelDownloadBatches(listOf(firstWork))
+ // When
+ val result = state.withCatalogResult(
+ type,
+ listOf(first.copy(downloaded = true), second),
+ LocalCatalogStatus.ERROR
+ )
+ // Then
+ assertFalse(result.catalogModels(type).first().downloaded)
+ assertEquals(
+ DownloadState.Downloading(30),
+ result.catalogModels(type).first().downloadState
+ )
+ assertEquals(LocalCatalogStatus.ERROR, result.localCatalogStatuses[type])
+ }
+
+ companion object {
+ /** Supplies all common catalog families, including those unavailable on the current host platform. */
+ @JvmStatic
+ @Parameterized.Parameters(name = "{0}")
+ fun providers() = LocalAiModel.Type.entries.map { arrayOf(it) }
+ }
+}
diff --git a/presentation/configuration/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/LocalModelDownloadActionStateTest.kt b/presentation/configuration/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/LocalModelDownloadActionStateTest.kt
new file mode 100644
index 000000000..bf208e046
--- /dev/null
+++ b/presentation/configuration/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/LocalModelDownloadActionStateTest.kt
@@ -0,0 +1,137 @@
+package com.shifthackz.aisdv1.presentation.configuration.setup.component
+
+import com.shifthackz.aisdv1.domain.entity.LocalAiModel
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadBatch
+import com.shifthackz.aisdv1.domain.entity.ServerSource
+import com.shifthackz.aisdv1.presentation.configuration.setup.LocalCatalogStatus
+import com.shifthackz.aisdv1.presentation.configuration.setup.ServerSetupState
+import com.shifthackz.aisdv1.presentation.configuration.setup.withCatalogResult
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Protects footer visibility and enabled click semantics without asserting animation implementation details.
+ * @author Dmitriy Moroz
+ */
+class LocalModelDownloadActionStateTest {
+ private val type = LocalAiModel.Type.ONNX
+ private val model =
+ LocalAiModel("catalog", type, "Model", "1 GB", listOf("https://models/model"))
+ private val state
+ get() = ServerSetupState(
+ mode = ServerSource.LOCAL_MICROSOFT_ONNX,
+ loadingConfiguration = false
+ )
+ .withCatalogResult(type, listOf(model), LocalCatalogStatus.READY)
+
+ @Test
+ fun `given missing catalog model, no worker is active, expected enabled download all action`() {
+ // Given
+ val initial = state
+ // When
+ val action = initial.toLocalModelDownloadActionState()
+ // Then
+ assertEquals(LocalModelDownloadActionState(true, true, false), action)
+ }
+
+ @Test
+ fun `given single model work, current provider starts transfer, expected batch action hidden until termination`() {
+ // Given
+ val work = ModelDownloadBatch(type, model.id, isBatch = false)
+ val active = state.copy(modelDownloadBatches = listOf(work))
+ // When
+ val during = active.toLocalModelDownloadActionState()
+ val after = active.copy(modelDownloadBatches = listOf(work.copy(isRunning = false)))
+ .toLocalModelDownloadActionState()
+ // Then
+ assertFalse(during.isVisible)
+ assertEquals(LocalModelDownloadActionState(true, true, false), after)
+ }
+
+ @Test
+ fun `given active provider batch, all catalog entries finish activation, expected cancel all action retained until worker stops`() {
+ // Given
+ val completed = state.withCatalogResult(
+ type,
+ listOf(model.copy(downloaded = true)),
+ LocalCatalogStatus.READY
+ )
+ .copy(modelDownloadBatches = listOf(ModelDownloadBatch(type)))
+ // When
+ val action = completed.toLocalModelDownloadActionState()
+ // Then
+ assertEquals(LocalModelDownloadActionState(true, true, true), action)
+ }
+
+ @Test
+ fun `given another provider download, current provider has missing models, expected enabled action for switch dialog`() {
+ // Given
+ val initial =
+ state.copy(modelDownloadBatches = listOf(ModelDownloadBatch(LocalAiModel.Type.MediaPipe)))
+ // When
+ val action = initial.toLocalModelDownloadActionState()
+ // Then
+ assertEquals(LocalModelDownloadActionState(true, true, false), action)
+ }
+
+ @Test
+ fun `given completed catalog, no missing models remain, expected download all hidden`() {
+ // Given
+ val completed = state.withCatalogResult(
+ type,
+ listOf(model.copy(downloaded = true)),
+ LocalCatalogStatus.READY
+ )
+ // When
+ val action = completed.toLocalModelDownloadActionState()
+ // Then
+ assertFalse(action.isVisible)
+ }
+
+ @Test
+ fun `given model without sources, catalog is ready, expected download all hidden`() {
+ // Given
+ val initial = state.withCatalogResult(
+ type,
+ listOf(model.copy(sources = emptyList())),
+ LocalCatalogStatus.READY
+ )
+ // When
+ val action = initial.toLocalModelDownloadActionState()
+ // Then
+ assertFalse(action.isVisible)
+ }
+
+ @Test
+ fun `given failed catalog, no work is running, expected visible download action inactive`() {
+ // Given
+ val initial = state.copy(localCatalogStatuses = mapOf(type to LocalCatalogStatus.ERROR))
+ // When
+ val action = initial.toLocalModelDownloadActionState()
+ // Then
+ assertTrue(action.isVisible)
+ assertFalse(action.isEnabled)
+ }
+
+ @Test
+ fun `given configuration initialization, catalog has missing models, expected footer disabled`() {
+ // Given
+ val initial = state.copy(loadingConfiguration = true)
+ // When
+ val action = initial.toLocalModelDownloadActionState()
+ // Then
+ assertFalse(action.isEnabled)
+ }
+
+ @Test
+ fun `given remote provider, model downloads exist, expected local footer absent`() {
+ // Given
+ val initial = state.copy(mode = ServerSource.AUTOMATIC1111)
+ // When
+ val action = initial.toLocalModelDownloadActionState()
+ // Then
+ assertEquals(LocalModelDownloadActionState(false, false, false), action)
+ }
+}
diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/di/ConfigurationCoreModule.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/di/ConfigurationCoreModule.kt
deleted file mode 100644
index 6fa83b872..000000000
--- a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/di/ConfigurationCoreModule.kt
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.shifthackz.aisdv1.presentation.configuration.di
-
-import com.shifthackz.aisdv1.presentation.configuration.setup.platform.NoOpServerSetupDownloadGuard
-import com.shifthackz.aisdv1.presentation.configuration.setup.platform.ServerSetupDownloadGuard
-import org.koin.dsl.module
-
-/**
- * Supplies the no-op download guard for hosts without Android-specific download prerequisites.
- *
- * @author Dmitriy Moroz
- */
-val configurationCoreModule = module {
- single { NoOpServerSetupDownloadGuard }
-}
diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/di/ConfigurationViewModelModule.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/di/ConfigurationViewModelModule.kt
index b530f8eb3..1065ca036 100644
--- a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/di/ConfigurationViewModelModule.kt
+++ b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/di/ConfigurationViewModelModule.kt
@@ -66,9 +66,8 @@ val configurationViewModelModule = module {
connectToStabilityAiUseCase = get(),
connectToFalAiUseCase = get(),
connectToArliAiUseCase = get(),
- downloadModelUseCase = get(),
+ modelDownloadManager = get(),
deleteModelUseCase = get(),
- downloadGuard = get(),
storageUsageObserver = get(),
linksProvider = get(),
preferenceManager = get(),
diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupCatalogState.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupCatalogState.kt
index 8203ecb49..b344fee21 100644
--- a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupCatalogState.kt
+++ b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupCatalogState.kt
@@ -93,14 +93,16 @@ internal fun ServerSetupState.withCatalogResult(
LocalAiModel.Type.Bonsai -> copy(localBonsaiModels = merged)
LocalAiModel.Type.Mnn -> copy(localMnnModels = merged)
}
- return result.copy(localCatalogStatuses = result.localCatalogStatuses + (type to status))
+ val refreshed =
+ result.copy(localCatalogStatuses = result.localCatalogStatuses + (type to status))
+ return refreshed.withModelDownloadBatches(modelDownloadBatches)
}
/**
- * Recovers a completed owned install after a transfer has joined but its terminal emission was lost.
- * The owning file-store read must confirm completion before this transition; partial directory observations during active work are insufficient.
+ * Records an owned install verified by the file store or a completed download activation.
+ * Partial directory observations during active work are insufficient.
*
- * @param id Model identity whose owned payload was verified after joining the transfer.
+ * @param id Model identity whose complete owned payload has been verified.
* @param type Provider owning the completed payload and its deletion/transfer markers.
*
* @author Dmitriy Moroz
diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupDownloadBatchState.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupDownloadBatchState.kt
new file mode 100644
index 000000000..7644b8c5c
--- /dev/null
+++ b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupDownloadBatchState.kt
@@ -0,0 +1,32 @@
+package com.shifthackz.aisdv1.presentation.configuration.setup
+
+import com.shifthackz.aisdv1.domain.entity.DownloadState
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadBatch
+
+/**
+ * Restores worker progress without replaying old successful installs over current file state.
+ * @param batches Worker snapshots, including terminal work retained for transition detection.
+ * @author Dmitriy Moroz
+ */
+internal fun ServerSetupState.withModelDownloadBatches(batches: List): ServerSetupState {
+ var result = copy(modelDownloadBatches = batches)
+ modelDownloadBatches.filter { it.isRunning }.forEach { previous ->
+ val model = result.catalogModels(previous.type).firstOrNull { it.id == previous.modelId }
+ if (model != null && model.downloadState is DownloadState.Downloading) result =
+ result.withUpdatedLocalModel(
+ model.copy(downloadState = DownloadState.Unknown),
+ previous.type
+ )
+ }
+ batches.filter { it.isRunning }.forEach { batch ->
+ batch.completedIds.forEach { id -> result = result.withVerifiedOwnedModel(id, batch.type) }
+ val model = result.catalogModels(batch.type).firstOrNull { it.id == batch.modelId }
+ if (model != null) result = result.withUpdatedLocalModel(
+ model.copy(
+ downloadState = batch.progress ?: DownloadState.Downloading(),
+ downloaded = model.downloaded || batch.progress is DownloadState.Complete,
+ ), batch.type
+ )
+ }
+ return result
+}
diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupIntent.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupIntent.kt
index 170df1282..a1a80152f 100644
--- a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupIntent.kt
+++ b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupIntent.kt
@@ -16,6 +16,15 @@ import com.shifthackz.aisdv1.domain.entity.ServerSourceType
* @author Dmitriy Moroz
*/
sealed interface ServerSetupIntent : MviIntent {
+ /** Downloads missing models of the visible provider in catalog order. */
+ data object DownloadAllModels : ServerSetupIntent
+
+ /** Replaces current provider downloads with the destination captured by the confirmation dialog. */
+ data object ConfirmModelDownloadSwitch : ServerSetupIntent
+
+ /** Stops the background batch while retaining completed models. */
+ data object CancelModelDownloads : ServerSetupIntent
+
/**
* Retries only the catalog whose recovery action was selected.
*
diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupState.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupState.kt
index 7a3cdb2bc..7d63a5a46 100644
--- a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupState.kt
+++ b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupState.kt
@@ -6,6 +6,7 @@ import com.shifthackz.aisdv1.core.mvi.MviState
import com.shifthackz.aisdv1.domain.entity.AuthorizationStorageFailure
import com.shifthackz.aisdv1.domain.entity.Configuration
import com.shifthackz.aisdv1.domain.entity.DownloadState
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadBatch
import com.shifthackz.aisdv1.domain.entity.FeatureTag
import com.shifthackz.aisdv1.domain.entity.HuggingFaceModel
import com.shifthackz.aisdv1.domain.entity.LocalAiModel
@@ -21,6 +22,8 @@ import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationCredentials
* per-provider form inputs, and the local model lists mirror downloadable model state for each
* local runtime. Derived properties expose the active provider's local model selection.
*
+ * @param modelDownloadBatches Independent single downloads and the exclusive provider batch.
+ * @param refreshingLocalCatalogs Providers refreshing metadata while retaining feedback layout.
* @param showBackNavArrow Whether this setup flow may return to its opening screen.
* @param step Current provider-selection or provider-configuration stage.
* @param mode Selected provider whose visible controls and generation dispatch apply.
@@ -102,6 +105,8 @@ import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationCredentials
*/
@Immutable
data class ServerSetupState(
+ val modelDownloadBatches: List = emptyList(),
+ val refreshingLocalCatalogs: Set = emptySet(),
val showBackNavArrow: Boolean = false,
val step: Step = Step.SOURCE,
val mode: ServerSource = ServerSource.AUTOMATIC1111,
@@ -467,6 +472,13 @@ data class ServerSetupState(
}
sealed interface Modal {
+ /**
+ * Retains the destination provider until a conflicting batch replacement is confirmed.
+ * @param type Provider whose missing models should replace current download work.
+ * @author Dmitriy Moroz
+ */
+ data class SwitchModelDownloads(val type: LocalAiModel.Type) : Modal
+
data object ConnectionUnverified : Modal
data object None : Modal
data object Communicating : Modal
diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupViewModel.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupViewModel.kt
index 5f3575c12..8236f0570 100644
--- a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupViewModel.kt
+++ b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupViewModel.kt
@@ -15,10 +15,6 @@ import com.shifthackz.aisdv1.presentation.components.model.localizedDescription
import com.shifthackz.aisdv1.presentation.components.model.observeOpenAiOAuthIdentity
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.cancel
-import kotlinx.coroutines.cancelAndJoin
-import kotlinx.coroutines.isActive
-import kotlinx.coroutines.flow.MutableStateFlow
-import kotlinx.coroutines.flow.update
import com.shifthackz.aisdv1.domain.usecase.downloadable.GetCachedLocalModelCatalogUseCase
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.currentCoroutineContext
@@ -28,7 +24,9 @@ import com.shifthackz.aisdv1.core.mvi.BaseMviViewModel
import com.shifthackz.aisdv1.core.validation.common.CommonStringValidator
import com.shifthackz.aisdv1.core.validation.path.FilePathValidator
import com.shifthackz.aisdv1.core.validation.url.UrlValidator
+import com.shifthackz.aisdv1.domain.entity.ModelDownloadRequest
import com.shifthackz.aisdv1.domain.entity.DownloadState
+import com.shifthackz.aisdv1.domain.feature.work.ModelDownloadManager
import com.shifthackz.aisdv1.domain.entity.HuggingFaceModel
import com.shifthackz.aisdv1.domain.entity.OpenAiCompatibleConnection
import com.shifthackz.aisdv1.domain.entity.LocalAiModel
@@ -41,7 +39,6 @@ import com.shifthackz.aisdv1.domain.usecase.settings.SetServerConfigurationUseCa
import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationCredentials
import com.shifthackz.aisdv1.domain.preference.PreferenceManager
import com.shifthackz.aisdv1.domain.usecase.downloadable.DeleteModelUseCase
-import com.shifthackz.aisdv1.domain.usecase.downloadable.DownloadModelUseCase
import com.shifthackz.aisdv1.domain.usecase.downloadable.RefreshLocalModelCatalogUseCase
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
@@ -64,16 +61,12 @@ import com.shifthackz.aisdv1.domain.usecase.settings.ConnectToSwarmUiUseCase
import com.shifthackz.aisdv1.domain.usecase.settings.GetConfigurationUseCase
import com.shifthackz.aisdv1.core.navigation.LaunchSource
import com.shifthackz.aisdv1.core.navigation.router.ServerSetupRouter
-import com.shifthackz.aisdv1.presentation.configuration.setup.platform.ServerSetupDownloadGuard
import com.shifthackz.aisdv1.presentation.configuration.setup.reducer.ServerSetupIntentProcessor
import com.shifthackz.aisdv1.presentation.configuration.setup.validation.validateServerSetup
import com.shifthackz.aisdv1.presentation.configuration.setup.viewmodel.HUGGING_FACE_MODELS_TIMEOUT_MILLIS
import com.shifthackz.aisdv1.domain.entity.setupAllowedModes
import com.shifthackz.aisdv1.presentation.components.service.storage.StorageUsageObserver
-import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Job
-import kotlinx.coroutines.flow.catch
-import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import kotlin.coroutines.cancellation.CancellationException
@@ -109,9 +102,8 @@ import kotlin.time.Duration.Companion.milliseconds
* @param connectToStabilityAiUseCase Applies Stability AI configuration.
* @param connectToFalAiUseCase Applies Fal AI configuration.
* @param connectToArliAiUseCase Validates ArliAI credentials and publishes the selected remote source.
- * @param downloadModelUseCase Downloads a selected local model.
+ * @param modelDownloadManager Owns concurrent single downloads or an exclusive sequential batch independently of setup.
* @param deleteModelUseCase Deletes a selected local model.
- * @param downloadGuard Platform guard for model download prerequisites.
* @param storageUsageObserver Invalidates Settings storage summaries after model changes.
* @param linksProvider External links and demo mode URL used by setup.
* @param preferenceManager Persists setup preferences.
@@ -152,9 +144,8 @@ class ServerSetupViewModel(
private val connectToStabilityAiUseCase: ConnectToStabilityAiUseCase,
private val connectToFalAiUseCase: ConnectToFalAiUseCase,
private val connectToArliAiUseCase: ConnectToArliAiUseCase,
- private val downloadModelUseCase: DownloadModelUseCase,
+ private val modelDownloadManager: ModelDownloadManager,
private val deleteModelUseCase: DeleteModelUseCase,
- private val downloadGuard: ServerSetupDownloadGuard,
private val storageUsageObserver: StorageUsageObserver,
private val linksProvider: LinksProvider,
private val preferenceManager: PreferenceManager,
@@ -176,9 +167,6 @@ class ServerSetupViewModel(
effectDispatcher = dispatchersProvider.immediate,
) {
- private val downloadJobs =
- MutableStateFlow