From a1c714a668255973637a959ee0e275fb91725d78 Mon Sep 17 00:00:00 2001 From: ShiftHackZ Date: Wed, 18 Nov 2026 23:45:10 +0200 Subject: [PATCH 1/2] Add background model downloads and batch controls --- .../src/androidMain/res/values-de/strings.xml | 9 +- .../src/androidMain/res/values-ru/strings.xml | 9 +- .../src/androidMain/res/values-tr/strings.xml | 9 +- .../src/androidMain/res/values-uk/strings.xml | 9 +- .../src/androidMain/res/values-zh/strings.xml | 9 +- .../src/androidMain/res/values/strings.xml | 9 +- .../AndroidDownloadableModelFileStore.kt | 79 ++--- .../AndroidDownloadableModelFileDownloader.kt | 5 +- .../aisdv1/domain/di/DomainCoreModule.kt | 5 +- .../domain/entity/ModelDownloadBatch.kt | 38 +++ .../domain/entity/ModelDownloadRequest.kt | 24 ++ .../feature/work/ModelDownloadManager.kt | 38 +++ .../downloadable/DownloadModelUseCaseImpl.kt | 27 +- .../downloadable/DownloadModelsUseCase.kt | 18 ++ .../downloadable/DownloadModelsUseCaseImpl.kt | 59 ++++ .../aisdv1/work/ModelDownloadManagerImpl.kt | 152 +++++++++ .../aisdv1/work/core/NotificationWorker.kt | 48 +-- .../aisdv1/work/di/BackgroundWorkModule.kt | 5 +- .../aisdv1/work/di/SdaiWorkerFactory.kt | 12 + .../aisdv1/work/task/DownloadModelsTask.kt | 91 ++++++ .../aisdv1/work/ModelDownloadManagerImpl.kt | 119 +++++++ .../aisdv1/work/di/BackgroundWorkModule.kt | 13 +- .../presentation/app/di/PresentationModule.kt | 2 - .../app/di/PresentationCoreModule.kt | 2 - .../di/ConfigurationUiUtilsModule.kt | 17 - .../AndroidServerSetupDownloadGuard.kt | 17 - .../setup/ServerSetupCatalogRefreshTest.kt | 79 +++-- .../di/ConfigurationCoreModule.kt | 14 - .../di/ConfigurationViewModelModule.kt | 3 +- .../setup/ServerSetupCatalogState.kt | 10 +- .../setup/ServerSetupDownloadBatchState.kt | 32 ++ .../configuration/setup/ServerSetupIntent.kt | 9 + .../configuration/setup/ServerSetupState.kt | 12 + .../setup/ServerSetupViewModel.kt | 302 +++++++++--------- .../component/LocalModelDownloadAction.kt | 74 +++++ .../setup/component/OpenAiOAuthActionBar.kt | 42 +-- .../setup/component/ServerSetupWidgets.kt | 16 + .../setup/component/SetupActionBar.kt | 87 +++++ .../setup/content/ServerSetupContent.kt | 58 ++-- .../form/local/LocalCatalogStatusCard.kt | 43 ++- .../form/local/LocalModelShimmerItems.kt | 27 ++ .../setup/form/local/ServerSetupLocalForms.kt | 13 +- .../form/local/ServerSetupLocalModels.kt | 17 + .../platform/NoOpServerSetupDownloadGuard.kt | 10 - .../platform/ServerSetupDownloadGuard.kt | 22 -- .../reducer/ServerSetupIntentProcessor.kt | 3 + 46 files changed, 1257 insertions(+), 441 deletions(-) create mode 100644 domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/ModelDownloadBatch.kt create mode 100644 domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/ModelDownloadRequest.kt create mode 100644 domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/feature/work/ModelDownloadManager.kt create mode 100644 domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelsUseCase.kt create mode 100644 domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelsUseCaseImpl.kt create mode 100644 feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/ModelDownloadManagerImpl.kt create mode 100644 feature/work/src/androidMain/kotlin/com/shifthackz/aisdv1/work/task/DownloadModelsTask.kt create mode 100644 feature/work/src/iosMain/kotlin/com/shifthackz/aisdv1/work/ModelDownloadManagerImpl.kt delete mode 100644 presentation/configuration/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/di/ConfigurationUiUtilsModule.kt delete mode 100644 presentation/configuration/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/platform/AndroidServerSetupDownloadGuard.kt delete mode 100644 presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/di/ConfigurationCoreModule.kt create mode 100644 presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupDownloadBatchState.kt create mode 100644 presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/LocalModelDownloadAction.kt create mode 100644 presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/SetupActionBar.kt create mode 100644 presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/form/local/LocalModelShimmerItems.kt delete mode 100644 presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/platform/NoOpServerSetupDownloadGuard.kt delete mode 100644 presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/platform/ServerSetupDownloadGuard.kt 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/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/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/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..982cf5b11 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,30 @@ 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() + batches.value = 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 +235,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 +250,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 +284,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 +294,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 +305,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 +315,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 +327,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 +337,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 +351,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)) @@ -379,9 +409,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/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, Job>>(emptyMap()) - private val downloadCancellationMutex = Mutex() private val catalogRefreshMutex = Mutex() private val refreshingCatalogs = mutableSetOf() private var oauthLoginJob: Job? = null @@ -253,6 +241,31 @@ class ServerSetupViewModel( ) ) } + launch(dispatchersProvider.io) { + modelDownloadManager.batches.collect { batches -> + val previous = currentState.modelDownloadBatches + updateState { state -> state.withModelDownloadBatches(batches) } + val completed = batches.filter { batch -> + !batch.isRunning && previous.any { it.workId == batch.workId && it.isRunning } + } + completed.forEach { batch -> + val failure = (batch.progress as? DownloadState.Error)?.error + if (failure != null) { + onError(failure) + updateState { + it.copy( + modal = ServerSetupState.Modal.Error( + failure.message + ?: Localization.string("error_title") + ) + ) + } + } + storageUsageObserver.notifyChanged() + reconcileLocalModelOwnership(batch.type) + } + } + } currentState.allowedModes.forEach(::refreshLocalCatalog) } .onFailure { t -> @@ -294,6 +307,56 @@ class ServerSetupViewModel( override fun processIntent(intent: ServerSetupIntent) { when (intent) { + ServerSetupIntent.DownloadAllModels -> { + val type = currentState.mode.localCatalogType ?: return + val active = currentState.modelDownloadBatches.filter { it.isRunning } + if (active.any { it.type != type }) { + updateState { it.copy(modal = ServerSetupState.Modal.SwitchModelDownloads(type)) } + return + } + launch(dispatchersProvider.io) { + try { + if (active.isEmpty()) modelDownloadManager.start(ModelDownloadRequest(type)) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (failure: Exception) { + onError(failure) + } + } + return + } + + ServerSetupIntent.ConfirmModelDownloadSwitch -> { + val modal = + currentState.modal as? ServerSetupState.Modal.SwitchModelDownloads ?: return + updateState { it.copy(modal = ServerSetupState.Modal.None) } + launch(dispatchersProvider.io) { + try { + modelDownloadManager.start( + ModelDownloadRequest(modal.type), + shouldReplace = true + ) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (failure: Exception) { + onError(failure) + updateState { + it.copy( + modal = ServerSetupState.Modal.Error( + failure.message ?: Localization.string("error_title") + ) + ) + } + } + } + return + } + + ServerSetupIntent.CancelModelDownloads -> { + launch(dispatchersProvider.io) { modelDownloadManager.cancel() } + return + } + is ServerSetupIntent.RetryLocalCatalog -> { refreshLocalCatalog(intent.source); return } @@ -386,11 +449,17 @@ class ServerSetupViewModel( launch(dispatchersProvider.io) { val canRefresh = catalogRefreshMutex.withLock { refreshingCatalogs.add(type) } if (!canRefresh) return@launch - updateState { it.copy(localCatalogStatuses = it.localCatalogStatuses + (type to LocalCatalogStatus.LOADING)) } + updateState { it.copy(refreshingLocalCatalogs = it.refreshingLocalCatalogs + type) } try { val cached = getCachedLocalModelCatalogUseCase(type) currentCoroutineContext().ensureActive() - updateState { it.withCatalogResult(type, cached, LocalCatalogStatus.LOADING) } + updateState { + it.withCatalogResult( + type, + cached, + it.localCatalogStatuses[type] ?: LocalCatalogStatus.LOADING + ) + } val result = refreshLocalModelCatalogUseCase(type) currentCoroutineContext().ensureActive() updateState { state -> @@ -408,7 +477,32 @@ class ServerSetupViewModel( onError(failure) } finally { catalogRefreshMutex.withLock { refreshingCatalogs.remove(type) } + currentCoroutineContext().ensureActive() + updateState { it.copy(refreshingLocalCatalogs = it.refreshingLocalCatalogs - type) } + } + } + } + + /** + * Reads installed files after work stops without restarting network refresh or loading UI. + * @param type Provider whose ownership may have changed during activation or cleanup. + * @author Dmitriy Moroz + */ + private suspend fun reconcileLocalModelOwnership(type: LocalAiModel.Type) { + try { + val cached = getCachedLocalModelCatalogUseCase(type) + currentCoroutineContext().ensureActive() + updateState { + it.withCatalogResult( + type, + cached, + it.localCatalogStatuses[type] ?: LocalCatalogStatus.READY + ) } + } catch (cancelled: CancellationException) { + throw cancelled + } catch (failure: Exception) { + onError(failure) } } @@ -788,9 +882,21 @@ class ServerSetupViewModel( */ private fun localModelDownloadClickReducer(value: ServerSetupState.LocalModel) { val type = currentState.mode.localCatalogType ?: return + val active = currentState.modelDownloadBatches.filter { it.isRunning } + if (active.any { it.isBatch }) return + if (active.any { it.type == type && it.modelId == value.id }) { + launch(dispatchersProvider.io) { modelDownloadManager.cancel(type, value.id) } + return + } val model = currentState.catalogModels(type).firstOrNull { it.id == value.id } ?: return when { - model.downloadState is DownloadState.Downloading -> cancelDownload(model.id, type) + model.downloadState is DownloadState.Downloading -> launch(dispatchersProvider.io) { + modelDownloadManager.cancel( + type, + model.id + ) + } + model.downloaded -> updateState { it.copy( modal = ServerSetupState.Modal.DeleteLocalModelConfirm( @@ -812,143 +918,33 @@ class ServerSetupViewModel( } /** - * Cancels and joins only the owning transfer before removing partial files; completed installs survive late Cancel. - * - * @param id Stable model identity whose active transfer is cancelled. - * @param type Provider captured when the action was requested. - * - * @author Dmitriy Moroz - */ - private fun cancelDownload(id: String, type: LocalAiModel.Type) { - launch(dispatchersProvider.io) { - try { - downloadCancellationMutex.withLock { - val job = downloadJobs.value[type to id] ?: return@withLock - job.cancelAndJoin() - if (currentState.catalogModels(type) - .firstOrNull { it.id == id }?.downloaded == true - ) return@withLock - val owned = getCachedLocalModelCatalogUseCase(type).firstOrNull { it.id == id } - if (owned?.downloaded == true) { - updateState { it.withVerifiedOwnedModel(id, type) } - storageUsageObserver.notifyChanged() - return@withLock - } - deleteModelUseCase(id) - updateState { state -> - val current = state.catalogModels(type).firstOrNull { it.id == id } - ?: return@updateState state - state.withDeletedLocalModel(current, type) - } - storageUsageObserver.notifyChanged() - } - } catch (cancelled: CancellationException) { - throw cancelled - } catch (failure: Exception) { - onDownloadFailure(id, type, failure) - } - } - } - - /** - * Starts the confirmed source-owned model transfer once, independent of subsequent mode changes. - * - * @param modelId Stable model identifier associated with the chosen download. - * @param url Chosen archive mirror. - * @param type Provider captured when its source picker opened. - * + * Schedules the selected archive in platform work, retaining ownership after setup closes. + * @param modelId Stable identity of the model selected in the source picker. + * @param url Confirmed catalog mirror for that single model. + * @param type Provider captured when the source picker opened. * @author Dmitriy Moroz */ private fun download(modelId: String, url: String, type: LocalAiModel.Type) { + if (currentState.modelDownloadBatches.any { it.isRunning && (it.isBatch || it.type == type && it.modelId == modelId) }) return val model = currentState.catalogModels(type).firstOrNull { it.id == modelId } ?: return - if (model.downloaded || downloadJobs.value[type to modelId]?.isActive == true) return - updateState { state -> - val current = state.catalogModels(type).firstOrNull { it.id == modelId } - ?: return@updateState state - state.copy(modal = ServerSetupState.Modal.None) - .withUpdatedLocalModel( - current.copy(downloadState = DownloadState.Downloading()), - type - ) - } - val job = scopeLaunchDownload(modelId, url, type) - downloadJobs.update { it + ((type to modelId) to job) } - job.start() - } - - /** - * Publishes progress into the captured provider using its current selection, never the download-start snapshot. - * - * @param id Stable model identity being transferred. - * @param url Chosen archive source. - * @param type Runtime owning every progress, completion and error callback. - * - * @author Dmitriy Moroz - */ - private fun scopeLaunchDownload(id: String, url: String, type: LocalAiModel.Type): Job = - launch(dispatchersProvider.io, start = CoroutineStart.LAZY) { + if (model.downloaded) return + updateState { it.copy(modal = ServerSetupState.Modal.None) } + launch(dispatchersProvider.io) { try { - downloadGuard.withDownload { - downloadModelUseCase(id, url).distinctUntilChanged().catch { failure -> - if (failure is CancellationException) throw failure - onDownloadFailure(id, type, failure) - }.collect { progress -> - currentCoroutineContext().ensureActive() - updateState { state -> - val current = state.catalogModels(type).firstOrNull { it.id == id } - ?: return@updateState state - state.withUpdatedLocalModel( - current.copy( - downloadState = progress, - downloaded = progress is DownloadState.Complete - ), type - ) - } - if (progress is DownloadState.Complete) storageUsageObserver.notifyChanged() - } - } + modelDownloadManager.start(ModelDownloadRequest(type, modelId, url)) } catch (cancelled: CancellationException) { throw cancelled } catch (failure: Exception) { - onDownloadFailure(id, type, failure) - } finally { - val job = currentCoroutineContext()[Job] - downloadJobs.update { jobs -> if (jobs[type to id] == job) jobs - (type to id) else jobs } - if (currentCoroutineContext().isActive) updateState { state -> - val current = state.catalogModels(type).firstOrNull { it.id == id } - ?: return@updateState state - if (current.downloadState is DownloadState.Downloading) state.withUpdatedLocalModel( - current.copy(downloadState = DownloadState.Unknown), - type - ) else state + onError(failure) + updateState { + it.copy( + modal = ServerSetupState.Modal.Error( + failure.message ?: Localization.string("error_title") + ) + ) } } } - - /** - * Keeps an archive failure with its owning item and reports it through the existing error sink. - * - * @param id Stable model identity whose transfer failed. - * @param type Provider that started the transfer. - * @param failure Underlying download failure. - * - * @author Dmitriy Moroz - */ - private fun onDownloadFailure(id: String, type: LocalAiModel.Type, failure: Throwable) { - updateState { state -> - val current = - state.catalogModels(type).firstOrNull { it.id == id } ?: return@updateState state - state.withUpdatedLocalModel( - current.copy(downloadState = DownloadState.Error(failure)), - type - ) - .copy( - modal = ServerSetupState.Modal.Error( - failure.message ?: Localization.string("error_title") - ) - ) - } - onError(failure) } /** @@ -963,16 +959,14 @@ class ServerSetupViewModel( updateState { it.copy(modal = ServerSetupState.Modal.None) } launch(dispatchersProvider.io) { try { - downloadCancellationMutex.withLock { - downloadJobs.value[type to id]?.cancelAndJoin() - deleteModelUseCase(id) - updateState { state -> - val current = state.catalogModels(type).firstOrNull { it.id == id } - ?: return@updateState state - state.withDeletedLocalModel(current, type) - } - storageUsageObserver.notifyChanged() + if (currentState.modelDownloadBatches.any { it.isRunning && (it.isBatch || it.type == type && it.modelId == id) }) return@launch + deleteModelUseCase(id) + updateState { state -> + val current = state.catalogModels(type).firstOrNull { it.id == id } + ?: return@updateState state + state.withDeletedLocalModel(current, type) } + storageUsageObserver.notifyChanged() } catch (cancelled: CancellationException) { throw cancelled } catch (failure: Exception) { diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/LocalModelDownloadAction.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/LocalModelDownloadAction.kt new file mode 100644 index 000000000..b5ce18893 --- /dev/null +++ b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/LocalModelDownloadAction.kt @@ -0,0 +1,74 @@ +package com.shifthackz.aisdv1.presentation.configuration.setup.component + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.expandVertically +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.shrinkVertically +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Download +import androidx.compose.material.icons.outlined.StopCircle +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.shifthackz.aisdv1.core.localization.Localization +import com.shifthackz.aisdv1.presentation.configuration.setup.LocalCatalogStatus +import com.shifthackz.aisdv1.presentation.configuration.setup.ServerSetupIntent +import com.shifthackz.aisdv1.presentation.configuration.setup.ServerSetupState +import com.shifthackz.aisdv1.presentation.configuration.setup.localCatalogType + +/** + * Animates the batch action and its footer gap together, keeping Setup at a fixed bottom position. + * Hides the start action during single-model work of this provider and when no catalog models are missing. + * The current batch always retains its cancellation action until work terminates. + * @param state Current provider catalog and application-owned batch status. + * @param processIntent Dispatches start, replacement confirmation or cancellation through MVI. + * @param modifier Layout modifiers for the secondary action. + * @author Dmitriy Moroz + */ +@Composable +internal fun LocalModelDownloadAction( + state: ServerSetupState, + processIntent: (ServerSetupIntent) -> Unit, + modifier: Modifier = Modifier, +) { + val type = state.mode.localCatalogType ?: return + val active = state.modelDownloadBatches.filter { it.isRunning } + val isWorkRunning = active.isNotEmpty() + val isCurrentBatch = active.any { it.isBatch && it.type == type } + val hasMissingModels = + state.localModels.any { !it.isCustom && !it.downloaded && it.sources.isNotEmpty() } + val canStart = state.localCatalogStatuses[type] == LocalCatalogStatus.READY && + !isWorkRunning && hasMissingModels + val hasSingleDownload = active.any { !it.isBatch && it.type == type } + val shouldShowAction = isCurrentBatch || (hasMissingModels && !hasSingleDownload) + AnimatedVisibility( + visible = shouldShowAction, + modifier = modifier, + enter = expandVertically() + fadeIn(), + exit = shrinkVertically() + fadeOut(), + ) { + Column { + SetupSecondaryAction( + isEnabled = !state.loadingConfiguration && (isWorkRunning || canStart), + onClick = { processIntent(if (isCurrentBatch) ServerSetupIntent.CancelModelDownloads else ServerSetupIntent.DownloadAllModels) }, + ) { + Icon( + imageVector = if (isCurrentBatch) Icons.Outlined.StopCircle else Icons.Outlined.Download, + contentDescription = null, + modifier = Modifier.size(20.dp), + ) + Spacer(Modifier.width(8.dp)) + Text(Localization.string(if (isCurrentBatch) "download_cancel_all" else "download_all")) + } + Spacer(Modifier.height(8.dp)) + } + } +} diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/OpenAiOAuthActionBar.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/OpenAiOAuthActionBar.kt index ea3c31370..2cf095fa0 100644 --- a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/OpenAiOAuthActionBar.kt +++ b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/OpenAiOAuthActionBar.kt @@ -1,26 +1,15 @@ package com.shifthackz.aisdv1.presentation.configuration.setup.component -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.windowInsetsPadding -import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier -import androidx.compose.ui.unit.dp import com.shifthackz.aisdv1.core.localization.Localization import com.shifthackz.aisdv1.presentation.configuration.setup.content.ServerSetupStrings import com.shifthackz.aisdv1.presentation.configuration.setup.OpenAiOAuthSetupPhase import com.shifthackz.aisdv1.presentation.configuration.setup.ServerSetupIntent import com.shifthackz.aisdv1.presentation.configuration.setup.ServerSetupState import com.shifthackz.aisdv1.presentation.configuration.setup.openAiOAuthPhase -import com.shifthackz.aisdv1.presentation.components.theme.global.persistentBottomBarWindowInsets /** * Pins only the actions available in the current OAuth phase below the scrolling form. @@ -40,18 +29,11 @@ internal fun OpenAiOAuthActionBar( processIntent: (ServerSetupIntent) -> Unit, modifier: Modifier = Modifier, ) { - Column( - modifier = modifier - .fillMaxWidth() - .background(MaterialTheme.colorScheme.background) - .windowInsetsPadding(persistentBottomBarWindowInsets()) - .padding(horizontal = 16.dp, vertical = 8.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { + SetupActionBar(modifier = modifier) { when (state.openAiOAuthPhase) { OpenAiOAuthSetupPhase.SIGNED_OUT -> OAuthPrimaryAction( label = Localization.string("open_ai_oauth_login"), - enabled = !state.loadingConfiguration, + isEnabled = !state.loadingConfiguration, onClick = { processIntent(ServerSetupIntent.OAuthLogin) }, ) @@ -74,7 +56,7 @@ internal fun OpenAiOAuthActionBar( OpenAiOAuthSetupPhase.SIGNED_IN -> { OAuthPrimaryAction( label = strings.connect, - enabled = !state.loadingConfiguration && state.mainButtonEnabled, + isEnabled = !state.loadingConfiguration && state.mainButtonEnabled, onClick = { processIntent(ServerSetupIntent.MainButtonClick) }, ) OAuthSecondaryAction( @@ -85,7 +67,7 @@ internal fun OpenAiOAuthActionBar( OpenAiOAuthSetupPhase.STORAGE_ERROR -> OAuthPrimaryAction( label = Localization.string("open_ai_oauth_reset"), - enabled = !state.loadingConfiguration, + isEnabled = !state.loadingConfiguration, onClick = { processIntent(ServerSetupIntent.OAuthLogout) }, ) } @@ -96,7 +78,8 @@ internal fun OpenAiOAuthActionBar( * Renders one full-width primary action without constraining multiline label height. * * @param label Localized visible and accessible action name. - * @param enabled Whether the action can currently be submitted. + * @param modifier Layout modifiers for the shared action button. + * @param isEnabled Whether the action can currently be submitted. * @param onClick Action callback. * * @author Dmitriy Moroz @@ -105,12 +88,12 @@ internal fun OpenAiOAuthActionBar( private fun OAuthPrimaryAction( label: String, modifier: Modifier = Modifier, - enabled: Boolean = true, + isEnabled: Boolean = true, onClick: () -> Unit, ) { - Button( - modifier = modifier.fillMaxWidth().heightIn(min = 48.dp), - enabled = enabled, + SetupPrimaryAction( + modifier = modifier, + isEnabled = isEnabled, onClick = onClick, ) { Text(text = label, style = MaterialTheme.typography.labelLarge) @@ -122,6 +105,7 @@ private fun OAuthPrimaryAction( * * @param label Localized visible and accessible action name. * @param onClick Action callback. + * @param modifier Layout modifiers for the shared action button. * * @author Dmitriy Moroz */ @@ -131,8 +115,8 @@ private fun OAuthSecondaryAction( onClick: () -> Unit, modifier: Modifier = Modifier, ) { - OutlinedButton( - modifier = modifier.fillMaxWidth().heightIn(min = 48.dp), + SetupSecondaryAction( + modifier = modifier, onClick = onClick, ) { Text(text = label, style = MaterialTheme.typography.labelLarge) diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/ServerSetupWidgets.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/ServerSetupWidgets.kt index 8ca19f86b..b977a077a 100644 --- a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/ServerSetupWidgets.kt +++ b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/ServerSetupWidgets.kt @@ -86,6 +86,22 @@ internal fun ServerSetupModal( processIntent: (ServerSetupIntent) -> Unit, ) { when (modal) { + is ServerSetupState.Modal.SwitchModelDownloads -> AlertDialog( + onDismissRequest = { processIntent(ServerSetupIntent.DismissDialog) }, + title = { Text(Localization.string("download_switch_title")) }, + text = { Text(Localization.string("download_switch_message")) }, + confirmButton = { + TextButton(onClick = { processIntent(ServerSetupIntent.ConfirmModelDownloadSwitch) }) { + Text(Localization.string("download_switch_confirm")) + } + }, + dismissButton = { + TextButton(onClick = { processIntent(ServerSetupIntent.DismissDialog) }) { + Text(Localization.string("close")) + } + }, + ) + ServerSetupState.Modal.ConnectionUnverified -> AlertDialog( onDismissRequest = { processIntent(ServerSetupIntent.AcknowledgeUnverifiedConnection) }, title = { Text(strings.connectionUnverifiedTitle) }, diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/SetupActionBar.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/SetupActionBar.kt new file mode 100644 index 000000000..52f6cf9a3 --- /dev/null +++ b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/SetupActionBar.kt @@ -0,0 +1,87 @@ +package com.shifthackz.aisdv1.presentation.configuration.setup.component + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.material3.Button +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.shifthackz.aisdv1.presentation.components.theme.global.persistentBottomBarWindowInsets + +/** + * Gives every setup provider identical horizontal margins, action spacing and bottom safe-area padding. + * @param modifier Bounds applied to the pinned action column. + * @param verticalArrangement Spacing between actions; animated actions may own their collapsing gap. + * @param content Primary and secondary actions, in display order. + * @author Dmitriy Moroz + */ +@Composable +internal fun SetupActionBar( + modifier: Modifier = Modifier, + verticalArrangement: Arrangement.Vertical = Arrangement.spacedBy(8.dp), + content: @Composable ColumnScope.() -> Unit, +) { + Column( + modifier = modifier.fillMaxWidth() + .background(MaterialTheme.colorScheme.background) + .windowInsetsPadding(persistentBottomBarWindowInsets()) + .padding(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 16.dp), + verticalArrangement = verticalArrangement, + content = content, + ) +} + +/** + * Uses the same full-width primary button geometry for Next, Connect, Setup and OAuth actions. + * @param onClick Dispatches the selected action. + * @param modifier Layout modifiers applied before the common button dimensions. + * @param isEnabled Whether this action is currently available. + * @param content Visible label and optional decorative icon. + * @author Dmitriy Moroz + */ +@Composable +internal fun SetupPrimaryAction( + onClick: () -> Unit, + modifier: Modifier = Modifier, + isEnabled: Boolean = true, + content: @Composable RowScope.() -> Unit, +) { + Button( + onClick = onClick, + modifier = modifier.fillMaxWidth().heightIn(min = 48.dp), + enabled = isEnabled, + content = content + ) +} + +/** + * Matches primary action dimensions while retaining the outlined treatment for secondary operations. + * @param onClick Dispatches the selected action. + * @param modifier Layout modifiers applied before the common button dimensions. + * @param isEnabled Whether this action is currently available. + * @param content Visible label and optional decorative icon. + * @author Dmitriy Moroz + */ +@Composable +internal fun SetupSecondaryAction( + onClick: () -> Unit, + modifier: Modifier = Modifier, + isEnabled: Boolean = true, + content: @Composable RowScope.() -> Unit, +) { + OutlinedButton( + onClick = onClick, + modifier = modifier.fillMaxWidth().heightIn(min = 48.dp), + enabled = isEnabled, + content = content + ) +} diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/content/ServerSetupContent.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/content/ServerSetupContent.kt index 8d3f4052b..1bd67e3b4 100644 --- a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/content/ServerSetupContent.kt +++ b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/content/ServerSetupContent.kt @@ -2,23 +2,18 @@ package com.shifthackz.aisdv1.presentation.configuration.setup.content -import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.outlined.ArrowBack -import androidx.compose.material3.Button import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton -import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.SheetValue @@ -29,7 +24,10 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.RectangleShape -import androidx.compose.ui.unit.dp +import com.shifthackz.aisdv1.presentation.configuration.setup.component.LocalModelDownloadAction +import com.shifthackz.aisdv1.presentation.configuration.setup.component.SetupActionBar +import com.shifthackz.aisdv1.presentation.configuration.setup.component.SetupPrimaryAction +import com.shifthackz.aisdv1.presentation.configuration.setup.localCatalogType import com.shifthackz.aisdv1.domain.entity.ServerSource import com.shifthackz.aisdv1.presentation.configuration.setup.component.ConfigurationStepBar import com.shifthackz.aisdv1.presentation.configuration.setup.component.OpenAiOAuthActionBar @@ -43,7 +41,6 @@ import com.shifthackz.aisdv1.presentation.configuration.setup.source.SourceFilte import com.shifthackz.aisdv1.presentation.configuration.setup.source.SourceSelectionEffects import com.shifthackz.aisdv1.presentation.configuration.setup.source.SourceSelectionStep import com.shifthackz.aisdv1.presentation.configuration.setup.source.SourceSortBottomSheet -import com.shifthackz.aisdv1.presentation.components.theme.global.persistentBottomBarWindowInsets import com.shifthackz.aisdv1.presentation.components.theme.global.persistentTopAppBarWindowInsets /** @@ -111,31 +108,28 @@ fun ServerSetupContent( processIntent = processIntent ) } else { - Button( - modifier = Modifier - .windowInsetsPadding(persistentBottomBarWindowInsets()) - .fillMaxWidth() - .height(68.dp) - .background(MaterialTheme.colorScheme.background) - .padding(horizontal = 16.dp) - .padding(bottom = 16.dp, top = 8.dp), - enabled = !state.loadingConfiguration && state.mainButtonEnabled, - onClick = { processIntent(ServerSetupIntent.MainButtonClick) }, - ) { - Text( - text = when (state.step) { - ServerSetupState.Step.SOURCE -> strings.next - ServerSetupState.Step.CONFIGURE -> when (state.mode) { - ServerSource.LOCAL_MICROSOFT_ONNX, - ServerSource.LOCAL_GOOGLE_MEDIA_PIPE, - ServerSource.LOCAL_STABLE_DIFFUSION_CPP, - -> strings.setup + SetupActionBar(verticalArrangement = Arrangement.Top) { + if (state.step == ServerSetupState.Step.CONFIGURE && state.mode.localCatalogType != null) { + LocalModelDownloadAction(state, processIntent) + } + SetupPrimaryAction( + isEnabled = !state.loadingConfiguration && state.mainButtonEnabled, + onClick = { processIntent(ServerSetupIntent.MainButtonClick) }, + ) { + Text( + text = when (state.step) { + ServerSetupState.Step.SOURCE -> strings.next + ServerSetupState.Step.CONFIGURE -> when (state.mode) { + ServerSource.LOCAL_MICROSOFT_ONNX, + ServerSource.LOCAL_GOOGLE_MEDIA_PIPE, + ServerSource.LOCAL_STABLE_DIFFUSION_CPP -> strings.setup - else -> strings.connect - } - }, - color = LocalContentColor.current, - ) + else -> strings.connect + } + }, + style = MaterialTheme.typography.labelLarge, + ) + } } } }, diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/form/local/LocalCatalogStatusCard.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/form/local/LocalCatalogStatusCard.kt index da488920e..372788c88 100644 --- a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/form/local/LocalCatalogStatusCard.kt +++ b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/form/local/LocalCatalogStatusCard.kt @@ -8,11 +8,11 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.CloudOff import androidx.compose.material.icons.outlined.Inventory2 -import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton @@ -33,6 +33,7 @@ import com.shifthackz.aisdv1.presentation.configuration.setup.LocalCatalogStatus * Places shared catalog feedback and recovery beside the affected model list, retaining native theme typography. * * @param status Refresh lifecycle of this local provider, with READY used for an empty remote catalog. + * @param isRefreshing Whether a retry is running while this card retains its title, message and action size. * @param onRetry Retries this provider without changing setup inputs or another provider's requests. * @param modifier Layout modifiers for provider-specific catalog feedback and retry. * @@ -41,14 +42,13 @@ import com.shifthackz.aisdv1.presentation.configuration.setup.LocalCatalogStatus @Composable internal fun LocalCatalogStatusCard( status: LocalCatalogStatus, + isRefreshing: Boolean, onRetry: () -> Unit, modifier: Modifier = Modifier, ) { - val isLoading = status == LocalCatalogStatus.LOADING val hasFailed = status == LocalCatalogStatus.ERROR val title = Localization.string( when { - isLoading -> "local_catalog_loading" hasFailed -> "local_catalog_error_title" else -> "local_catalog_empty_title" } @@ -68,16 +68,12 @@ internal fun LocalCatalogStatusCard( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp) ) { - if (isLoading) { - CircularProgressIndicator(modifier = Modifier.size(24.dp), strokeWidth = 2.dp) - } else { - Icon( - imageVector = if (hasFailed) Icons.Outlined.CloudOff else Icons.Outlined.Inventory2, - contentDescription = null, - tint = if (hasFailed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary, - modifier = Modifier.size(24.dp), - ) - } + Icon( + imageVector = if (hasFailed) Icons.Outlined.CloudOff else Icons.Outlined.Inventory2, + contentDescription = null, + tint = if (hasFailed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary, + modifier = Modifier.size(24.dp), + ) Text( title, modifier = Modifier.weight(1f), @@ -85,17 +81,20 @@ internal fun LocalCatalogStatusCard( fontWeight = FontWeight.SemiBold ) } - if (!isLoading) { + Text( + Localization.string(if (hasFailed) "local_catalog_error_body" else "local_catalog_empty_body"), + style = MaterialTheme.typography.bodyMedium, + ) + OutlinedButton( + onClick = onRetry, + enabled = !isRefreshing, + modifier = Modifier.align(Alignment.CenterHorizontally).widthIn(min = 144.dp) + .heightIn(min = 48.dp), + ) { Text( - Localization.string(if (hasFailed) "local_catalog_error_body" else "local_catalog_empty_body"), - style = MaterialTheme.typography.bodyMedium, + Localization.string(if (isRefreshing) "loading" else "retry"), + style = MaterialTheme.typography.labelLarge ) - OutlinedButton( - onClick = onRetry, - modifier = Modifier.align(Alignment.CenterHorizontally).heightIn(min = 48.dp), - ) { - Text(Localization.string("retry"), style = MaterialTheme.typography.labelLarge) - } } } } diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/form/local/LocalModelShimmerItems.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/form/local/LocalModelShimmerItems.kt new file mode 100644 index 000000000..d407d28fd --- /dev/null +++ b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/form/local/LocalModelShimmerItems.kt @@ -0,0 +1,27 @@ +package com.shifthackz.aisdv1.presentation.configuration.setup.form.local + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.unit.dp +import com.shifthackz.aisdv1.core.extensions.shimmer + +/** + * Reserves three rounded model rows while an initially empty catalog is loading. + * @param modifier Layout modifiers for the placeholder list. + * @author Dmitriy Moroz + */ +@Composable +internal fun LocalModelShimmerItems(modifier: Modifier = Modifier) { + Column(modifier = modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) { + repeat(3) { + Box(Modifier.fillMaxWidth().height(68.dp).clip(RoundedCornerShape(16.dp)).shimmer()) + } + } +} diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/form/local/ServerSetupLocalForms.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/form/local/ServerSetupLocalForms.kt index 0ec0bd97c..600fcce6f 100644 --- a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/form/local/ServerSetupLocalForms.kt +++ b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/form/local/ServerSetupLocalForms.kt @@ -153,8 +153,6 @@ internal fun ConfigurationStep( } } -@Composable - /** * Displays downloaded/custom model selection and provider-specific local runtime controls. * @@ -164,6 +162,7 @@ internal fun ConfigurationStep( * * @author Dmitriy Moroz */ +@Composable internal fun LocalGenerationForm( state: ServerSetupState, strings: ServerSetupStrings, @@ -209,16 +208,21 @@ internal fun LocalGenerationForm( } val catalogStatus = state.mode.localCatalogType?.let { state.localCatalogStatuses[it] } ?: LocalCatalogStatus.LOADING - if (catalogStatus != LocalCatalogStatus.READY || catalogModels.isEmpty()) { + if (catalogStatus == LocalCatalogStatus.LOADING && catalogModels.isEmpty()) { + LocalModelShimmerItems() + } else if (catalogStatus == LocalCatalogStatus.ERROR || catalogModels.isEmpty()) { LocalCatalogStatusCard( status = catalogStatus, + isRefreshing = state.mode.localCatalogType in state.refreshingLocalCatalogs, onRetry = { processIntent(ServerSetupIntent.RetryLocalCatalog(state.mode)) }, ) } + val isBatchRunning = state.modelDownloadBatches.any { it.isRunning && it.isBatch } catalogModels.filter { catalogStatus != LocalCatalogStatus.ERROR || it.downloaded || it.downloadState != DownloadState.Unknown } .forEach { model -> LocalModelItem( model = model, + isActionEnabled = !isBatchRunning, selected = model.selected, strings = strings, onSelect = { processIntent(ServerSetupIntent.SelectLocalModel(model)) }, @@ -228,8 +232,6 @@ internal fun LocalGenerationForm( } } -@Composable - /** * Displays the active local provider’s custom model path and validation feedback. * @@ -239,6 +241,7 @@ internal fun LocalGenerationForm( * * @author Dmitriy Moroz */ +@Composable internal fun LocalCustomModelPathForm( state: ServerSetupState, strings: ServerSetupStrings, diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/form/local/ServerSetupLocalModels.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/form/local/ServerSetupLocalModels.kt index 36094e622..71269d7e3 100644 --- a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/form/local/ServerSetupLocalModels.kt +++ b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/form/local/ServerSetupLocalModels.kt @@ -28,6 +28,7 @@ import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.text.font.FontWeight @@ -39,6 +40,17 @@ import com.shifthackz.aisdv1.presentation.configuration.setup.component.isCustom import com.shifthackz.aisdv1.presentation.configuration.setup.content.ServerSetupStrings import com.shifthackz.aisdv1.presentation.configuration.setup.ServerSetupState +/** + * Shows model selection, ownership and the active archive transfer in one catalog row. + * @param model Current catalog metadata and transfer progress. + * @param selected Whether the setup candidate uses this model. + * @param strings Localized row actions and feedback. + * @param onSelect Selects the candidate without changing download ownership. + * @param onAction Downloads, retries, cancels or deletes the model. + * @param modifier Layout and decoration applied to the row surface. + * @param isActionEnabled Prevents conflicting transfers or removal while a batch owns the catalog. + * @author Dmitriy Moroz + */ @Composable internal fun LocalModelItem( model: ServerSetupState.LocalModel, @@ -47,11 +59,13 @@ internal fun LocalModelItem( onSelect: () -> Unit, onAction: () -> Unit, modifier: Modifier = Modifier, + isActionEnabled: Boolean = true, ) { Surface( modifier = modifier .fillMaxWidth() .defaultMinSize(minHeight = 50.dp) + .clip(RoundedCornerShape(16.dp)) .clickable(onClick = onSelect), shape = RoundedCornerShape(16.dp), color = MaterialTheme.colorScheme.surfaceTint.copy(alpha = 0.8f), @@ -90,6 +104,7 @@ internal fun LocalModelItem( model = model, strings = strings, onClick = onAction, + isEnabled = isActionEnabled, ) } } @@ -187,12 +202,14 @@ private fun LocalModelActionButton( strings: ServerSetupStrings, onClick: () -> Unit, modifier: Modifier = Modifier, + isEnabled: Boolean = true, ) { val action = model.action(strings) OutlinedIconButton( modifier = modifier.size(40.dp), onClick = onClick, + enabled = isEnabled, ) { Icon( modifier = Modifier.size(20.dp), diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/platform/NoOpServerSetupDownloadGuard.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/platform/NoOpServerSetupDownloadGuard.kt deleted file mode 100644 index 1334313de..000000000 --- a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/platform/NoOpServerSetupDownloadGuard.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.shifthackz.aisdv1.presentation.configuration.setup.platform - -/** - * Runs downloads directly on platforms that do not require a wake lock. - * - * @author Dmitriy Moroz - */ -internal object NoOpServerSetupDownloadGuard : ServerSetupDownloadGuard { - override suspend fun withDownload(block: suspend () -> T): T = block() -} diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/platform/ServerSetupDownloadGuard.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/platform/ServerSetupDownloadGuard.kt deleted file mode 100644 index 3c14eca3d..000000000 --- a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/platform/ServerSetupDownloadGuard.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.shifthackz.aisdv1.presentation.configuration.setup.platform - -/** - * Runs a model download within the platform safeguard lifetime. - * - * Android holds a wake lock until the operation returns or fails; platforms without a safeguard - * execute the same suspending operation directly. Cancellation and failures propagate to the caller. - * - * @author Dmitriy Moroz - */ -interface ServerSetupDownloadGuard { - /** - * Keeps the platform safeguard active while [block] executes and releases it on completion. - * - * @param block Download operation whose value, failure or cancellation is passed to the caller. - * - * @return The value produced by [block]. - * - * @author Dmitriy Moroz - */ - suspend fun withDownload(block: suspend () -> T): T -} diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/reducer/ServerSetupIntentProcessor.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/reducer/ServerSetupIntentProcessor.kt index 6502fef30..96db58428 100644 --- a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/reducer/ServerSetupIntentProcessor.kt +++ b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/reducer/ServerSetupIntentProcessor.kt @@ -53,6 +53,9 @@ internal class ServerSetupIntentProcessor( fun process(intent: ServerSetupIntent) { when (intent) { + ServerSetupIntent.ConfirmModelDownloadSwitch, + ServerSetupIntent.DownloadAllModels, + ServerSetupIntent.CancelModelDownloads, is ServerSetupIntent.RetryLocalCatalog, ServerSetupIntent.RetryAuthorizationStorage, ServerSetupIntent.RequestAuthorizationReset, From 235db4eed07592465544caa77bdc0e07e9af6cb8 Mon Sep 17 00:00:00 2001 From: ShiftHackZ Date: Thu, 19 Nov 2026 00:14:18 +0200 Subject: [PATCH 2/2] Fix provider wire contracts and report upstream schema gaps --- .../data/local/ModelDownloadMarkerTest.kt | 79 ++++ .../AndroidModelDownloadLifecycleTest.kt | 113 ++++++ .../domain/entity/ModelDownloadBatchTest.kt | 72 ++++ .../domain/entity/ModelDownloadRequestTest.kt | 57 +++ .../DownloadModelUseCaseImplTest.kt | 246 ++++++------ .../DownloadModelsUseCaseImplTest.kt | 320 ++++++++++++++++ .../aisdv1/work/core/CoreGenerationWorker.kt | 7 - .../work/ModelDownloadManagerImplTest.kt | 359 ++++++++++++++++++ .../core/ModelDownloadNotificationTest.kt | 157 ++++++++ .../work/task/DownloadModelsTaskTest.kt | 237 ++++++++++++ .../setup/ServerSetupCatalogRefreshTest.kt | 217 ++++++++++- .../ServerSetupDownloadBatchStateTest.kt | 145 +++++++ .../LocalModelDownloadActionStateTest.kt | 137 +++++++ .../component/LocalModelDownloadAction.kt | 38 +- .../LocalModelDownloadActionState.kt | 16 + 15 files changed, 2067 insertions(+), 133 deletions(-) create mode 100644 data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/local/ModelDownloadMarkerTest.kt create mode 100644 data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/remote/AndroidModelDownloadLifecycleTest.kt create mode 100644 domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/entity/ModelDownloadBatchTest.kt create mode 100644 domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/entity/ModelDownloadRequestTest.kt create mode 100644 domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/downloadable/DownloadModelsUseCaseImplTest.kt create mode 100644 feature/work/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/work/ModelDownloadManagerImplTest.kt create mode 100644 feature/work/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/work/core/ModelDownloadNotificationTest.kt create mode 100644 feature/work/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/work/task/DownloadModelsTaskTest.kt create mode 100644 presentation/configuration/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupDownloadBatchStateTest.kt create mode 100644 presentation/configuration/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/LocalModelDownloadActionStateTest.kt create mode 100644 presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/LocalModelDownloadActionState.kt 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/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/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/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 982cf5b11..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 @@ -84,15 +84,17 @@ class ServerSetupCatalogRefreshTest { every { modelDownloadManager.batches } returns batches coEvery { modelDownloadManager.start(any(), any()) } coAnswers { val request = firstArg() - batches.value = listOf( - ModelDownloadBatch( - request.type, - request.modelId, - DownloadState.Downloading(50), - isBatch = request.isBatch, - workId = request.modelId.orEmpty(), + 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() @@ -369,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. * 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/setup/component/LocalModelDownloadAction.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/LocalModelDownloadAction.kt index b5ce18893..6685a238e 100644 --- a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/LocalModelDownloadAction.kt +++ b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/LocalModelDownloadAction.kt @@ -39,25 +39,17 @@ internal fun LocalModelDownloadAction( processIntent: (ServerSetupIntent) -> Unit, modifier: Modifier = Modifier, ) { - val type = state.mode.localCatalogType ?: return - val active = state.modelDownloadBatches.filter { it.isRunning } - val isWorkRunning = active.isNotEmpty() - val isCurrentBatch = active.any { it.isBatch && it.type == type } - val hasMissingModels = - state.localModels.any { !it.isCustom && !it.downloaded && it.sources.isNotEmpty() } - val canStart = state.localCatalogStatuses[type] == LocalCatalogStatus.READY && - !isWorkRunning && hasMissingModels - val hasSingleDownload = active.any { !it.isBatch && it.type == type } - val shouldShowAction = isCurrentBatch || (hasMissingModels && !hasSingleDownload) + val action = state.toLocalModelDownloadActionState() + val isCurrentBatch = action.isCancelling AnimatedVisibility( - visible = shouldShowAction, + visible = action.isVisible, modifier = modifier, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut(), ) { Column { SetupSecondaryAction( - isEnabled = !state.loadingConfiguration && (isWorkRunning || canStart), + isEnabled = action.isEnabled, onClick = { processIntent(if (isCurrentBatch) ServerSetupIntent.CancelModelDownloads else ServerSetupIntent.DownloadAllModels) }, ) { Icon( @@ -72,3 +64,25 @@ internal fun LocalModelDownloadAction( } } } + +/** + * Maps current catalogs and worker ownership to the footer's visibility and click behavior. + * Keeps another provider's action enabled so it can open the switch confirmation. + * @author Dmitriy Moroz + */ +internal fun ServerSetupState.toLocalModelDownloadActionState(): LocalModelDownloadActionState { + val type = mode.localCatalogType ?: return LocalModelDownloadActionState(false, false, false) + val active = modelDownloadBatches.filter { it.isRunning } + val isWorkRunning = active.isNotEmpty() + val isCurrentBatch = active.any { it.isBatch && it.type == type } + val hasMissingModels = + localModels.any { !it.isCustom && !it.downloaded && it.sources.isNotEmpty() } + val canStart = + localCatalogStatuses[type] == LocalCatalogStatus.READY && !isWorkRunning && hasMissingModels + val hasSingleDownload = active.any { !it.isBatch && it.type == type } + return LocalModelDownloadActionState( + isVisible = isCurrentBatch || (hasMissingModels && !hasSingleDownload), + isEnabled = !loadingConfiguration && (isWorkRunning || canStart), + isCancelling = isCurrentBatch, + ) +} diff --git a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/LocalModelDownloadActionState.kt b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/LocalModelDownloadActionState.kt new file mode 100644 index 000000000..48d8d79fa --- /dev/null +++ b/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/LocalModelDownloadActionState.kt @@ -0,0 +1,16 @@ +package com.shifthackz.aisdv1.presentation.configuration.setup.component + +/** + * Rendering decisions for the pinned provider download action, independent of animation timing. + * + * @param isVisible Whether the action and its footer gap occupy space. + * @param isEnabled Whether the action accepts a start, switch-dialog or cancellation click. + * @param isCancelling Whether the action stops the current provider's batch. + * + * @author Dmitriy Moroz + */ +internal data class LocalModelDownloadActionState( + val isVisible: Boolean, + val isEnabled: Boolean, + val isCancelling: Boolean, +)