diff --git a/core/localization/src/androidMain/res/values-de/strings.xml b/core/localization/src/androidMain/res/values-de/strings.xml index 4fb9e3dfd..307566af5 100644 --- a/core/localization/src/androidMain/res/values-de/strings.xml +++ b/core/localization/src/androidMain/res/values-de/strings.xml @@ -741,4 +741,39 @@ Laden Download abgeschlossen 🤩 Download fehlgeschlagen 😞 + Sichern und wiederherstellen + Anbieterkonfiguration + Galerie und Verlauf + Netzwerkstatistik + App-Einstellungen + %1$s Einträge + Leer oder von dieser Version nicht unterstützt + Anbieterauswahl + Wähle die zu sichernden Daten. Modelldateien sind nicht enthalten. + Anbietersicherungen enthalten API-Schlüssel und Passwörter. Die Datei ist nicht verschlüsselt. Bewahre sie sicher auf. + Wähle eine Sicherung und die gewünschten Daten. Galerie- und Netzwerkdaten werden hinzugefügt; gewählte App-Einstellungen werden ersetzt. + Sicherungsdatei wählen + SDAI %1$s · %2$s + Erstellt: %1$s + Übersprungen oder nicht unterstützt: %1$s + Nimm deine SDAI-Daten mit + Hast du eine Sicherung? Stelle Anbieter, Galerie und Einstellungen vor der Anbieterauswahl wieder her. Du kannst auch neu beginnen. + Aus Sicherung wiederherstellen + Weiter + Sicherung wird verarbeitet… + Fertig + Gewählte Daten wiederherstellen + Sicherung erstellen + Erstellen + Wiederherstellen + Vorgang fehlgeschlagen. Prüfe die Datei und den freien Speicher und versuche es erneut. + Abgebrochen. Bereits wiederhergestellte Bereiche bleiben erhalten. + Sicherung gespeichert + Wiederherstellung angehalten. Fertige Bereiche bleiben erhalten; ein erneuter Versuch setzt die übrigen fort. + Gewählte Daten wiederhergestellt + Anbietereinstellungen ersetzen? + Die Wiederherstellung ersetzt gespeicherte Einstellungen für: %1$s. Der aktuelle Anbieter bleibt ausgewählt. + Anbietereinstellungen ersetzen + Abbrechen + Gemeinsame Zugangsdaten bleiben für nicht ausgewählte Anbieter erhalten: %1$s. diff --git a/core/localization/src/androidMain/res/values-ru/strings.xml b/core/localization/src/androidMain/res/values-ru/strings.xml index 1874dd494..a773bf5f9 100644 --- a/core/localization/src/androidMain/res/values-ru/strings.xml +++ b/core/localization/src/androidMain/res/values-ru/strings.xml @@ -704,4 +704,39 @@ Загрузка Загрузка завершена 🤩 Не удалось загрузить 😞 + Резервное копирование + Настройки провайдеров + Галерея и история + Статистика сети + Настройки приложения + Элементов: %1$s + Нет данных или не поддерживается этой версией + Выбор провайдеров + Выберите данные для сохранения. Файлы моделей не включаются. + Копии провайдеров содержат API-ключи и пароли. Файл не зашифрован. Храните его в безопасном месте. + Выберите копию, затем данные для восстановления. Галерея и статистика добавляются; выбранные настройки заменяются. + Выбрать файл копии + SDAI %1$s · %2$s + Создано: %1$s + Пропущено или не поддерживается: %1$s + Перенесите свои данные SDAI + Есть резервная копия? Восстановите провайдеров, галерею и настройки перед выбором провайдера. Или начните с нуля. + Восстановить из копии + Продолжить + Обработка резервной копии… + Готово + Восстановить выбранные данные + Создать копию + Создать + Восстановить + Не удалось завершить. Проверьте файл и свободное место и повторите попытку. + Отменено. Уже восстановленные разделы сохранены. + Копия сохранена + Восстановление остановлено. Готовые разделы сохранены; повторная попытка продолжит остальные. + Выбранные данные восстановлены + Заменить настройки провайдеров? + Восстановление заменит сохранённые настройки: %1$s. Текущий провайдер останется выбранным. + Заменить настройки + Отмена + Общие учётные данные сохранены для невыбранных провайдеров: %1$s. diff --git a/core/localization/src/androidMain/res/values-tr/strings.xml b/core/localization/src/androidMain/res/values-tr/strings.xml index 1f0ac45b9..a85534a54 100644 --- a/core/localization/src/androidMain/res/values-tr/strings.xml +++ b/core/localization/src/androidMain/res/values-tr/strings.xml @@ -704,4 +704,39 @@ Yükleniyor İndirme tamamlandı 🤩 İndirme başarısız 😞 + Yedekleme ve geri yükleme + Sağlayıcı yapılandırması + Galeri ve geçmiş + Ağ istatistikleri + Uygulama ayarları + %1$s öğe + Boş veya bu sürümde desteklenmiyor + Sağlayıcı seçenekleri + Yanınıza alacağınız verileri seçin. Model dosyaları dahil değildir. + Sağlayıcı yedekleri API anahtarları ve parolalar içerir. Dosya şifrelenmez. Güvenli bir yerde saklayın. + Bir yedek ve geri yüklenecek verileri seçin. Galeri ve ağ verileri eklenir; seçili uygulama ayarları değiştirilir. + Yedek dosyası seç + SDAI %1$s · %2$s + Oluşturulma: %1$s + Atlanan veya desteklenmeyen: %1$s + SDAI verilerinizi yanınıza alın + Yedeğiniz var mı? Sağlayıcı seçmeden önce sağlayıcılarınızı, galerinizi ve tercihlerinizi geri yükleyin. Sıfırdan da başlayabilirsiniz. + Yedekten geri yükle + Devam et + Yedek işleniyor… + Bitti + Seçili verileri geri yükle + Yedek oluştur + Oluştur + Geri yükle + Tamamlanamadı. Dosyayı ve boş alanı kontrol edip tekrar deneyin. + İptal edildi. Tamamlanan geri yükleme bölümleri korunur. + Yedek kaydedildi + Geri yükleme durdu. Tamamlanan bölümler korunur; tekrar denemek kalan bölümlerden devam eder. + Seçili veriler geri yüklendi + Sağlayıcı ayarları değiştirilsin mi? + Geri yükleme şu sağlayıcıların kayıtlı ayarlarını değiştirir: %1$s. Geçerli sağlayıcınız seçili kalır. + Sağlayıcı ayarlarını değiştir + İptal + Seçilmeyen sağlayıcıları korumak için ortak kimlik bilgileri tutuldu: %1$s. diff --git a/core/localization/src/androidMain/res/values-uk/strings.xml b/core/localization/src/androidMain/res/values-uk/strings.xml index 432e2d8c7..f05edb7a2 100644 --- a/core/localization/src/androidMain/res/values-uk/strings.xml +++ b/core/localization/src/androidMain/res/values-uk/strings.xml @@ -704,4 +704,39 @@ Завантаження Завантаження завершено 🤩 Не вдалося завантажити 😞 + Резервне копіювання + Налаштування провайдерів + Галерея та історія + Статистика мережі + Налаштування застосунку + Елементів: %1$s + Немає даних або не підтримується цією версією + Вибір провайдерів + Виберіть дані для збереження. Файли моделей не включаються. + Копії провайдерів містять API-ключі та паролі. Файл не зашифровано. Зберігайте його в безпечному місці. + Виберіть копію, а потім дані для відновлення. Галерея та статистика додаються; вибрані налаштування замінюються. + Вибрати файл копії + SDAI %1$s · %2$s + Створено: %1$s + Пропущено або не підтримується: %1$s + Перенесіть свої дані SDAI + Маєте резервну копію? Відновіть провайдерів, галерею та налаштування перед вибором провайдера. Або почніть з нуля. + Відновити з копії + Продовжити + Обробка резервної копії… + Готово + Відновити вибрані дані + Створити копію + Створити + Відновити + Не вдалося завершити. Перевірте файл і вільне місце та спробуйте ще раз. + Скасовано. Уже відновлені розділи збережено. + Копію збережено + Відновлення зупинено. Завершені розділи збережено; повторна спроба продовжить решту. + Вибрані дані відновлено + Замінити налаштування провайдерів? + Відновлення замінить збережені налаштування: %1$s. Поточний провайдер залишиться вибраним. + Замінити налаштування + Скасувати + Спільні облікові дані збережено для невибраних провайдерів: %1$s. diff --git a/core/localization/src/androidMain/res/values-zh/strings.xml b/core/localization/src/androidMain/res/values-zh/strings.xml index 38ac75353..d90f86b61 100644 --- a/core/localization/src/androidMain/res/values-zh/strings.xml +++ b/core/localization/src/androidMain/res/values-zh/strings.xml @@ -756,4 +756,39 @@ 加载中 下载完成 🤩 下载失败 😞 + 备份与恢复 + 提供商配置 + 图库与历史记录 + 网络统计 + 应用设置 + %1$s 项 + 为空或此版本不支持 + 提供商选项 + 选择要备份的数据。不包含模型文件。 + 提供商备份包含 API 密钥和密码。此文件未加密,请妥善保管。 + 选择备份后选择要恢复的内容。图库和网络数据会累加,所选应用设置会被替换。 + 选择备份文件 + SDAI %1$s · %2$s + 创建时间:%1$s + 已跳过或不支持:%1$s + 带上您的 SDAI 数据 + 有备份吗?选择提供商前恢复提供商配置、图库和偏好设置。您也可以全新开始。 + 从备份恢复 + 继续 + 正在处理备份… + 完成 + 恢复所选数据 + 创建备份 + 创建 + 恢复 + 无法完成。请检查文件及可用存储空间后重试。 + 已取消。已完成恢复的部分将保留。 + 备份已保存 + 恢复已停止。已完成的部分将保留,重试将继续恢复其余部分。 + 所选数据已恢复 + 替换提供商设置? + 恢复将替换以下提供商的已保存设置:%1$s。当前提供商的选择将保持不变。 + 替换提供商设置 + 取消 + 为保留未选提供商的设置,共用凭据未更改:%1$s。 diff --git a/core/localization/src/androidMain/res/values/strings.xml b/core/localization/src/androidMain/res/values/strings.xml index e69b7980f..9ab4fec8a 100755 --- a/core/localization/src/androidMain/res/values/strings.xml +++ b/core/localization/src/androidMain/res/values/strings.xml @@ -741,4 +741,39 @@ Loading Download complete 🤩 Download failed 😞 + Backup and restore + Provider configuration + Gallery and history + Network statistics + App settings + %1$s items + Empty or unsupported by this version + Provider choices + Choose the data to take with you. Model files are not included. + Provider backups include API keys and passwords. This file is not encrypted. Store it somewhere safe. + Choose a backup, then select what to restore. Gallery and network data are added; selected app settings are replaced. + Choose backup file + SDAI %1$s · %2$s + Created: %1$s + Skipped or unsupported: %1$s + Bring your SDAI data with you + Have a backup? Restore your providers, gallery and preferences before choosing a provider. You can also start fresh. + Restore from backup + Continue + Working on your backup… + Done + Restore selected data + Create backup + Create + Restore + Could not finish. Check the file and available storage, then try again. + Canceled. Any completed restore sections are kept. + Backup saved + Restore stopped. Completed sections are kept; retry resumes the remaining sections. + Selected data restored + Replace provider settings? + Restoring will replace saved settings for: %1$s. Your current provider will stay selected. + Replace provider settings + Cancel + Shared sign-in credentials were kept to preserve unselected providers: %1$s. diff --git a/core/navigation/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/core/navigation/RootAppRouterTest.kt b/core/navigation/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/core/navigation/RootAppRouterTest.kt index 8b183fe67..cc4645c05 100644 --- a/core/navigation/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/core/navigation/RootAppRouterTest.kt +++ b/core/navigation/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/core/navigation/RootAppRouterTest.kt @@ -65,4 +65,17 @@ class RootAppRouterTest { assertEquals(AppRoute.Gallery, router.route.value) } + + @Test + fun `given cold start pending backup, startup opens recovery and user returns, expected Settings context restored`() { + // Given + val router = RootAppRouter() + // When + router.navigateToBackupRestore() + // Then + assertEquals(AppRoute.Backup(LaunchSource.SETTINGS), router.route.value) + router.navigateBack() + assertEquals(AppRoute.Settings, router.route.value) + } + } diff --git a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/AppRoute.kt b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/AppRoute.kt index 43159bed2..34a00abb2 100644 --- a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/AppRoute.kt +++ b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/AppRoute.kt @@ -14,10 +14,20 @@ sealed interface AppRoute { val destination: NavigationDestination /** - * Initial launch gate before onboarding, setup or configuration loading. - * + * Reusable backup route carrying settings or first-launch completion behavior. + * @param source Caller context; SPLASH requires configuration on exit. * @author Dmitriy Moroz */ + data class Backup(val source: LaunchSource = LaunchSource.SETTINGS) : AppRoute { + override val destination = NavigationDestination.BACKUP + } + + /** First-launch restore invitation, which cannot return to completed onboarding. @author Dmitriy Moroz */ + data object BackupWelcome : AppRoute { + override val destination = NavigationDestination.BACKUP_WELCOME + } + + /** Initial launch gate before onboarding, setup or configuration loading. @author Dmitriy Moroz */ data object Splash : AppRoute { override val destination = NavigationDestination.SPLASH } diff --git a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/HomeTabRoutes.kt b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/HomeTabRoutes.kt index b212177e0..1cce7ce2c 100644 --- a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/HomeTabRoutes.kt +++ b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/HomeTabRoutes.kt @@ -18,6 +18,8 @@ fun AppRoute.asHomeTabRoute(): AppRoute? = when (this) { AppRoute.Benchmark, AppRoute.StorageUsage, AppRoute.NetworkUsage, + AppRoute.BackupWelcome, + is AppRoute.Backup, AppRoute.Splash, is AppRoute.OnBoarding, is AppRoute.Setup, diff --git a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/NavigationDestination.kt b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/NavigationDestination.kt index 1f8dfc187..d5258a22e 100644 --- a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/NavigationDestination.kt +++ b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/NavigationDestination.kt @@ -7,6 +7,8 @@ package com.shifthackz.aisdv1.core.navigation */ enum class NavigationDestination { SPLASH, + BACKUP, + BACKUP_WELCOME, ON_BOARDING, SERVER_SETUP, CONFIGURATION_LOADER, diff --git a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/RootAppRouter.kt b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/RootAppRouter.kt index df74a9801..c28239256 100644 --- a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/RootAppRouter.kt +++ b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/RootAppRouter.kt @@ -1,5 +1,6 @@ package com.shifthackz.aisdv1.core.navigation +import com.shifthackz.aisdv1.core.navigation.router.BackupRouter import com.shifthackz.aisdv1.core.navigation.router.BenchmarkRouter import com.shifthackz.aisdv1.core.navigation.router.ConfigurationLoaderRouter import com.shifthackz.aisdv1.core.navigation.router.DebugMenuRouter @@ -31,6 +32,7 @@ import kotlinx.coroutines.flow.asStateFlow class RootAppRouter( initialRoute: AppRoute = AppRoute.Splash, ) : ServerSetupRouter, + BackupRouter, ConfigurationLoaderRouter, SplashRouter, DonateRouter, @@ -50,6 +52,28 @@ class RootAppRouter( WebUiRouter, OnBoardingRouter { + /** Opens reusable backup tabs from Settings. @author Dmitriy Moroz */ + override fun navigateToBackup() = navigateTo(AppRoute.Backup(LaunchSource.SETTINGS)) + + /** Consumes onboarding so Back cannot reopen it. @author Dmitriy Moroz */ + override fun navigateToBackupWelcome() = replaceRoute(AppRoute.BackupWelcome) + + /** + * Rebuilds Settings as the return destination before opening a cold-start pending backup operation. + * @author Dmitriy Moroz + */ + override fun navigateToBackupRestore() { + replaceRoute(AppRoute.Settings) + navigateTo(AppRoute.Backup(LaunchSource.SETTINGS)) + } + + /** Opens restore-only content during first launch. @author Dmitriy Moroz */ + override fun navigateToInitialRestore() = replaceRoute(AppRoute.Backup(LaunchSource.SPLASH)) + + /** Consumes first-launch backup before mandatory provider setup. @author Dmitriy Moroz */ + override fun navigateToInitialConfiguration() = + replaceRoute(AppRoute.Setup(LaunchSource.SPLASH)) + private val routeState = MutableStateFlow(initialRoute) /** @@ -162,14 +186,6 @@ class RootAppRouter( navigateTo(AppRoute.Setup(source)) } - /** - * Replaces completed onboarding with initial-launch server setup. - * - * @author Dmitriy Moroz - */ - override fun navigateToServerSetupAfterOnBoarding() { - replaceRoute(AppRoute.Setup(LaunchSource.SPLASH)) - } /** * Selects text-to-image, replacing the active home tab or consumed gallery-detail route. @@ -298,14 +314,6 @@ class RootAppRouter( navigateTo(AppRoute.OnBoarding(source)) } - /** - * Replaces completed onboarding with configuration loading. - * - * @author Dmitriy Moroz - */ - override fun navigateToPostOnBoardingConfigLoader() { - replaceRoute(AppRoute.ConfigurationLoader) - } /** * Opens the gallery result identified by its persisted item ID. @@ -403,6 +411,8 @@ fun AppRoute.isHomeRoute(): Boolean = when (this) { AppRoute.Settings, -> true + AppRoute.BackupWelcome, + is AppRoute.Backup, AppRoute.Splash, is AppRoute.OnBoarding, is AppRoute.Setup, @@ -427,6 +437,7 @@ fun AppRoute.isHomeRoute(): Boolean = when (this) { * @author Dmitriy Moroz */ private fun AppRoute.canFallBackToTextToImage(): Boolean = when (this) { + is AppRoute.Backup -> source == LaunchSource.SETTINGS AppRoute.ImageToImage, AppRoute.ImageInPaint, AppRoute.Gallery, @@ -445,6 +456,7 @@ private fun AppRoute.canFallBackToTextToImage(): Boolean = when (this) { AppRoute.Home, AppRoute.TextToImage, + AppRoute.BackupWelcome, AppRoute.Splash, is AppRoute.OnBoarding, is AppRoute.Setup, diff --git a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/BackupRouter.kt b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/BackupRouter.kt new file mode 100644 index 000000000..719955b8f --- /dev/null +++ b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/BackupRouter.kt @@ -0,0 +1,31 @@ +package com.shifthackz.aisdv1.core.navigation.router + +/** + * Navigation out of reusable backup screens without exposing application assembly. + * @author Dmitriy Moroz + */ +interface BackupRouter { + /** + * Returns to the preceding Settings route after normal-flow backup. + * @author Dmitriy Moroz + */ + fun navigateBack() + + /** + * Consumes a reconstructed recovery route after provider setup has already completed. + * @author Dmitriy Moroz + */ + fun navigateToHomeScreen() + + /** + * Replaces the invitation with the restore-only first-launch screen. + * @author Dmitriy Moroz + */ + fun navigateToInitialRestore() + + /** + * Consumes first-launch recovery and opens provider selection/configuration. + * @author Dmitriy Moroz + */ + fun navigateToInitialConfiguration() +} diff --git a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/NoOpBackupRouter.kt b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/NoOpBackupRouter.kt new file mode 100644 index 000000000..3975991fb --- /dev/null +++ b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/NoOpBackupRouter.kt @@ -0,0 +1,12 @@ +package com.shifthackz.aisdv1.core.navigation.router + +/** + * Inert backup navigation for previews and unbound composition roots. + * @author Dmitriy Moroz + */ +object NoOpBackupRouter : BackupRouter { + override fun navigateToHomeScreen() = Unit + override fun navigateBack() = Unit + override fun navigateToInitialRestore() = Unit + override fun navigateToInitialConfiguration() = Unit +} diff --git a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/NoOpOnBoardingRouter.kt b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/NoOpOnBoardingRouter.kt index 57f2b4957..174fe19b1 100644 --- a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/NoOpOnBoardingRouter.kt +++ b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/NoOpOnBoardingRouter.kt @@ -7,6 +7,8 @@ package com.shifthackz.aisdv1.core.navigation.router * @author Dmitriy Moroz */ object NoOpOnBoardingRouter : OnBoardingRouter { + override fun navigateToBackupWelcome() = Unit + /** * Ignores this action because no navigation host is attached. * @@ -14,17 +16,5 @@ object NoOpOnBoardingRouter : OnBoardingRouter { */ override fun navigateBack() = Unit - /** - * Ignores this action because no navigation host is attached. - * - * @author Dmitriy Moroz - */ - override fun navigateToServerSetupAfterOnBoarding() = Unit - /** - * Ignores this action because no navigation host is attached. - * - * @author Dmitriy Moroz - */ - override fun navigateToPostOnBoardingConfigLoader() = Unit } diff --git a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/NoOpSettingsRouter.kt b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/NoOpSettingsRouter.kt index 5f588a5ab..a5cef2c07 100644 --- a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/NoOpSettingsRouter.kt +++ b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/NoOpSettingsRouter.kt @@ -8,6 +8,8 @@ import com.shifthackz.aisdv1.core.navigation.LaunchSource * @author Dmitriy Moroz */ object NoOpSettingsRouter : SettingsRouter { + override fun navigateToBackup() = Unit + /** * Ignores this action because no navigation host is attached. * diff --git a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/NoOpSplashRouter.kt b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/NoOpSplashRouter.kt index 317ad27ee..12828b27f 100644 --- a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/NoOpSplashRouter.kt +++ b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/NoOpSplashRouter.kt @@ -6,6 +6,10 @@ package com.shifthackz.aisdv1.core.navigation.router * @author Dmitriy Moroz */ object NoOpSplashRouter : SplashRouter { + override fun navigateToInitialRestore() = Unit + override fun navigateToBackupWelcome() = Unit + override fun navigateToBackupRestore() = Unit + /** * Ignores this action because no navigation host is attached. * diff --git a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/OnBoardingRouter.kt b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/OnBoardingRouter.kt index 81debf3f3..d249c3284 100644 --- a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/OnBoardingRouter.kt +++ b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/OnBoardingRouter.kt @@ -8,23 +8,17 @@ package com.shifthackz.aisdv1.core.navigation.router */ interface OnBoardingRouter { /** - * Closes the drawer first, otherwise returns to the previous route or the generation-home fallback. - * + * Replaces completed onboarding with the first-launch recovery invitation. * @author Dmitriy Moroz */ - fun navigateBack() + fun navigateToBackupWelcome() /** - * Replaces completed onboarding with initial-launch server setup. + * Closes the drawer first, otherwise returns to the previous route or the generation-home fallback. * * @author Dmitriy Moroz */ - fun navigateToServerSetupAfterOnBoarding() + fun navigateBack() + - /** - * Replaces completed onboarding with configuration loading. - * - * @author Dmitriy Moroz - */ - fun navigateToPostOnBoardingConfigLoader() } diff --git a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/SettingsRouter.kt b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/SettingsRouter.kt index bcc1f0254..c7d814b6c 100644 --- a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/SettingsRouter.kt +++ b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/SettingsRouter.kt @@ -8,6 +8,12 @@ import com.shifthackz.aisdv1.core.navigation.LaunchSource * @author Dmitriy Moroz */ interface SettingsRouter { + /** + * Opens the standalone Create/Restore backup tabs. + * @author Dmitriy Moroz + */ + fun navigateToBackup() + /** * Opens the application drawer without changing the active route. * diff --git a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/SplashRouter.kt b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/SplashRouter.kt index df1f5b4df..af530d411 100644 --- a/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/SplashRouter.kt +++ b/core/navigation/src/commonMain/kotlin/com/shifthackz/aisdv1/core/navigation/router/SplashRouter.kt @@ -7,6 +7,21 @@ package com.shifthackz.aisdv1.core.navigation.router * @author Dmitriy Moroz */ interface SplashRouter { + /** Resumes first-launch restore-only content before mandatory setup. @author Dmitriy Moroz */ + fun navigateToInitialRestore() + + /** + * Resumes pending restore work before normal configuration publication. + * @author Dmitriy Moroz + */ + fun navigateToBackupRestore() + + /** + * Resumes the first-launch restore invitation. + * @author Dmitriy Moroz + */ + fun navigateToBackupWelcome() + /** * Replaces splash with onboarding using the initial-launch source. * diff --git a/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/image/PlatformBackupImageDecoder.android.kt b/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/image/PlatformBackupImageDecoder.android.kt new file mode 100644 index 000000000..108bcef69 --- /dev/null +++ b/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/image/PlatformBackupImageDecoder.android.kt @@ -0,0 +1,43 @@ +package com.shifthackz.aisdv1.data.image + +import android.graphics.Bitmap +import android.graphics.BitmapFactory + +/** + * Uses bounds-only Android probing followed by power-of-two sampling; original pixels are never decoded. + * @author Dmitriy Moroz + */ +internal actual class PlatformBackupImageDecoder actual constructor() : BackupImageDecoder { + override fun dimensions(bytes: ByteArray): Pair { + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) + require(bounds.outWidth > 0 && bounds.outHeight > 0) { "Invalid backup image dimensions" } + return bounds.outWidth.toLong() to bounds.outHeight.toLong() + } + + override fun validateSample(bytes: ByteArray, maxEdge: Int) { + val (width, height) = dimensions(bytes) + var sample = 1L + while ((width - 1) / sample + 1 > maxEdge || (height - 1) / sample + 1 > maxEdge) sample *= 2 + require(sample <= Int.MAX_VALUE) { "Invalid backup sample size" } + val options = BitmapFactory.Options().apply { + inSampleSize = sample.toInt() + inPreferredConfig = Bitmap.Config.ARGB_8888 + inScaled = false + } + val image = requireNotNull( + BitmapFactory.decodeByteArray( + bytes, + 0, + bytes.size, + options + ) + ) { "Invalid backup image content" } + try { + require(image.width in 1..maxEdge && image.height in 1..maxEdge) { "Backup sample exceeds bounds" } + require(image.allocationByteCount.toLong() <= maxEdge.toLong() * maxEdge * 4) { "Backup sample exceeds byte budget" } + } finally { + image.recycle() + } + } +} diff --git a/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/preference/AndroidKeyValueStore.android.kt b/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/preference/AndroidKeyValueStore.android.kt index ae69b85ae..ba406286a 100644 --- a/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/preference/AndroidKeyValueStore.android.kt +++ b/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/preference/AndroidKeyValueStore.android.kt @@ -26,6 +26,28 @@ private class AndroidPreferencesKeyValueStore( */ private fun withMemoryLock(block: () -> T): T = synchronized(memoryLock, block) + /** + * Reports trusted persisted presence, including explicitly saved default values. + * @param key Existing preference key. + * @author Dmitriy Moroz + */ + override fun contains(key: String): Boolean = withMemoryLock { + val mask = configurationMask + when { + mask?.strings?.containsKey(key) == true -> mask.strings[key] != null + mask?.booleans?.containsKey(key) == true -> mask.booleans[key] != null + mask?.integers?.containsKey(key) == true -> mask.integers[key] != null + else -> preferences.contains(key) + } + } + + /** Finishes the exact quarantined write before a restore session may be abandoned. @author Dmitriy Moroz */ + override fun retryPendingWrite(): Boolean { + val batch = withMemoryLock { configurationMask } ?: return false + putSettingsDurably(batch.candidateStrings, batch.candidateBooleans, batch.candidateIntegers) + return true + } + private var configurationMask: ConfigurationMemoryMask? = null private var isBatchInFlight = false @@ -76,11 +98,29 @@ private class AndroidPreferencesKeyValueStore( override fun putConfigurationDurably( strings: Map, booleans: Map + ) = putSettingsDurably(strings, booleans, emptyMap()) + + /** + * Persists a complete typed backup settings batch with the same quarantine as configuration. + * @param strings String replacements. + * @param booleans Boolean replacements. + * @param integers Integer replacements. + * @author Dmitriy Moroz + */ + override fun putSettingsDurably( + strings: Map, + booleans: Map, + integers: Map, ) { val batch = withMemoryLock { if (isBatchInFlight) persistenceFailure() val current = configurationMask - if (current != null && !current.matches(strings, booleans)) persistenceFailure() + if (current != null && !current.matches( + strings, + booleans, + integers + ) + ) persistenceFailure() if (current == null) configurationMask = ConfigurationMemoryMask( strings.keys.associateWith { key -> preferences.getString(key, null) }, booleans.keys.associateWith { key -> @@ -91,6 +131,13 @@ private class AndroidPreferencesKeyValueStore( }, strings.toMap(), booleans.toMap(), + integers.keys.associateWith { key -> + if (preferences.contains(key)) preferences.getInt( + key, + 0 + ) else null + }, + integers.toMap(), ) isBatchInFlight = true checkNotNull(configurationMask) @@ -100,6 +147,7 @@ private class AndroidPreferencesKeyValueStore( check(preferences.edit().apply { batch.candidateStrings.forEach { (key, value) -> putString(key, value) } batch.candidateBooleans.forEach { (key, value) -> putBoolean(key, value) } + batch.candidateIntegers.forEach { (key, value) -> putInt(key, value) } }.commit()) { "Configuration persistence failed" } hasPersisted = true } finally { @@ -143,7 +191,11 @@ private class AndroidPreferencesKeyValueStore( * @author Dmitriy Moroz */ override fun getInt(key: String, default: Int): Int = - withMemoryLock { preferences.getInt(key, default) } + withMemoryLock { + val mask = configurationMask + if (mask?.integers?.containsKey(key) == true) mask.integers[key] ?: default + else preferences.getInt(key, default) + } /** * Writes an ordinary integer, rejecting accidental overlap with pending configuration keys. diff --git a/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/image/BackupImageValidatorImplTest.kt b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/image/BackupImageValidatorImplTest.kt new file mode 100644 index 000000000..77627d5fc --- /dev/null +++ b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/image/BackupImageValidatorImplTest.kt @@ -0,0 +1,69 @@ +package com.shifthackz.aisdv1.data.image + +import com.shifthackz.aisdv1.domain.entity.backup.BackupImageBudget +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Test + +class BackupImageValidatorImplTest { + private val decoder = mockk(relaxed = true) + private val budget = BackupImageBudget(1024, 16_777_216, 128L * 1024 * 1024, 256) + private val validator = BackupImageValidatorImpl(decoder, budget) + private val encoded = byteArrayOf(1) + + @Test + fun `given compact image with enormous dimensions, native probe reports dimensions, expected pixel rejection before content allocation`() { + // Given + every { decoder.dimensions(encoded) } returns (16_384L to 16_384L) + // When + val failure = assertThrows(IllegalArgumentException::class.java) { validator(encoded) } + // Then + assertEquals("Backup image exceeds pixel budget", failure.message) + verify(exactly = 0) { decoder.validateSample(any(), any()) } + } + + @Test + fun `given image metadata beyond integral multiplication range, native probe reports dimensions, expected rejection without overflow or sample allocation`() { + // Given + every { decoder.dimensions(encoded) } returns (Long.MAX_VALUE to Long.MAX_VALUE) + // When + assertThrows(IllegalArgumentException::class.java) { validator(encoded) } + // Then + verify(exactly = 0) { decoder.validateSample(any(), any()) } + } + + @Test + fun `given pixel count admitted but decoded bytes over budget, validation begins, expected byte admission before sample allocation`() { + // Given + val constrained = BackupImageValidatorImpl(decoder, budget.copy(maxDecodedBytes = 7)) + every { decoder.dimensions(encoded) } returns (1L to 1L) + // When + val failure = assertThrows(IllegalArgumentException::class.java) { constrained(encoded) } + // Then + assertEquals("Backup image exceeds decoded byte budget", failure.message) + verify(exactly = 0) { decoder.validateSample(any(), any()) } + } + + @Test + fun `given encoded image exceeds admission, validation starts, expected native decoder never called`() { + // Given + val oversized = ByteArray(1025) + // When + assertThrows(IllegalArgumentException::class.java) { validator(oversized) } + // Then + verify(exactly = 0) { decoder.dimensions(any()); decoder.validateSample(any(), any()) } + } + + @Test + fun `given admitted dimensions, image validation runs, expected bounded native sample without original bitmap`() { + // Given + every { decoder.dimensions(encoded) } returns (4096L to 4096L) + // When + validator(encoded) + // Then + verify(exactly = 1) { decoder.validateSample(encoded, 256) } + } +} diff --git a/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/image/PlatformBackupImageDecoderTest.kt b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/image/PlatformBackupImageDecoderTest.kt new file mode 100644 index 000000000..81f2da9e1 --- /dev/null +++ b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/image/PlatformBackupImageDecoderTest.kt @@ -0,0 +1,58 @@ +package com.shifthackz.aisdv1.data.image + +import com.shifthackz.aisdv1.data.export.MediaStoreImageFixture +import com.shifthackz.aisdv1.domain.entity.backup.BackupImageBudget +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode +import java.nio.ByteBuffer +import java.util.zip.CRC32 + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class PlatformBackupImageDecoderTest { + private val decoder = PlatformBackupImageDecoder() + private val validator = BackupImageValidatorImpl( + decoder, + BackupImageBudget(24 * 1024 * 1024, 16_777_216, 128L * 1024 * 1024, 256) + ) + + @Test + fun `given valid application image formats, bounded native validation runs, expected standard PNG JPEG WebP admitted`() { + // Given + val images = MediaStoreImageFixture.entries.map { it.bytes() } + // When + images.forEach(validator::invoke) + // Then + images.forEach { assertEquals(1L to 1L, decoder.dimensions(it)) } + } + + @Test + fun `given compact PNG with enormous header dimensions, native bounds probe runs, expected rejection before raster allocation`() { + // Given + val encoded = MediaStoreImageFixture.PNG.bytes() + ByteBuffer.wrap(encoded).apply { putInt(16, 16384); putInt(20, 16384) } + val crc = CRC32().apply { update(encoded, 12, 17) }.value.toInt() + ByteBuffer.wrap(encoded).putInt(29, crc) + // When + val failure = assertThrows(IllegalArgumentException::class.java) { validator(encoded) } + // Then + assertEquals(16384L to 16384L, decoder.dimensions(encoded)) + assertEquals("Backup image exceeds pixel budget", failure.message) + } + + @Test + fun `given corrupted encoded image, native validation runs, expected rejection without bitmap retention`() { + // Given + val encoded = MediaStoreImageFixture.PNG.bytes().copyOf(20) + // When + assertThrows(IllegalArgumentException::class.java) { validator(encoded) } + // Then + assertThrows(IllegalArgumentException::class.java) { validator("corrupted image".toByteArray()) } + } +} diff --git a/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/preference/PreferenceManagerImplTest.kt b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/preference/PreferenceManagerImplTest.kt index ad3e6c2ea..ab7dadf6e 100644 --- a/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/preference/PreferenceManagerImplTest.kt +++ b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/preference/PreferenceManagerImplTest.kt @@ -249,6 +249,20 @@ class PreferenceManagerImplTest { } private class InMemoryKeyValueStore : KeyValueStore { + override fun retryPendingWrite(): Boolean = false + override fun contains(key: String): Boolean = + key in strings || key in booleans || key in ints + + override fun putSettingsDurably( + strings: Map, + booleans: Map, + integers: Map + ) { + this.strings.putAll(strings) + this.booleans.putAll(booleans) + this.ints.putAll(integers) + } + override fun putConfigurationDurably( strings: Map, booleans: Map diff --git a/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupExportStateStoreImplTest.kt b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupExportStateStoreImplTest.kt new file mode 100644 index 000000000..4007fed14 --- /dev/null +++ b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupExportStateStoreImplTest.kt @@ -0,0 +1,139 @@ +package com.shifthackz.aisdv1.data.preference.backup + +import com.shifthackz.aisdv1.data.preference.KeyValueStore +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportIntent +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportStatus +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +class BackupExportStateStoreImplTest { + private var raw = "" + private val store = mockk(relaxed = true) { + every { getString(any(), any()) } answers { raw } + every { putStringDurably(any(), any()) } answers { raw = secondArg() } + } + private val records = BackupExportStateStoreImpl(store) + + @Test + fun `given pending destination copy, checked operation record round trips, expected source and destination association preserved`() { + // Given + val intent = BackupExportIntent( + "handle", + "backup.sdaibackup", + BackupExportStatus.COPYING, + "content://destination" + ) + // When + records.write(intent) + val restored = records.read() + // Then + assertEquals(intent, restored) + verify(exactly = 1) { store.putStringDurably("pending_export", any()) } + verify(exactly = 0) { store.putConfigurationDurably(any(), any()) } + } + + @Test + fun `given native export acknowledged, checked clear completes, expected no recoverable pending source`() { + // Given + records.write(BackupExportIntent("handle", "backup")) + // When + records.clear() + // Then + assertNull(records.read()) + } + + @Test + fun `given quarantined operation record, startup recovers exact write, expected dedicated preference owner retried`() { + // Given + every { store.retryPendingWrite() } returns true + // When + records.recoverPendingWrite() + // Then + verify(exactly = 1) { store.retryPendingWrite() } + } + + @Test + fun `given invalid operation record, startup reads unknown schema, expected failure without silent pending export loss`() { + // Given + raw = """{"version":2}""" + // When + val error = assertThrows(IllegalStateException::class.java) { records.read() } + // Then + assertEquals("Unsupported pending export state", error.message) + } + + @Test + fun `given transient export stages, durable write is requested, expected rejection before persistence`() { + // Given + val stages = listOf(BackupExportStatus.NONE, BackupExportStatus.PROCESSING) + // When + val failures = stages.map { + runCatching { + records.write( + BackupExportIntent( + "handle", + "backup", + it + ) + ) + }.exceptionOrNull() + } + // Then + assertTrue(failures.all { it?.message == "Invalid durable export stage" }) + verify(exactly = 0) { store.putStringDurably(any(), any()) } + } + + @Test + fun `given missing source identity, durable export write is requested, expected rejection without storage changes`() { + // Given + val intents = listOf(BackupExportIntent("", "backup"), BackupExportIntent("handle", " ")) + // When + val failures = intents.map { runCatching { records.write(it) }.exceptionOrNull() } + // Then + assertTrue(failures.all { it?.message == "Missing pending export identity" }) + verify(exactly = 0) { store.putStringDurably(any(), any()) } + } + + @Test + fun `given copying state without destination, durable write is requested, expected explicit rejection`() { + // Given + val intent = BackupExportIntent("handle", "backup", BackupExportStatus.COPYING) + // When + val failure = runCatching { records.write(intent) }.exceptionOrNull() + // Then + assertEquals("Missing pending export destination", failure?.message) + verify(exactly = 0) { store.putStringDurably(any(), any()) } + } + + @Test + fun `given corrupted durable JSON, startup reads operation, expected failure without silent record clearing`() { + // Given + raw = "not JSON" + // When + val failure = runCatching { records.read() }.exceptionOrNull() + // Then + assertTrue(failure != null) + assertEquals("not JSON", raw) + verify(exactly = 0) { store.putStringDurably(any(), any()) } + } + + @Test + fun `given retained pending export, checked clear fails, expected failure propagated and association retained`() { + // Given + val intent = BackupExportIntent("handle", "backup") + records.write(intent) + val failure = IllegalStateException("cannot clear") + every { store.putStringDurably("pending_export", "") } throws failure + // When + val caught = runCatching { records.clear() }.exceptionOrNull() + // Then + assertTrue(failure === caught) + assertEquals(intent, records.read()) + } +} diff --git a/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupPreferencesGatewayImplTest.kt b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupPreferencesGatewayImplTest.kt new file mode 100644 index 000000000..19142cc6f --- /dev/null +++ b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupPreferencesGatewayImplTest.kt @@ -0,0 +1,426 @@ +package com.shifthackz.aisdv1.data.preference.backup + +import com.shifthackz.aisdv1.data.preference.KeyValueStore +import com.shifthackz.aisdv1.data.preference.KeyValueConfigurationStore +import com.shifthackz.aisdv1.data.preference.PreferenceManagerImpl +import com.shifthackz.aisdv1.domain.entity.Grid +import com.shifthackz.aisdv1.domain.entity.ServerSource +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationCredentials +import com.shifthackz.aisdv1.domain.entity.NetworkTimeout +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.entity.backup.BackupPreferences +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage +import com.shifthackz.aisdv1.domain.entity.backup.BackupValue +import com.shifthackz.aisdv1.domain.preference.PreferenceManager +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +class BackupPreferencesGatewayImplTest { + private val strings = mutableMapOf() + private val flags = mutableMapOf() + private val integers = mutableMapOf() + private val store = mockk(relaxed = true) + private val preferences = mockk(relaxed = true) + private val gateway = BackupPreferencesGatewayImpl(store, preferences) + + @Before + fun setup() { + every { store.contains(any()) } answers { firstArg() in strings || firstArg() in flags || firstArg() in integers } + every { store.getString(any(), any()) } answers { strings[firstArg()] ?: secondArg() } + every { store.getBoolean(any(), any()) } answers { flags[firstArg()] ?: secondArg() } + every { store.getInt(any(), any()) } answers { integers[firstArg()] ?: secondArg() } + every { + store.putConfigurationDurably( + any(), + any() + ) + } answers { strings.putAll(firstArg()); flags.putAll(secondArg()); Unit } + every { preferences.galleryGrid } returns Grid.Fixed2 + every { preferences.connectionTimeout } returns NetworkTimeout.TWO_MINUTES + every { preferences.generationRequestTimeout } returns NetworkTimeout.TWO_MINUTES + every { preferences.designColorToken } returns "default" + every { preferences.designDarkThemeToken } returns "FRAPPE" + every { preferences.languageCode } returns "" + every { preferences.textToImageCfgScale } returns 7f + every { preferences.imageToImageCfgScale } returns 7f + every { preferences.textToImageSamplingSteps } returns 20 + every { preferences.imageToImageSamplingSteps } returns 20 + } + + @Test + fun `given fresh default settings, backup inventory reads effective preferences, expected settings remain selectable`() { + // Given + every { preferences.autoSaveAiResults } returns true + // When + val snapshot = gateway.read() + // Then + assertEquals(BackupValue.Flag(true), snapshot.settings["autoSave"]) + assertEquals(BackupValue.Integer(20), snapshot.settings["textToImageSteps"]) + assertTrue(snapshot.providers.isEmpty()) + } + + @Test + fun `given configured provider with explicit saved default, snapshot is read, expected default presence preserved`() { + // Given + flags["key_demo_mode"] = false + strings["key_server_url"] = "https://configured" + // When + val snapshot = gateway.read() + // Then + assertEquals(BackupValue.Flag(false), snapshot.providers["custom"]?.get("demoMode")) + assertFalse(snapshot.providers.getValue("custom").containsKey("model")) + } + + @Test + fun `given existing installation, recovery stage is absent, expected completed stage without invitation`() { + // Given + flags["key_on_boarding_complete"] = true + // When + val stage = gateway.readStartupStage() + // Then + assertEquals(BackupStartupStage.COMPLETE, stage) + } + + @Test + fun `given onboarding completion, invitation is persisted, expected atomic completed flag and stage batch`() { + // Given + flags["key_on_boarding_complete"] = false + // When + gateway.writeStartupStage(BackupStartupStage.INVITATION) + // Then + verify { + store.putConfigurationDurably( + mapOf("key_backup_startup_stage" to "INVITATION"), + mapOf("key_on_boarding_complete" to true) + ) + } + verify(exactly = 0) { store.putBoolean(any(), any()) } + assertEquals(true, flags["key_on_boarding_complete"]) + assertEquals(BackupStartupStage.INVITATION, gateway.readStartupStage()) + } + + @Test + fun `given inactive provider restore, selected provider is OpenAI, expected selection and revision untouched`() { + // Given + strings["key_provider_selection_state"] = "open_ai|41" + // When + gateway.writeProviders( + mapOf("custom" to mapOf("serverUrl" to BackupValue.Text("https://imported"))), + null + ) + // Then + assertEquals("open_ai|41", strings["key_provider_selection_state"]) + assertEquals("https://imported", strings["key_server_url"]) + } + + @Test + fun `given selected provider restore, connection changes, expected same source with advanced revision`() { + // Given + strings["key_provider_selection_state"] = "easy_diffusion|41" + strings["key_easy_diffusion_url"] = "https://old" + // When + gateway.writeProviders( + mapOf("easy_diffusion" to mapOf("serverUrl" to BackupValue.Text("https://imported"))), + null + ) + // Then + assertEquals("easy_diffusion|42", strings["key_provider_selection_state"]) + } + + @Test + fun `given future provider and removed field, compatibility filtering runs, expected only known fields retained`() { + // Given + val incoming = BackupPreferences( + mapOf( + "future_provider" to mapOf("secret" to BackupValue.Text("ignored")), + "custom" to mapOf( + "serverUrl" to BackupValue.Text("keep"), + "removed" to BackupValue.Text("ignored") + ) + ), mapOf("future_setting" to BackupValue.Flag(true)) + ) + // When + val supported = gateway.filterSupported(incoming) + // Then + assertEquals( + mapOf("custom" to mapOf("serverUrl" to BackupValue.Text("keep"))), + supported.providers + ) + assertTrue(supported.settings.isEmpty()) + } + + @Test + fun `given known provider field, malformed scalar type is imported, expected validation failure`() { + // Given + val incoming = BackupPreferences( + mapOf("custom" to mapOf("serverUrl" to BackupValue.Integer(1))), + emptyMap() + ) + // When + val failure = + assertThrows(IllegalArgumentException::class.java) { gateway.filterSupported(incoming) } + // Then + assertEquals("Invalid portable preference type", failure.message) + } + + @Test + fun `given removed MNN backend and future timeout option, compatibility filtering runs, expected unsupported values skipped`() { + // Given + val incoming = BackupPreferences( + mapOf("local_mnn" to mapOf("backend" to BackupValue.Text("removed_backend"))), + mapOf("generationTimeout" to BackupValue.Integer(999)) + ) + // When + val supported = gateway.filterSupported(incoming) + // Then + assertTrue(supported.providers.getValue("local_mnn").isEmpty()) + assertTrue(supported.settings.isEmpty()) + } + + @Test + fun `given quarantined authorization association only, checked replay commits, expected provider invalidation without ordinary field changes`() { + // Given + strings["key_authorization_commit_id"] = "old" + every { store.retryPendingWrite() } answers { + strings["key_authorization_commit_id"] = "new"; true + } + // When + val recovered = gateway.recoverPendingWrite() + // Then + assertEquals(setOf(BackupCategory.PROVIDERS), recovered) + } + + @Test + fun `given quarantined language setting, checked replay commits, expected settings invalidation for locale refresh`() { + // Given + every { preferences.languageCode } answers { strings["key_language"].orEmpty() } + every { store.retryPendingWrite() } answers { strings["key_language"] = "de"; true } + // When + val recovered = gateway.recoverPendingWrite() + // Then + assertEquals(setOf(BackupCategory.SETTINGS), recovered) + } + + @Test + fun `given normal Horde configuration commit, full default provider snapshot persists, expected only meaningful provider group in backup`() { + // Given + val configuration = KeyValueConfigurationStore(store) + val candidate = configuration.getConfiguration(AuthorizationCredentials.None) + .copy(source = ServerSource.HORDE, hordeApiKey = "horde-key") + configuration.commitConfiguration(candidate, "association") + val actualPreferences = PreferenceManagerImpl(store) + val actualGateway = BackupPreferencesGatewayImpl(store, actualPreferences) + // When + val snapshot = actualGateway.read() + // Then + assertTrue(strings.containsKey("key_swarm_server_url")) + assertTrue(flags.containsKey("key_demo_mode")) + assertEquals(setOf("horde"), snapshot.providers.keys) + assertFalse(snapshot.providers.containsKey("custom")) + assertFalse(snapshot.providers.containsKey("swarm_ui")) + } + + @Test + fun `given normal configured A1111 commit with explicit false default, backup reads existing provider, expected saved default retained for conflict checks`() { + // Given + val configuration = KeyValueConfigurationStore(store) + val candidate = configuration.getConfiguration(AuthorizationCredentials.None) + .copy(serverUrl = "https://configured", demoMode = false) + configuration.commitConfiguration(candidate, "association") + val actualGateway = BackupPreferencesGatewayImpl(store, PreferenceManagerImpl(store)) + // When + val snapshot = actualGateway.read() + // Then + assertEquals( + BackupValue.Flag(false), + snapshot.providers.getValue("custom").getValue("demoMode") + ) + assertFalse(snapshot.providers.containsKey("swarm_ui")) + } + + @Test + fun `given legacy partial provider with missing mandatory fields, backup reads nondefault model choice, expected partial configuration retained without setup validation`() { + // Given + strings["key_open_ai_compatible_model"] = "user-model" + // When + val snapshot = gateway.read() + // Then + assertEquals( + BackupValue.Text("user-model"), + snapshot.providers.getValue("open_ai_compatible").getValue("model") + ) + } + + @Test + fun `given invalid numeric form defaults, compatibility filtering runs, expected nonfinite negative and zero steps skipped`() { + // Given + val invalidValues = listOf("NaN", "Infinity", "-1", "not-a-number") + // When + val filtered = invalidValues.map { text -> + gateway.filterSupported( + BackupPreferences( + emptyMap(), + mapOf( + "textToImageCfg" to BackupValue.Text(text), + "imageToImageSteps" to BackupValue.Integer(0) + ) + ) + ) + } + // Then + assertTrue(filtered.all { it.settings.isEmpty() }) + } + + @Test + fun `given zero guidance and positive sampling steps, compatibility filtering runs, expected valid boundary values retained`() { + // Given + val settings = mapOf( + "imageToImageCfg" to BackupValue.Text("0"), + "textToImageSteps" to BackupValue.Integer(1) + ) + // When + val supported = gateway.filterSupported(BackupPreferences(emptyMap(), settings)) + // Then + assertEquals(settings, supported.settings) + } + + @Test + fun `given unknown theme language and grid values, compatibility filtering runs, expected unsupported options skipped`() { + // Given + val settings = mapOf( + "colorToken" to BackupValue.Text("future"), + "darkToken" to BackupValue.Text("future"), + "language" to BackupValue.Text("future"), + "galleryGrid" to BackupValue.Integer(-1) + ) + // When + val supported = gateway.filterSupported(BackupPreferences(emptyMap(), settings)) + // Then + assertTrue(supported.settings.isEmpty()) + } + + @Test + fun `given malformed flag and integer fields, compatibility filtering runs, expected explicit type rejection`() { + // Given + val malformed = + listOf("autoSave" to BackupValue.Text("true"), "galleryGrid" to BackupValue.Flag(true)) + // When + val failures = malformed.map { (key, value) -> + runCatching { + gateway.filterSupported( + BackupPreferences( + emptyMap(), + mapOf(key to value) + ) + ) + }.exceptionOrNull() + } + // Then + assertTrue(failures.all { it is IllegalArgumentException && it.message == "Invalid portable preference type" }) + } + + @Test + fun `given selected provider already matches restored fields, backup applies, expected selection revision unchanged`() { + // Given + strings["key_provider_selection_state"] = "custom|41" + strings["key_server_url"] = "https://same" + // When + gateway.writeProviders( + mapOf("custom" to mapOf("serverUrl" to BackupValue.Text("https://same"))), + null + ) + // Then + assertEquals("custom|41", strings["key_provider_selection_state"]) + } + + @Test + fun `given exhausted provider revision, backup changes selected provider, expected failure before durable write`() { + // Given + strings["key_provider_selection_state"] = "custom|${Long.MAX_VALUE}" + // When + val failure = runCatching { + gateway.writeProviders( + mapOf( + "custom" to mapOf( + "serverUrl" to BackupValue.Text("https://new") + ) + ), null + ) + }.exceptionOrNull() + // Then + assertEquals("Provider revision exhausted", failure?.message) + verify(exactly = 0) { store.putConfigurationDurably(any(), any()) } + } + + @Test + fun `given selected provider authorization reassociation, backup fields match, expected revision advances with checked association`() { + // Given + strings["key_provider_selection_state"] = "custom|41" + strings["key_server_url"] = "https://same" + // When + gateway.writeProviders( + mapOf("custom" to mapOf("serverUrl" to BackupValue.Text("https://same"))), + "new-association" + ) + // Then + assertEquals("custom|42", strings["key_provider_selection_state"]) + assertEquals("new-association", strings["key_authorization_commit_id"]) + } + + @Test + fun `given mixed portable settings, selective restore writes batch, expected only known typed settings persisted`() { + // Given + val values = mapOf( + "language" to BackupValue.Text("de"), + "autoSave" to BackupValue.Flag(false), + "textToImageSteps" to BackupValue.Integer(30), + "removed" to BackupValue.Text("ignored") + ) + // When + gateway.writeSettings(values) + // Then + verify { + store.putSettingsDurably( + mapOf("key_language_code" to "de"), + mapOf("key_ai_auto_save" to false), + mapOf("key_text_to_image_sampling_steps" to 30) + ) + } + verify(exactly = 0) { store.putConfigurationDurably(any(), any()) } + } + + @Test + fun `given checked settings persistence failure, restore writes batch, expected original failure propagated`() { + // Given + val failure = IllegalStateException("disk unavailable") + every { store.putSettingsDurably(any(), any(), any()) } throws failure + // When + val caught = + runCatching { gateway.writeSettings(mapOf("autoSave" to BackupValue.Flag(true))) }.exceptionOrNull() + // Then + assertTrue(failure === caught) + verify(exactly = 0) { + store.putBoolean(any(), any()); store.putInt( + any(), + any() + ); store.putString(any(), any()) + } + } + + @Test + fun `given no pending checked write, recovery is requested, expected no invalidation categories`() { + // Given + every { store.retryPendingWrite() } returns false + // When + val recovered = gateway.recoverPendingWrite() + // Then + assertTrue(recovered.isEmpty()) + } +} diff --git a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/di/DataCoreModule.kt b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/di/DataCoreModule.kt index a5a6050fd..0652144a4 100644 --- a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/di/DataCoreModule.kt +++ b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/di/DataCoreModule.kt @@ -1,5 +1,11 @@ package com.shifthackz.aisdv1.data.di +import com.shifthackz.aisdv1.data.image.BackupImageValidatorImpl +import com.shifthackz.aisdv1.data.image.BackupImageDecoder +import com.shifthackz.aisdv1.data.image.PlatformBackupImageDecoder +import com.shifthackz.aisdv1.domain.entity.backup.BackupImageBudget +import com.shifthackz.aisdv1.domain.gateway.backup.BackupImageValidator + import com.shifthackz.aisdv1.domain.datasource.EasyDiffusionRemoteDataSource import com.shifthackz.aisdv1.data.remote.KtorEasyDiffusionRemoteDataSource @@ -181,6 +187,16 @@ import org.koin.dsl.module * @author Dmitriy Moroz */ val coreDataModule = module { + single { + BackupImageBudget( + maxEncodedBytes = 24 * 1024 * 1024, + maxPixels = 16_777_216L, + maxDecodedBytes = 128L * 1024 * 1024, + validationEdge = 256 + ) + } + single { PlatformBackupImageDecoder() } + single { BackupImageValidatorImpl(get(), get()) } single { GalleryReadGatewayImpl(get()) } single { AuthenticatedConnectionProviderImpl( diff --git a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/di/PreferenceDataModule.kt b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/di/PreferenceDataModule.kt index 297070cb9..da75fb1bc 100644 --- a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/di/PreferenceDataModule.kt +++ b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/di/PreferenceDataModule.kt @@ -11,14 +11,25 @@ import com.shifthackz.aisdv1.domain.preference.SessionPreference import com.shifthackz.aisdv1.network.client.ConnectionTimeoutProvider import com.shifthackz.aisdv1.network.client.GenerationTimeoutProvider import org.koin.core.qualifier.named +import com.shifthackz.aisdv1.data.preference.backup.BackupPreferencesGatewayImpl +import com.shifthackz.aisdv1.domain.gateway.backup.BackupPreferencesGateway +import com.shifthackz.aisdv1.domain.gateway.backup.BackupExportStateStore +import com.shifthackz.aisdv1.data.preference.backup.BackupExportStateStoreImpl import org.koin.dsl.module /** - * Exposes the `preferenceDataModule` value used by the SDAI data layer. + * Shares one checked preference owner across provider settings, portable backup adapters and live timeout readers. * * @author Dmitriy Moroz */ val preferenceDataModule = module { + single { BackupExportStateStoreImpl(createKeyValueStore("aisdv1_backup_operations")) } + single { + BackupPreferencesGatewayImpl( + get(named(KEY_PREFERENCE_MANAGER)), + get() + ) + } single(named(KEY_PREFERENCE_MANAGER)) { createKeyValueStore( KEY_PREFERENCE_MANAGER @@ -48,7 +59,7 @@ val preferenceDataModule = module { } /** - * Exposes the `KEY_PREFERENCE_MANAGER` value used by the SDAI data layer. + * Installed preference-suite name; preserving it retains settings across app updates. * * @author Dmitriy Moroz */ diff --git a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/image/BackupImageDecoder.kt b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/image/BackupImageDecoder.kt new file mode 100644 index 000000000..75a94bbf4 --- /dev/null +++ b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/image/BackupImageDecoder.kt @@ -0,0 +1,22 @@ +package com.shifthackz.aisdv1.data.image + +/** + * Backup-specific native probing and bounded content decoding; never materializes the original bitmap. + * @author Dmitriy Moroz + */ +internal interface BackupImageDecoder { + /** + * Reads original pixel dimensions through metadata-only platform APIs before pixel allocation. + * @param bytes Encoded image already admitted by the shared byte budget. + * @author Dmitriy Moroz + */ + fun dimensions(bytes: ByteArray): Pair + + /** + * Rejects undecodable content by creating and immediately releasing a bounded native sample. + * @param bytes Encoded image whose original dimensions passed admission. + * @param maxEdge Maximum sample width and height in pixels. + * @author Dmitriy Moroz + */ + fun validateSample(bytes: ByteArray, maxEdge: Int) +} diff --git a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/image/BackupImageValidatorImpl.kt b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/image/BackupImageValidatorImpl.kt new file mode 100644 index 000000000..6c55fd709 --- /dev/null +++ b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/image/BackupImageValidatorImpl.kt @@ -0,0 +1,25 @@ +package com.shifthackz.aisdv1.data.image + +import com.shifthackz.aisdv1.domain.entity.backup.BackupImageBudget +import com.shifthackz.aisdv1.domain.gateway.backup.BackupImageValidator + +/** + * Admits native header dimensions before any content bitmap is allocated, then validates a small sample. + * @param decoder Backup-specific metadata probe and bounded platform content decoder. + * @param budget Shared encoded, original-pixel and sampled-allocation admission limits. + * @author Dmitriy Moroz + */ +internal class BackupImageValidatorImpl( + private val decoder: BackupImageDecoder, + private val budget: BackupImageBudget, +) : BackupImageValidator { + override fun invoke(bytes: ByteArray) { + require(bytes.isNotEmpty() && bytes.size <= budget.maxEncodedBytes) { "Backup image exceeds encoded budget" } + val (width, height) = decoder.dimensions(bytes) + require(width > 0 && height > 0 && width <= budget.maxPixels / height) { "Backup image exceeds pixel budget" } + val pixels = width * height + // PNG may carry 16-bit RGBA; use eight bytes per pixel without overflowing a multiplication. + require(pixels <= budget.maxDecodedBytes / 8) { "Backup image exceeds decoded byte budget" } + decoder.validateSample(bytes, budget.validationEdge) + } +} diff --git a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/image/PlatformBackupImageDecoder.kt b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/image/PlatformBackupImageDecoder.kt new file mode 100644 index 000000000..6b36fcc4d --- /dev/null +++ b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/image/PlatformBackupImageDecoder.kt @@ -0,0 +1,7 @@ +package com.shifthackz.aisdv1.data.image + +/** + * Supplies native metadata-only probing and sampled validation on each supported platform. + * @author Dmitriy Moroz + */ +internal expect class PlatformBackupImageDecoder() : BackupImageDecoder diff --git a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/ConfigurationMemoryMask.kt b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/ConfigurationMemoryMask.kt index 88971cab9..5b1084b74 100644 --- a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/ConfigurationMemoryMask.kt +++ b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/ConfigurationMemoryMask.kt @@ -8,6 +8,8 @@ package com.shifthackz.aisdv1.data.preference * @param booleans Trusted boolean entries immediately before replacement. * @param candidateStrings Exact string batch admitted for checked retry. * @param candidateBooleans Exact boolean batch admitted for checked retry. + * @param integers Trusted integer values before a checked settings batch. + * @param candidateIntegers Exact integer replacements retained for retry. * @author Dmitriy Moroz */ internal class ConfigurationMemoryMask( @@ -15,6 +17,8 @@ internal class ConfigurationMemoryMask( val booleans: Map, val candidateStrings: Map, val candidateBooleans: Map, + val integers: Map = emptyMap(), + val candidateIntegers: Map = emptyMap(), ) { /** * Identifies entries owned by the pending transaction, excluding unrelated settings. @@ -22,15 +26,21 @@ internal class ConfigurationMemoryMask( * @param key Preference key being accessed. * @author Dmitriy Moroz */ - fun contains(key: String): Boolean = strings.containsKey(key) || booleans.containsKey(key) + fun contains(key: String): Boolean = + strings.containsKey(key) || booleans.containsKey(key) || integers.containsKey(key) /** * Allows only a identical complete key/value batch to retry while reads are masked. * * @param strings Proposed string replacements. * @param booleans Proposed boolean replacements. + * @param integers Proposed integer replacements. * @author Dmitriy Moroz */ - fun matches(strings: Map, booleans: Map): Boolean = - candidateStrings == strings && candidateBooleans == booleans + fun matches( + strings: Map, + booleans: Map, + integers: Map = emptyMap() + ): Boolean = + candidateStrings == strings && candidateBooleans == booleans && candidateIntegers == integers } diff --git a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/KeyValueStore.kt b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/KeyValueStore.kt index f3e461680..02884e0fb 100644 --- a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/KeyValueStore.kt +++ b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/KeyValueStore.kt @@ -7,6 +7,29 @@ package com.shifthackz.aisdv1.data.preference * @author Dmitriy Moroz */ internal interface KeyValueStore { + /** Retries only an existing quarantined typed batch; false means no write was pending. @author Dmitriy Moroz */ + fun retryPendingWrite(): Boolean + + /** + * Distinguishes explicitly saved defaults from missing portable fields. + * @param key Existing preference key. + * @author Dmitriy Moroz + */ + fun contains(key: String): Boolean + + /** + * Checks one atomic typed settings batch before acknowledging restore. + * @param strings String replacements. + * @param booleans Boolean replacements. + * @param integers Integer replacements. + * @author Dmitriy Moroz + */ + fun putSettingsDurably( + strings: Map, + booleans: Map, + integers: Map + ) + /** * Reads a trusted string, using the caller fallback when its prior entry was absent. * diff --git a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupExportStateStoreImpl.kt b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupExportStateStoreImpl.kt new file mode 100644 index 000000000..054d3e1af --- /dev/null +++ b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupExportStateStoreImpl.kt @@ -0,0 +1,62 @@ +package com.shifthackz.aisdv1.data.preference.backup + +import com.shifthackz.aisdv1.data.preference.KeyValueStore +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportIntent +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportStatus +import com.shifthackz.aisdv1.domain.gateway.backup.BackupExportStateStore +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive + +/** + * Stores only export handles and result association in a separate checked preference suite. + * @param store Dedicated backup-operation preference owner; never the provider/settings suite. + * @author Dmitriy Moroz + */ +internal class BackupExportStateStoreImpl(private val store: KeyValueStore) : + BackupExportStateStore { + override fun recoverPendingWrite() { + store.retryPendingWrite() + } + + override fun read(): BackupExportIntent? { + val raw = store.getString(KEY) + if (raw.isEmpty()) return null + val fields = Json.parseToJsonElement(raw).jsonObject + check(fields.getValue("version").jsonPrimitive.content == "1") { "Unsupported pending export state" } + return validated( + BackupExportIntent( + fields.getValue("handle").jsonPrimitive.content, + fields.getValue("filename").jsonPrimitive.content, + BackupExportStatus.valueOf(fields.getValue("status").jsonPrimitive.content), + fields["destination"]?.jsonPrimitive?.content, + ) + ) + } + + override fun write(intent: BackupExportIntent) { + validated(intent) + store.putStringDurably(KEY, buildJsonObject { + put("version", JsonPrimitive(1)) + put("handle", JsonPrimitive(intent.handle)) + put("filename", JsonPrimitive(intent.filename)) + put("status", JsonPrimitive(intent.status.name)) + intent.destination?.let { put("destination", JsonPrimitive(it)) } + }.toString()) + } + + private fun validated(intent: BackupExportIntent): BackupExportIntent { + check(intent.handle.isNotBlank() && intent.filename.isNotBlank()) { "Missing pending export identity" } + check(intent.status != BackupExportStatus.NONE && intent.status != BackupExportStatus.PROCESSING) { "Invalid durable export stage" } + check(intent.status != BackupExportStatus.COPYING || !intent.destination.isNullOrBlank()) { "Missing pending export destination" } + return intent + } + + override fun clear() = store.putStringDurably(KEY, "") + + private companion object { + const val KEY = "pending_export" + } +} diff --git a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupPreferencesGatewayImpl.kt b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupPreferencesGatewayImpl.kt new file mode 100644 index 000000000..7ef06ca93 --- /dev/null +++ b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupPreferencesGatewayImpl.kt @@ -0,0 +1,223 @@ +package com.shifthackz.aisdv1.data.preference.backup + +import com.shifthackz.aisdv1.data.preference.KeyValueStore +import com.shifthackz.aisdv1.data.preference.readProviderSelection +import com.shifthackz.aisdv1.domain.preference.PreferenceManager +import com.shifthackz.aisdv1.domain.entity.Grid +import com.shifthackz.aisdv1.domain.entity.ColorToken +import com.shifthackz.aisdv1.domain.entity.DarkThemeToken +import com.shifthackz.aisdv1.domain.entity.NetworkTimeout +import com.shifthackz.aisdv1.domain.entity.MnnBackend +import com.shifthackz.aisdv1.domain.entity.Configuration +import com.shifthackz.aisdv1.domain.entity.HuggingFaceModel +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.entity.backup.BackupPreferences +import com.shifthackz.aisdv1.domain.entity.backup.BackupValue +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage +import com.shifthackz.aisdv1.domain.gateway.backup.BackupPreferencesGateway + +/** + * Reads and checks portable preference batches without publishing partial or untrusted writes. + * @param store Shared typed preference owner, also used by normal settings/configuration. + * @param preferences Effective user settings, including defaults that have never been explicitly saved. + * @author Dmitriy Moroz + */ +internal class BackupPreferencesGatewayImpl( + private val store: KeyValueStore, + private val preferences: PreferenceManager +) : BackupPreferencesGateway { + override fun recoverPendingWrite(): Set { + val previous = read() + val authorizationCommit = store.getString("key_authorization_commit_id") + val selection = store.getString("key_provider_selection_state") + if (!store.retryPendingWrite()) return emptySet() + val current = read() + return buildSet { + if (previous.providers != current.providers || authorizationCommit != store.getString("key_authorization_commit_id") || selection != store.getString( + "key_provider_selection_state" + ) + ) add(BackupCategory.PROVIDERS) + if (previous.settings != current.settings) add(BackupCategory.SETTINGS) + } + } + + override fun filterSupported(preferences: BackupPreferences) = BackupPreferences( + providers = preferences.providers.mapNotNull { (provider, values) -> + val schema = PortablePreferenceSchema.providers[provider] ?: return@mapNotNull null + provider to filterFields(values, schema) + }.toMap(), + settings = filterFields(preferences.settings, PortablePreferenceSchema.settings), + ) + + private fun filterFields( + values: Map, + schema: Map + ): Map = values.filter { (id, value) -> + val field = schema[id] ?: return@filter false + val hasCorrectType = when (field.type) { + PortablePreferenceType.TEXT -> value is BackupValue.Text + PortablePreferenceType.FLAG -> value is BackupValue.Flag + PortablePreferenceType.INTEGER -> value is BackupValue.Integer + } + require(hasCorrectType) { "Invalid portable preference type" } + when (id) { + "backend" -> (value as BackupValue.Text).value in MnnBackend.entries.map { it.key } + "colorToken" -> (value as BackupValue.Text).value in ColorToken.entries.map { it.name } + "darkToken" -> (value as BackupValue.Text).value in DarkThemeToken.entries.map { it.name } + "galleryGrid" -> (value as BackupValue.Integer).value in Grid.entries.indices + "connectionTimeout", "generationTimeout" -> (value as BackupValue.Integer).value in NetworkTimeout.entries.map { it.seconds } + "textToImageSteps", "imageToImageSteps" -> (value as BackupValue.Integer).value > 0 + "textToImageCfg", "imageToImageCfg" -> (value as BackupValue.Text).value.toFloatOrNull() + ?.let { it.isFinite() && it >= 0 } == true + + "language" -> (value as BackupValue.Text).value in setOf( + "", + "en", + "de", + "ru", + "tr", + "uk", + "zh" + ) + + else -> true + } + } + + override fun read() = BackupPreferences( + providers = PortablePreferenceSchema.providers.mapValues { (_, fields) -> readFields(fields) } + .filter { (provider, fields) -> hasProviderConfiguration(provider, fields) }, + settings = mapOf( + "dynamicColors" to BackupValue.Flag(preferences.designUseSystemColorPalette), + "systemDarkTheme" to BackupValue.Flag(preferences.designUseSystemDarkTheme), + "darkTheme" to BackupValue.Flag(preferences.designDarkTheme), + "colorToken" to BackupValue.Text(preferences.designColorToken), + "darkToken" to BackupValue.Text(preferences.designDarkThemeToken), + "language" to BackupValue.Text(preferences.languageCode), + "galleryGrid" to BackupValue.Integer(preferences.galleryGrid.ordinal), + "autoSave" to BackupValue.Flag(preferences.autoSaveAiResults), + "saveToMediaStore" to BackupValue.Flag(preferences.saveToMediaStore), + "advancedOptions" to BackupValue.Flag(preferences.formAdvancedOptionsAlwaysShow), + "taggedInput" to BackupValue.Flag(preferences.formPromptTaggedInput), + "connectionTimeout" to BackupValue.Integer(preferences.connectionTimeout.seconds), + "generationTimeout" to BackupValue.Integer(preferences.generationRequestTimeout.seconds), + "backgroundGeneration" to BackupValue.Flag(preferences.backgroundGeneration), + "monitorConnection" to BackupValue.Flag(preferences.monitorConnectivity), + "textToImageSteps" to BackupValue.Integer(preferences.textToImageSamplingSteps), + "textToImageCfg" to BackupValue.Text(preferences.textToImageCfgScale.toString()), + "imageToImageSteps" to BackupValue.Integer(preferences.imageToImageSamplingSteps), + "imageToImageCfg" to BackupValue.Text(preferences.imageToImageCfgScale.toString()), + ), + ) + + override fun writeProviders( + providers: Map>, + authorizationCommitId: String? + ) { + val fields = providers.flatMap { (provider, values) -> + val schema = PortablePreferenceSchema.providers[provider].orEmpty() + values.mapNotNull { (id, value) -> schema[id]?.let { it to value } } + }.toMap() + val strings = mutableMapOf() + val flags = mutableMapOf() + collect(fields, strings, flags, mutableMapOf()) + authorizationCommitId?.let { strings["key_authorization_commit_id"] = it } + val selection = store.readProviderSelection() + val source = selection.first.key + if (providers.containsKey(source) && (authorizationCommitId != null || fields.any { (field, value) -> + readField( + field + ) != value + })) { + val revision = selection.second + check(revision < Long.MAX_VALUE) { "Provider revision exhausted" } + strings["key_provider_selection_state"] = "$source|${revision + 1}" + } + store.putConfigurationDurably(strings, flags) + } + + override fun writeSettings(settings: Map) { + val fields = + settings.mapNotNull { (id, value) -> PortablePreferenceSchema.settings[id]?.let { it to value } } + .toMap() + val strings = mutableMapOf() + val flags = mutableMapOf() + val integers = mutableMapOf() + collect(fields, strings, flags, integers) + store.putSettingsDurably(strings, flags, integers) + } + + override fun readStartupStage(): BackupStartupStage = + BackupStartupStage.entries.firstOrNull { it.name == store.getString("key_backup_startup_stage") } + ?: if (store.getBoolean("key_on_boarding_complete")) BackupStartupStage.COMPLETE else BackupStartupStage.INVITATION + + override fun writeStartupStage(stage: BackupStartupStage) { + if (stage == BackupStartupStage.INVITATION) { + store.putConfigurationDurably( + mapOf("key_backup_startup_stage" to stage.name), + mapOf("key_on_boarding_complete" to true) + ) + } else store.putStringDurably("key_backup_startup_stage", stage.name) + } + + /** + * Distinguishes legacy complete-snapshot defaults from saved provider or partial setup data. + * Normal configuration commits materialize every provider's empty/default fields; those alone + * cannot make a provider configured or consume the shared Basic Auth association. + * @param provider Stable provider wire identifier. + * @param fields Persisted portable values, retaining explicit defaults for an existing configuration. + * @author Dmitriy Moroz + */ + private fun hasProviderConfiguration( + provider: String, + fields: Map + ): Boolean = + fields.any { (id, value) -> + when (value) { + is BackupValue.Flag -> value.isTrue + is BackupValue.Integer -> value.value != 0 + is BackupValue.Text -> { + val implicitDefault = when { + provider == "open_ai_compatible" && id == "model" -> Configuration().openAiCompatibleModel + provider == "hugging_face" && id == "model" -> HuggingFaceModel.default.alias + provider == "local_mnn" && id == "backend" -> MnnBackend.CPU.key + else -> "" + } + value.value.isNotBlank() && value.value != implicitDefault + } + + BackupValue.Unsupported -> false + } + } + + private fun readFields(fields: Map): Map = + fields.filterValues { store.contains(it.key) }.mapValues { (_, field) -> readField(field) } + + private fun readField(field: PortablePreferenceField): BackupValue = when (field.type) { + PortablePreferenceType.TEXT -> BackupValue.Text(store.getString(field.key)) + PortablePreferenceType.FLAG -> BackupValue.Flag(store.getBoolean(field.key)) + PortablePreferenceType.INTEGER -> BackupValue.Integer(store.getInt(field.key)) + } + + private fun collect( + fields: Map, + strings: MutableMap, + flags: MutableMap, + integers: MutableMap + ) { + fields.forEach { (field, value) -> + when { + field.type == PortablePreferenceType.TEXT && value is BackupValue.Text -> strings[field.key] = + value.value + + field.type == PortablePreferenceType.FLAG && value is BackupValue.Flag -> flags[field.key] = + value.isTrue + + field.type == PortablePreferenceType.INTEGER && value is BackupValue.Integer -> integers[field.key] = + value.value + + else -> error("Invalid portable preference type") + } + } + } +} diff --git a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/PortablePreferenceField.kt b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/PortablePreferenceField.kt new file mode 100644 index 000000000..1b67f1412 --- /dev/null +++ b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/PortablePreferenceField.kt @@ -0,0 +1,9 @@ +package com.shifthackz.aisdv1.data.preference.backup + +/** + * Storage binding for one stable portable field. + * @param key Existing platform preference key. + * @param type Expected persisted value type. + * @author Dmitriy Moroz + */ +internal data class PortablePreferenceField(val key: String, val type: PortablePreferenceType) diff --git a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/PortablePreferenceSchema.kt b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/PortablePreferenceSchema.kt new file mode 100644 index 000000000..fcaf12d17 --- /dev/null +++ b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/PortablePreferenceSchema.kt @@ -0,0 +1,174 @@ +package com.shifthackz.aisdv1.data.preference.backup + +/** + * Wire-to-storage allowlist. Keys outside these maps can never be imported from a backup. + * @author Dmitriy Moroz + */ +internal object PortablePreferenceSchema { + val providers = mapOf( + "custom" to mapOf( + "serverUrl" to PortablePreferenceField("key_server_url", PortablePreferenceType.TEXT), + "demoMode" to PortablePreferenceField("key_demo_mode", PortablePreferenceType.FLAG), + "model" to PortablePreferenceField("key_sd_model", PortablePreferenceType.TEXT) + ), + "swarm_ui" to mapOf( + "serverUrl" to PortablePreferenceField( + "key_swarm_server_url", + PortablePreferenceType.TEXT + ), + "model" to PortablePreferenceField("key_swarm_model", PortablePreferenceType.TEXT) + ), + "easy_diffusion" to mapOf( + "serverUrl" to PortablePreferenceField( + "key_easy_diffusion_url", + PortablePreferenceType.TEXT + ), + "model" to PortablePreferenceField( + "key_easy_diffusion_model", + PortablePreferenceType.TEXT + ) + ), + "open_ai_compatible" to mapOf( + "serverUrl" to PortablePreferenceField( + "key_open_ai_compatible_url", + PortablePreferenceType.TEXT + ), + "model" to PortablePreferenceField( + "key_open_ai_compatible_model", + PortablePreferenceType.TEXT + ), + "apiKey" to PortablePreferenceField( + "key_open_ai_compatible_api_key", + PortablePreferenceType.TEXT + ) + ), + "open_ai" to mapOf( + "apiKey" to PortablePreferenceField("key_open_ai_api_key", PortablePreferenceType.TEXT) + ), + "horde" to mapOf( + "apiKey" to PortablePreferenceField("key_horde_api_key", PortablePreferenceType.TEXT) + ), + "hugging_face" to mapOf( + "apiKey" to PortablePreferenceField( + "key_hugging_face_api_key", + PortablePreferenceType.TEXT + ), + "model" to PortablePreferenceField( + "key_hugging_face_model_key", + PortablePreferenceType.TEXT + ) + ), + "stability_ai" to mapOf( + "apiKey" to PortablePreferenceField( + "key_stability_ai_api_key", + PortablePreferenceType.TEXT + ), + "model" to PortablePreferenceField( + "key_stability_ai_engine_id_key", + PortablePreferenceType.TEXT + ) + ), + "fal_ai" to mapOf( + "apiKey" to PortablePreferenceField("key_fal_ai_api_key", PortablePreferenceType.TEXT) + ), + "arli_ai" to mapOf( + "apiKey" to PortablePreferenceField("key_arli_ai_api_key", PortablePreferenceType.TEXT), + "model" to PortablePreferenceField("key_arli_ai_model_key", PortablePreferenceType.TEXT) + ), + "local" to mapOf( + "model" to PortablePreferenceField("key_local_model_id", PortablePreferenceType.TEXT), + "useNnapi" to PortablePreferenceField("key_local_nn_api", PortablePreferenceType.FLAG) + ), + "local_google_media_pipe" to mapOf( + "model" to PortablePreferenceField( + "key_mediapipe_model_id", + PortablePreferenceType.TEXT + ) + ), + "local_stable_diffusion_cpp" to mapOf( + "model" to PortablePreferenceField("key_sdxl_model_id", PortablePreferenceType.TEXT) + ), + "local_apple_core_ml" to mapOf( + "model" to PortablePreferenceField("key_core_ml_model_id", PortablePreferenceType.TEXT) + ), + "local_apple_bonsai" to mapOf( + "model" to PortablePreferenceField("key_bonsai_model_id", PortablePreferenceType.TEXT) + ), + "local_mnn" to mapOf( + "model" to PortablePreferenceField("key_mnn_model_id", PortablePreferenceType.TEXT), + "backend" to PortablePreferenceField("key_mnn_backend", PortablePreferenceType.TEXT) + ) + ) + val settings = mapOf( + "dynamicColors" to PortablePreferenceField( + "key_design_dynamic_colors", + PortablePreferenceType.FLAG + ), + "systemDarkTheme" to PortablePreferenceField( + "key_design_system_dark_theme", + PortablePreferenceType.FLAG + ), + "darkTheme" to PortablePreferenceField( + "key_design_dark_theme", + PortablePreferenceType.FLAG + ), + "colorToken" to PortablePreferenceField( + "key_design_color_token_theme", + PortablePreferenceType.TEXT + ), + "darkToken" to PortablePreferenceField( + "key_design_dark_color_token_theme", + PortablePreferenceType.TEXT + ), + "language" to PortablePreferenceField("key_language_code", PortablePreferenceType.TEXT), + "galleryGrid" to PortablePreferenceField( + "key_gallery_grid", + PortablePreferenceType.INTEGER + ), + "autoSave" to PortablePreferenceField("key_ai_auto_save", PortablePreferenceType.FLAG), + "saveToMediaStore" to PortablePreferenceField( + "key_save_to_media_store", + PortablePreferenceType.FLAG + ), + "advancedOptions" to PortablePreferenceField( + "key_always_show_advanced_options", + PortablePreferenceType.FLAG + ), + "taggedInput" to PortablePreferenceField( + "key_prompt_tagged_input_kb", + PortablePreferenceType.FLAG + ), + "connectionTimeout" to PortablePreferenceField( + "key_connection_timeout_seconds", + PortablePreferenceType.INTEGER + ), + "generationTimeout" to PortablePreferenceField( + "key_generation_request_timeout_seconds", + PortablePreferenceType.INTEGER + ), + "backgroundGeneration" to PortablePreferenceField( + "key_background_generation", + PortablePreferenceType.FLAG + ), + "monitorConnection" to PortablePreferenceField( + "key_monitor_connection", + PortablePreferenceType.FLAG + ), + "textToImageSteps" to PortablePreferenceField( + "key_text_to_image_sampling_steps", + PortablePreferenceType.INTEGER + ), + "textToImageCfg" to PortablePreferenceField( + "key_text_to_image_cfg_scale", + PortablePreferenceType.TEXT + ), + "imageToImageSteps" to PortablePreferenceField( + "key_image_to_image_sampling_steps", + PortablePreferenceType.INTEGER + ), + "imageToImageCfg" to PortablePreferenceField( + "key_image_to_image_cfg_scale", + PortablePreferenceType.TEXT + ) + ) +} diff --git a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/PortablePreferenceType.kt b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/PortablePreferenceType.kt new file mode 100644 index 000000000..53af3040a --- /dev/null +++ b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/PortablePreferenceType.kt @@ -0,0 +1,7 @@ +package com.shifthackz.aisdv1.data.preference.backup + +/** + * Allowed platform preference primitives; arbitrary objects are not portable. + * @author Dmitriy Moroz + */ +internal enum class PortablePreferenceType { TEXT, FLAG, INTEGER } diff --git a/data/src/iosMain/kotlin/com/shifthackz/aisdv1/data/image/PlatformBackupImageDecoder.ios.kt b/data/src/iosMain/kotlin/com/shifthackz/aisdv1/data/image/PlatformBackupImageDecoder.ios.kt new file mode 100644 index 000000000..c513af0cf --- /dev/null +++ b/data/src/iosMain/kotlin/com/shifthackz/aisdv1/data/image/PlatformBackupImageDecoder.ios.kt @@ -0,0 +1,202 @@ +@file:OptIn(ExperimentalForeignApi::class) + +package com.shifthackz.aisdv1.data.image + +import kotlinx.cinterop.ExperimentalForeignApi +import kotlinx.cinterop.IntVar +import kotlinx.cinterop.LongVar +import kotlinx.cinterop.addressOf +import kotlinx.cinterop.alloc +import kotlinx.cinterop.memScoped +import kotlinx.cinterop.ptr +import kotlinx.cinterop.reinterpret +import kotlinx.cinterop.usePinned +import kotlinx.cinterop.value +import platform.CoreFoundation.CFDataCreate +import platform.CoreFoundation.CFDictionaryCreateMutable +import platform.CoreFoundation.CFDictionarySetValue +import platform.CoreFoundation.CFDictionaryGetValue +import platform.CoreFoundation.CFDictionaryRef +import platform.CoreFoundation.CFNumberCreate +import platform.CoreFoundation.CFNumberGetValue +import platform.CoreFoundation.CFRelease +import platform.CoreFoundation.CFStringRef +import platform.CoreFoundation.kCFAllocatorDefault +import platform.CoreFoundation.kCFBooleanTrue +import platform.CoreFoundation.kCFBooleanFalse +import platform.CoreFoundation.kCFNumberIntType +import platform.CoreFoundation.kCFTypeDictionaryKeyCallBacks +import platform.CoreFoundation.kCFTypeDictionaryValueCallBacks +import platform.CoreFoundation.kCFNumberSInt64Type +import platform.CoreGraphics.CGImageGetBytesPerRow +import platform.CoreGraphics.CGImageGetHeight +import platform.CoreGraphics.CGImageGetWidth +import platform.CoreGraphics.CGImageRelease +import platform.ImageIO.CGImageSourceCopyPropertiesAtIndex +import platform.ImageIO.CGImageSourceCreateThumbnailAtIndex +import platform.ImageIO.CGImageSourceCreateWithData +import platform.ImageIO.CGImageSourceGetStatusAtIndex +import platform.ImageIO.CGImageSourceRef +import platform.ImageIO.kCGImagePropertyPixelHeight +import platform.ImageIO.kCGImagePropertyPixelWidth +import platform.ImageIO.kCGImageSourceCreateThumbnailFromImageAlways +import platform.ImageIO.kCGImageSourceShouldCache +import platform.ImageIO.kCGImageSourceShouldCacheImmediately +import platform.ImageIO.kCGImageSourceThumbnailMaxPixelSize +import platform.ImageIO.kCGImageStatusComplete + +/** + * Reads uncached ImageIO properties before creating only a bounded thumbnail for content validation. + * @author Dmitriy Moroz + */ +internal actual class PlatformBackupImageDecoder actual constructor() : BackupImageDecoder { + override fun dimensions(bytes: ByteArray): Pair = withSource(bytes) { source -> + val properties = requireNotNull( + CGImageSourceCopyPropertiesAtIndex( + source, + 0u, + null + ) + ) { "Invalid backup image properties" } + try { + dimension(properties, kCGImagePropertyPixelWidth) to dimension( + properties, + kCGImagePropertyPixelHeight + ) + } finally { + CFRelease(properties) + } + } + + override fun validateSample(bytes: ByteArray, maxEdge: Int) = withSource(bytes) { source -> + val options = imageOptions(maxEdge) + try { + val image = requireNotNull( + CGImageSourceCreateThumbnailAtIndex( + source, + 0u, + options + ) + ) { "Invalid backup image content" } + try { + val width = CGImageGetWidth(image).toLong() + val height = CGImageGetHeight(image).toLong() + val rowBytes = CGImageGetBytesPerRow(image).toLong() + require(width in 1..maxEdge.toLong() && height in 1..maxEdge.toLong()) { "Backup sample exceeds bounds" } + require(rowBytes > 0 && rowBytes <= maxEdge.toLong() * maxEdge * 8 / height) { "Backup sample exceeds byte budget" } + require( + CGImageSourceGetStatusAtIndex( + source, + 0u + ) == kCGImageStatusComplete + ) { "Incomplete backup image content" } + } finally { + CGImageRelease(image) + } + } finally { + CFRelease(options) + } + } + + /** + * Creates an owned CF dictionary with native CFString keys and retained CFBoolean/CFNumber values. + * @param maxEdge Thumbnail edge, or null for metadata-only source options with pixel caching disabled. + * @author Dmitriy Moroz + */ + private fun imageOptions(maxEdge: Int?): CFDictionaryRef = memScoped { + val options = requireNotNull( + CFDictionaryCreateMutable( + kCFAllocatorDefault, + 0, + kCFTypeDictionaryKeyCallBacks.ptr, + kCFTypeDictionaryValueCallBacks.ptr, + ) + ) + try { + if (maxEdge == null) { + CFDictionarySetValue(options, kCGImageSourceShouldCache, kCFBooleanFalse) + } else { + CFDictionarySetValue( + options, + kCGImageSourceCreateThumbnailFromImageAlways, + kCFBooleanTrue + ) + CFDictionarySetValue(options, kCGImageSourceShouldCacheImmediately, kCFBooleanTrue) + val edge = alloc() + edge.value = maxEdge + val number = + requireNotNull(CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, edge.ptr)) + try { + CFDictionarySetValue(options, kCGImageSourceThumbnailMaxPixelSize, number) + } finally { + CFRelease(number) + } + } + options + } catch (failure: Throwable) { + CFRelease(options) + throw failure + } + } + + /** + * Extracts an integral native dimension without rasterizing the encoded image. + * @param properties ImageIO metadata dictionary retained by the caller. + * @param key Native pixel width or height property identifier. + * @author Dmitriy Moroz + */ + private fun dimension(properties: CFDictionaryRef, key: CFStringRef?): Long = memScoped { + val number = requireNotNull( + CFDictionaryGetValue( + properties, + key + ) + ) { "Missing backup image dimension" } + val result = alloc() + require( + CFNumberGetValue( + number.reinterpret(), + kCFNumberSInt64Type, + result.ptr + ) + ) { "Invalid backup image dimension" } + result.value + } + + /** + * Creates a metadata-only source with deferred pixel caching, releasing every native owner on failure. + * @param bytes Bounded encoded image retained by the caller. + * @param block Metadata probing or sampled validation before native source release. + * @author Dmitriy Moroz + */ + private fun withSource(bytes: ByteArray, block: (CGImageSourceRef) -> T): T { + require(bytes.isNotEmpty()) { "Empty backup image" } + val data = requireNotNull(bytes.usePinned { + CFDataCreate( + kCFAllocatorDefault, + it.addressOf(0).reinterpret(), + bytes.size.toLong() + ) + }) + try { + val options = imageOptions(null) + val source = try { + requireNotNull( + CGImageSourceCreateWithData( + data, + options + ) + ) { "Invalid backup image" } + } finally { + CFRelease(options) + } + try { + return block(source) + } finally { + CFRelease(source) + } + } finally { + CFRelease(data) + } + } +} diff --git a/data/src/iosMain/kotlin/com/shifthackz/aisdv1/data/preference/AppleKeyValueStore.ios.kt b/data/src/iosMain/kotlin/com/shifthackz/aisdv1/data/preference/AppleKeyValueStore.ios.kt index 50bf4b8a4..59ca37809 100644 --- a/data/src/iosMain/kotlin/com/shifthackz/aisdv1/data/preference/AppleKeyValueStore.ios.kt +++ b/data/src/iosMain/kotlin/com/shifthackz/aisdv1/data/preference/AppleKeyValueStore.ios.kt @@ -33,6 +33,28 @@ private class NsUserDefaultsKeyValueStore( } } + /** + * Reports trusted persisted presence, including explicitly saved default values. + * @param key Existing preference key. + * @author Dmitriy Moroz + */ + override fun contains(key: String): Boolean = withMemoryLock { + val mask = configurationMask + when { + mask?.strings?.containsKey(key) == true -> mask.strings[key] != null + mask?.booleans?.containsKey(key) == true -> mask.booleans[key] != null + mask?.integers?.containsKey(key) == true -> mask.integers[key] != null + else -> defaults.objectForKey(key) != null + } + } + + /** Finishes the exact quarantined write before a restore session may be abandoned. @author Dmitriy Moroz */ + override fun retryPendingWrite(): Boolean { + val batch = withMemoryLock { configurationMask } ?: return false + putSettingsDurably(batch.candidateStrings, batch.candidateBooleans, batch.candidateIntegers) + return true + } + private var configurationMask: ConfigurationMemoryMask? = null private var isBatchInFlight = false @@ -83,11 +105,29 @@ private class NsUserDefaultsKeyValueStore( override fun putConfigurationDurably( strings: Map, booleans: Map + ) = putSettingsDurably(strings, booleans, emptyMap()) + + /** + * Persists a complete typed backup settings batch with the same quarantine as configuration. + * @param strings String replacements. + * @param booleans Boolean replacements. + * @param integers Integer replacements. + * @author Dmitriy Moroz + */ + override fun putSettingsDurably( + strings: Map, + booleans: Map, + integers: Map, ) { val batch = withMemoryLock { if (isBatchInFlight) persistenceFailure() val current = configurationMask - if (current != null && !current.matches(strings, booleans)) persistenceFailure() + if (current != null && !current.matches( + strings, + booleans, + integers + ) + ) persistenceFailure() if (current == null) configurationMask = ConfigurationMemoryMask( strings.keys.associateWith { key -> defaults.stringForKey(key) }, booleans.keys.associateWith { key -> @@ -97,6 +137,12 @@ private class NsUserDefaultsKeyValueStore( }, strings.toMap(), booleans.toMap(), + integers.keys.associateWith { key -> + if (defaults.objectForKey(key) != null) defaults.integerForKey( + key + ).toInt() else null + }, + integers.toMap(), ) isBatchInFlight = true checkNotNull(configurationMask) @@ -105,7 +151,7 @@ private class NsUserDefaultsKeyValueStore( try { withMemoryLock { val domain = defaults.persistentDomainForName(name) - .orEmpty() + batch.candidateStrings + batch.candidateBooleans + .orEmpty() + batch.candidateStrings + batch.candidateBooleans + batch.candidateIntegers defaults.setPersistentDomain(domain, name) } check(defaults.synchronize()) { "Configuration persistence failed" } @@ -151,7 +197,10 @@ private class NsUserDefaultsKeyValueStore( * @author Dmitriy Moroz */ override fun getInt(key: String, default: Int): Int = withMemoryLock { - if (defaults.objectForKey(key) == null) default else defaults.integerForKey(key).toInt() + val mask = configurationMask + if (mask?.integers?.containsKey(key) == true) mask.integers[key] ?: default + else if (defaults.objectForKey(key) == null) default else defaults.integerForKey(key) + .toInt() } /** diff --git a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/mocks/ImmediateGenerationRestoreGate.kt b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/mocks/ImmediateGenerationRestoreGate.kt new file mode 100644 index 000000000..53800025f --- /dev/null +++ b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/mocks/ImmediateGenerationRestoreGate.kt @@ -0,0 +1,9 @@ +package com.shifthackz.aisdv1.domain.mocks + +import com.shifthackz.aisdv1.domain.gateway.GenerationRestoreGate + +/** Runs isolated generation component cases without the feature-owned process admission state. @author Dmitriy Moroz */ +class ImmediateGenerationRestoreGate : GenerationRestoreGate { + override suspend fun generating(block: suspend () -> T): T = block() + override suspend fun restoring(block: suspend () -> T): T = block() +} diff --git a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/ImageToImageUseCaseImplTest.kt b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/ImageToImageUseCaseImplTest.kt index 9081c1126..97cb2780e 100644 --- a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/ImageToImageUseCaseImplTest.kt +++ b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/ImageToImageUseCaseImplTest.kt @@ -1,5 +1,6 @@ package com.shifthackz.aisdv1.domain.usecase.generation +import com.shifthackz.aisdv1.domain.mocks.ImmediateGenerationRestoreGate import com.shifthackz.aisdv1.domain.entity.ServerSource import com.shifthackz.aisdv1.domain.entity.EasyDiffusionConnection import com.shifthackz.aisdv1.domain.entity.EasyDiffusionRequest @@ -48,6 +49,7 @@ class ImageToImageUseCaseImplTest { private val generateEasyDiffusion = mockk() private val captureEasyDiffusion = mockk() private val useCase = ImageToImageUseCaseImpl( + generationRestoreGate = ImmediateGenerationRestoreGate(), generateEasyDiffusionUseCase = generateEasyDiffusion, captureEasyDiffusionConnectionUseCase = captureEasyDiffusion, stableDiffusionGenerationRepository = stubStableDiffusionGenerationRepository, @@ -62,8 +64,9 @@ class ImageToImageUseCaseImplTest { ) @Test - fun `Easy Diffusion captures one immutable connection and delegates the complete batch once`() = + fun `given Easy Diffusion generation, complete batch is submitted, generation is requested, expected one immutable connection capture`() = runTest { + // Given every { stubPreferenceManager.source } returns ServerSource.EASY_DIFFUSION val connection = EasyDiffusionConnection("https://server.example", "folder/model", 7) coEvery { captureEasyDiffusion(7, null) } returns connection @@ -74,7 +77,10 @@ class ImageToImageUseCaseImplTest { sourceSnapshot = ServerSource.EASY_DIFFUSION, providerSelectionRevision = 7, batchCount = 3, seed = "4294967295", base64Image = "AQID", denoisingStrength = 0.5f ) - assertSame(results, useCase(payload)) + // When + val actual = useCase(payload) + // Then + assertSame(results, actual) assertEquals(connection.url, request.captured.url) assertEquals(connection.model, request.captured.model) assertEquals(7L, request.captured.selectionRevision) @@ -84,179 +90,265 @@ class ImageToImageUseCaseImplTest { } @Test - fun `stale Easy Diffusion capture stops dispatch before any generation`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.EASY_DIFFUSION - coEvery { captureEasyDiffusion(6, null) } throws stubException - assertSame(stubException, runCatching { - useCase( - mockImageToImagePayload.copy( - sourceSnapshot = ServerSource.EASY_DIFFUSION, - providerSelectionRevision = 6, base64Image = "AQID", denoisingStrength = 0.5f + fun `given Easy Diffusion generation, captured connection is stale, generation is requested, expected no generation dispatch`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.EASY_DIFFUSION + coEvery { captureEasyDiffusion(6, null) } throws stubException + // When + val actual = runCatching { + useCase( + mockImageToImagePayload.copy( + sourceSnapshot = ServerSource.EASY_DIFFUSION, + providerSelectionRevision = 6, + base64Image = "AQID", + denoisingStrength = 0.5f + ) ) - ) - }.exceptionOrNull()) - coVerify(exactly = 0) { generateEasyDiffusion(any()) } - } + } + // Then + assertSame(stubException, actual.exceptionOrNull()) + coVerify(exactly = 0) { generateEasyDiffusion(any()) } + } @Test - fun `given source is AUTOMATIC1111, expected stable diffusion generation`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.AUTOMATIC1111 - coEvery { stubStableDiffusionGenerationRepository.generateFromImage(any()) } returns listOf( - mockAiGenerationResult - ) + fun `given source is AUTOMATIC1111, generation is requested, expected stable diffusion generation`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.AUTOMATIC1111 + coEvery { stubStableDiffusionGenerationRepository.generateFromImage(any()) } returns listOf( + mockAiGenerationResult + ) - val actual = useCase(mockImageToImagePayload.copy(batchCount = 1)) + // When - assertEquals(listOf(mockAiGenerationResult), actual) - coVerify(exactly = 1) { stubStableDiffusionGenerationRepository.generateFromImage(any()) } - } + val actual = useCase(mockImageToImagePayload.copy(batchCount = 1)) + + // Then + + assertEquals(listOf(mockAiGenerationResult), actual) + coVerify(exactly = 1) { stubStableDiffusionGenerationRepository.generateFromImage(any()) } + } @Test - fun `given source is SWARM_UI, expected swarm ui generation`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.SWARM_UI - coEvery { stubSwarmUiGenerationRepository.generateFromImage(any()) } returns mockAiGenerationResult + fun `given source is SWARM_UI, generation is requested, expected swarm ui generation`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.SWARM_UI + coEvery { stubSwarmUiGenerationRepository.generateFromImage(any()) } returns mockAiGenerationResult - val actual = useCase(mockImageToImagePayload.copy(batchCount = 1)) + // When - assertEquals(listOf(mockAiGenerationResult), actual) - coVerify(exactly = 1) { stubSwarmUiGenerationRepository.generateFromImage(any()) } - } + val actual = useCase(mockImageToImagePayload.copy(batchCount = 1)) + + // Then + + assertEquals(listOf(mockAiGenerationResult), actual) + coVerify(exactly = 1) { stubSwarmUiGenerationRepository.generateFromImage(any()) } + } @Test - fun `given source is HORDE, expected horde generation`() = runTest { + fun `given source is HORDE, generation is requested, expected horde generation`() = runTest { + // Given every { stubPreferenceManager.source } returns ServerSource.HORDE coEvery { stubHordeGenerationRepository.generateFromImage(any()) } returns mockAiGenerationResult + // When + val actual = useCase(mockImageToImagePayload.copy(batchCount = 1)) + // Then + assertEquals(listOf(mockAiGenerationResult), actual) coVerify(exactly = 1) { stubHordeGenerationRepository.generateFromImage(any()) } } @Test - fun `given source is HUGGING_FACE, expected hugging face generation`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.HUGGING_FACE - coEvery { stubHuggingFaceGenerationRepository.generateFromImage(any()) } returns mockAiGenerationResult + fun `given source is HUGGING_FACE, generation is requested, expected hugging face generation`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.HUGGING_FACE + coEvery { stubHuggingFaceGenerationRepository.generateFromImage(any()) } returns mockAiGenerationResult - val actual = useCase(mockImageToImagePayload.copy(batchCount = 1)) + // When - assertEquals(listOf(mockAiGenerationResult), actual) - coVerify(exactly = 1) { stubHuggingFaceGenerationRepository.generateFromImage(any()) } - } + val actual = useCase(mockImageToImagePayload.copy(batchCount = 1)) + + // Then + + assertEquals(listOf(mockAiGenerationResult), actual) + coVerify(exactly = 1) { stubHuggingFaceGenerationRepository.generateFromImage(any()) } + } @Test - fun `given source is STABILITY_AI, expected stability ai generation`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.STABILITY_AI - coEvery { stubStabilityAiGenerationRepository.generateFromImage(any()) } returns mockAiGenerationResult + fun `given source is STABILITY_AI, generation is requested, expected stability ai generation`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.STABILITY_AI + coEvery { stubStabilityAiGenerationRepository.generateFromImage(any()) } returns mockAiGenerationResult - val actual = useCase(mockImageToImagePayload.copy(batchCount = 1)) + // When - assertEquals(listOf(mockAiGenerationResult), actual) - coVerify(exactly = 1) { stubStabilityAiGenerationRepository.generateFromImage(any()) } - } + val actual = useCase(mockImageToImagePayload.copy(batchCount = 1)) + + // Then + + assertEquals(listOf(mockAiGenerationResult), actual) + coVerify(exactly = 1) { stubStabilityAiGenerationRepository.generateFromImage(any()) } + } @Test - fun `given source is LOCAL_APPLE_CORE_ML, expected core ml generation`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.LOCAL_APPLE_CORE_ML - coEvery { stubCoreMlGenerationRepository.generateFromImage(any()) } returns mockAiGenerationResult + fun `given source is LOCAL_APPLE_CORE_ML, generation is requested, expected core ml generation`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.LOCAL_APPLE_CORE_ML + coEvery { stubCoreMlGenerationRepository.generateFromImage(any()) } returns mockAiGenerationResult - val actual = useCase(mockImageToImagePayload.copy(batchCount = 1)) + // When - assertEquals(listOf(mockAiGenerationResult), actual) - coVerify(exactly = 1) { stubCoreMlGenerationRepository.generateFromImage(any()) } - } + val actual = useCase(mockImageToImagePayload.copy(batchCount = 1)) + + // Then + + assertEquals(listOf(mockAiGenerationResult), actual) + coVerify(exactly = 1) { stubCoreMlGenerationRepository.generateFromImage(any()) } + } @Test - fun `given source is FAL_AI, expected fal ai generation`() = runTest { + fun `given source is FAL_AI, generation is requested, expected fal ai generation`() = runTest { + // Given every { stubPreferenceManager.source } returns ServerSource.FAL_AI coEvery { stubFalAiGenerationRepository.generateFromImage(any()) } returns listOf( mockAiGenerationResult ) + // When + val actual = useCase(mockImageToImagePayload.copy(batchCount = 1)) + // Then + assertEquals(listOf(mockAiGenerationResult), actual) coVerify(exactly = 1) { stubFalAiGenerationRepository.generateFromImage(any()) } } @Test - fun `given source is ARLI_AI, expected arli ai generation`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.ARLI_AI - coEvery { stubArliAiGenerationRepository.generateFromImage(any()) } returns listOf( - mockAiGenerationResult - ) + fun `given source is ARLI_AI, generation is requested, expected arli ai generation`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.ARLI_AI + coEvery { stubArliAiGenerationRepository.generateFromImage(any()) } returns listOf( + mockAiGenerationResult + ) - val actual = useCase(mockImageToImagePayload.copy(batchCount = 1)) + // When - assertEquals(listOf(mockAiGenerationResult), actual) - coVerify(exactly = 1) { stubArliAiGenerationRepository.generateFromImage(any()) } - } + val actual = useCase(mockImageToImagePayload.copy(batchCount = 1)) + + // Then + + assertEquals(listOf(mockAiGenerationResult), actual) + coVerify(exactly = 1) { stubArliAiGenerationRepository.generateFromImage(any()) } + } @Test - fun `given automatic1111 batch count is 10, expected batch generated by repository`() = + fun `given automatic1111 batch count is 10, generation is requested, expected batch generated by repository`() = runTest { + // Given every { stubPreferenceManager.source } returns ServerSource.AUTOMATIC1111 coEvery { stubStableDiffusionGenerationRepository.generateFromImage(any()) } returns List( 10 ) { mockAiGenerationResult } + // When + val actual = useCase(mockImageToImagePayload.copy(batchCount = 10)) + // Then + assertEquals(List(10) { mockAiGenerationResult }, actual) coVerify(exactly = 1) { stubStableDiffusionGenerationRepository.generateFromImage(any()) } } @Test - fun `given non batch source batch count is 10, expected generation repeated 10 times`() = + fun `given non batch source batch count is 10, generation is requested, expected generation repeated 10 times`() = runTest { + // Given every { stubPreferenceManager.source } returns ServerSource.HORDE coEvery { stubHordeGenerationRepository.generateFromImage(any()) } returns mockAiGenerationResult + // When + val actual = useCase(mockImageToImagePayload.copy(batchCount = 10)) + // Then + assertEquals(List(10) { mockAiGenerationResult }, actual) coVerify(exactly = 10) { stubHordeGenerationRepository.generateFromImage(any()) } } @Test - fun `given fal ai batch count is 4, expected batch generated by repository`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.FAL_AI - coEvery { stubFalAiGenerationRepository.generateFromImage(any()) } returns List(4) { mockAiGenerationResult } + fun `given fal ai batch count is 4, generation is requested, expected batch generated by repository`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.FAL_AI + coEvery { stubFalAiGenerationRepository.generateFromImage(any()) } returns List(4) { mockAiGenerationResult } - val actual = useCase(mockImageToImagePayload.copy(batchCount = 4)) + // When - assertEquals(List(4) { mockAiGenerationResult }, actual) - coVerify(exactly = 1) { stubFalAiGenerationRepository.generateFromImage(any()) } - } + val actual = useCase(mockImageToImagePayload.copy(batchCount = 4)) + + // Then + + assertEquals(List(4) { mockAiGenerationResult }, actual) + coVerify(exactly = 1) { stubFalAiGenerationRepository.generateFromImage(any()) } + } @Test - fun `given arli ai batch count is 4, expected batch generated by repository`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.ARLI_AI - coEvery { stubArliAiGenerationRepository.generateFromImage(any()) } returns List(4) { mockAiGenerationResult } + fun `given arli ai batch count is 4, generation is requested, expected batch generated by repository`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.ARLI_AI + coEvery { stubArliAiGenerationRepository.generateFromImage(any()) } returns List(4) { mockAiGenerationResult } - val actual = useCase(mockImageToImagePayload.copy(batchCount = 4)) + // When - assertEquals(List(4) { mockAiGenerationResult }, actual) - coVerify(exactly = 1) { stubArliAiGenerationRepository.generateFromImage(any()) } - } + val actual = useCase(mockImageToImagePayload.copy(batchCount = 4)) + + // Then + + assertEquals(List(4) { mockAiGenerationResult }, actual) + coVerify(exactly = 1) { stubArliAiGenerationRepository.generateFromImage(any()) } + } @Test - fun `given generation fails, expected error propagated`() = runTest { + fun `given generation fails, generation is requested, expected error propagated`() = runTest { + // Given every { stubPreferenceManager.source } returns ServerSource.AUTOMATIC1111 coEvery { stubStableDiffusionGenerationRepository.generateFromImage(any()) } throws stubException + // When + val actual = runCatching { useCase(mockImageToImagePayload.copy(batchCount = 1)) } + // Then + assertSame(stubException, actual.exceptionOrNull()) } @Test - fun `given unsupported source, expected unsupported error`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.LOCAL_MICROSOFT_ONNX + fun `given unsupported source, generation is requested, expected unsupported error`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.LOCAL_MICROSOFT_ONNX - val actual = runCatching { useCase(mockImageToImagePayload.copy(batchCount = 1)) } + // When - assertTrue(actual.exceptionOrNull() is IllegalStateException) - assertTrue(actual.exceptionOrNull()?.message?.startsWith("Img2Img not yet supported") == true) - } + val actual = runCatching { useCase(mockImageToImagePayload.copy(batchCount = 1)) } + + // Then + + assertTrue(actual.exceptionOrNull() is IllegalStateException) + assertTrue(actual.exceptionOrNull()?.message?.startsWith("Img2Img not yet supported") == true) + } } diff --git a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/MnnTextToImageUseCaseTest.kt b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/MnnTextToImageUseCaseTest.kt index 6a28c450d..2fcc24299 100644 --- a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/MnnTextToImageUseCaseTest.kt +++ b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/MnnTextToImageUseCaseTest.kt @@ -1,5 +1,6 @@ package com.shifthackz.aisdv1.domain.usecase.generation +import com.shifthackz.aisdv1.domain.mocks.ImmediateGenerationRestoreGate import com.shifthackz.aisdv1.domain.entity.ServerSource import com.shifthackz.aisdv1.domain.entity.TextToImagePayload import com.shifthackz.aisdv1.domain.mocks.mockAiGenerationResult @@ -50,6 +51,7 @@ class MnnTextToImageUseCaseTest { mnnProfile = "sd15-512-general-int8-v1" ) private val useCase = TextToImageUseCaseImpl( + generationRestoreGate = ImmediateGenerationRestoreGate(), stableDiffusionGenerationRepository = mockk(), hordeGenerationRepository = mockk(), huggingFaceGenerationRepository = mockk(), openAiGenerationRepository = mockk(), openAiCompatibleGenerationRepository = mockk(), openAiOAuthGenerationRepository = mockk(), diff --git a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/TextToImageUseCaseImplTest.kt b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/TextToImageUseCaseImplTest.kt index a06a28466..77cdd3855 100644 --- a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/TextToImageUseCaseImplTest.kt +++ b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/TextToImageUseCaseImplTest.kt @@ -1,5 +1,6 @@ package com.shifthackz.aisdv1.domain.usecase.generation +import com.shifthackz.aisdv1.domain.mocks.ImmediateGenerationRestoreGate import com.shifthackz.aisdv1.domain.entity.ServerSource import com.shifthackz.aisdv1.domain.entity.EasyDiffusionConnection import com.shifthackz.aisdv1.domain.entity.EasyDiffusionRequest @@ -59,6 +60,7 @@ class TextToImageUseCaseImplTest { private val generateEasyDiffusion = mockk() private val captureEasyDiffusion = mockk() private val useCase = TextToImageUseCaseImpl( + generationRestoreGate = ImmediateGenerationRestoreGate(), generateEasyDiffusionUseCase = generateEasyDiffusion, captureEasyDiffusionConnectionUseCase = captureEasyDiffusion, stableDiffusionGenerationRepository = stubStableDiffusionGenerationRepository, @@ -81,8 +83,9 @@ class TextToImageUseCaseImplTest { ) @Test - fun `Easy Diffusion captures one immutable connection and delegates the complete batch once`() = + fun `given Easy Diffusion generation, complete batch is submitted, generation is requested, expected one immutable connection capture`() = runTest { + // Given every { stubPreferenceManager.source } returns ServerSource.EASY_DIFFUSION val connection = EasyDiffusionConnection("https://server.example", "folder/model", 7) coEvery { captureEasyDiffusion(7, null) } returns connection @@ -93,7 +96,10 @@ class TextToImageUseCaseImplTest { sourceSnapshot = ServerSource.EASY_DIFFUSION, providerSelectionRevision = 7, batchCount = 3, seed = "4294967295" ) - assertSame(results, useCase(payload)) + // When + val actual = useCase(payload) + // Then + assertSame(results, actual) assertEquals(connection.url, request.captured.url) assertEquals(connection.model, request.captured.model) assertEquals(7L, request.captured.selectionRevision) @@ -103,225 +109,332 @@ class TextToImageUseCaseImplTest { } @Test - fun `stale Easy Diffusion capture stops dispatch before any generation`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.EASY_DIFFUSION - coEvery { captureEasyDiffusion(6, null) } throws stubException - assertSame(stubException, runCatching { - useCase( - mockTextToImagePayload.copy( - sourceSnapshot = ServerSource.EASY_DIFFUSION, - providerSelectionRevision = 6 + fun `given Easy Diffusion generation, captured connection is stale, generation is requested, expected no generation dispatch`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.EASY_DIFFUSION + coEvery { captureEasyDiffusion(6, null) } throws stubException + // When + val actual = runCatching { + useCase( + mockTextToImagePayload.copy( + sourceSnapshot = ServerSource.EASY_DIFFUSION, + providerSelectionRevision = 6 + ) ) - ) - }.exceptionOrNull()) - coVerify(exactly = 0) { generateEasyDiffusion(any()) } - } + } + // Then + assertSame(stubException, actual.exceptionOrNull()) + coVerify(exactly = 0) { generateEasyDiffusion(any()) } + } @Test - fun `given source is AUTOMATIC1111, expected stable diffusion generation`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.AUTOMATIC1111 - coEvery { stubStableDiffusionGenerationRepository.generateFromText(any()) } returns listOf( - mockAiGenerationResult - ) + fun `given source is AUTOMATIC1111, generation is requested, expected stable diffusion generation`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.AUTOMATIC1111 + coEvery { stubStableDiffusionGenerationRepository.generateFromText(any()) } returns listOf( + mockAiGenerationResult + ) - val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + // When - assertEquals(listOf(mockAiGenerationResult), actual) - coVerify(exactly = 1) { stubStableDiffusionGenerationRepository.generateFromText(any()) } - } + val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + + // Then + + assertEquals(listOf(mockAiGenerationResult), actual) + coVerify(exactly = 1) { stubStableDiffusionGenerationRepository.generateFromText(any()) } + } @Test - fun `given source is HORDE, expected horde generation`() = runTest { + fun `given source is HORDE, generation is requested, expected horde generation`() = runTest { + // Given every { stubPreferenceManager.source } returns ServerSource.HORDE coEvery { stubHordeGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult + // When + val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + // Then + assertEquals(listOf(mockAiGenerationResult), actual) coVerify(exactly = 1) { stubHordeGenerationRepository.generateFromText(any()) } } @Test - fun `given source is HUGGING_FACE, expected hugging face generation`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.HUGGING_FACE - coEvery { stubHuggingFaceGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult + fun `given source is HUGGING_FACE, generation is requested, expected hugging face generation`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.HUGGING_FACE + coEvery { stubHuggingFaceGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult - val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + // When - assertEquals(listOf(mockAiGenerationResult), actual) - coVerify(exactly = 1) { stubHuggingFaceGenerationRepository.generateFromText(any()) } - } + val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + + // Then + + assertEquals(listOf(mockAiGenerationResult), actual) + coVerify(exactly = 1) { stubHuggingFaceGenerationRepository.generateFromText(any()) } + } @Test - fun `given source is OPEN_AI, expected open ai generation`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.OPEN_AI - coEvery { stubOpenAiGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult + fun `given source is OPEN_AI, generation is requested, expected open ai generation`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.OPEN_AI + coEvery { stubOpenAiGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult - val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + // When - assertEquals(listOf(mockAiGenerationResult), actual) - coVerify(exactly = 1) { stubOpenAiGenerationRepository.generateFromText(any()) } - } + val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + + // Then + + assertEquals(listOf(mockAiGenerationResult), actual) + coVerify(exactly = 1) { stubOpenAiGenerationRepository.generateFromText(any()) } + } @Test - fun `given source is STABILITY_AI, expected stability ai generation`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.STABILITY_AI - coEvery { stubStabilityAiGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult + fun `given source is STABILITY_AI, generation is requested, expected stability ai generation`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.STABILITY_AI + coEvery { stubStabilityAiGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult - val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + // When - assertEquals(listOf(mockAiGenerationResult), actual) - coVerify(exactly = 1) { stubStabilityAiGenerationRepository.generateFromText(any()) } - } + val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + + // Then + + assertEquals(listOf(mockAiGenerationResult), actual) + coVerify(exactly = 1) { stubStabilityAiGenerationRepository.generateFromText(any()) } + } @Test - fun `given source is FAL_AI, expected fal ai generation`() = runTest { + fun `given source is FAL_AI, generation is requested, expected fal ai generation`() = runTest { + // Given every { stubPreferenceManager.source } returns ServerSource.FAL_AI coEvery { stubFalAiGenerationRepository.generateFromText(any()) } returns listOf( mockAiGenerationResult ) + // When + val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + // Then + assertEquals(listOf(mockAiGenerationResult), actual) coVerify(exactly = 1) { stubFalAiGenerationRepository.generateFromText(any()) } } @Test - fun `given source is ARLI_AI, expected arli ai generation`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.ARLI_AI - coEvery { stubArliAiGenerationRepository.generateFromText(any()) } returns listOf( - mockAiGenerationResult - ) + fun `given source is ARLI_AI, generation is requested, expected arli ai generation`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.ARLI_AI + coEvery { stubArliAiGenerationRepository.generateFromText(any()) } returns listOf( + mockAiGenerationResult + ) - val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + // When - assertEquals(listOf(mockAiGenerationResult), actual) - coVerify(exactly = 1) { stubArliAiGenerationRepository.generateFromText(any()) } - } + val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + + // Then + + assertEquals(listOf(mockAiGenerationResult), actual) + coVerify(exactly = 1) { stubArliAiGenerationRepository.generateFromText(any()) } + } @Test - fun `given source is SWARM_UI, expected swarm ui generation`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.SWARM_UI - coEvery { stubSwarmUiGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult + fun `given source is SWARM_UI, generation is requested, expected swarm ui generation`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.SWARM_UI + coEvery { stubSwarmUiGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult - val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + // When - assertEquals(listOf(mockAiGenerationResult), actual) - coVerify(exactly = 1) { stubSwarmUiGenerationRepository.generateFromText(any()) } - } + val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + + // Then + + assertEquals(listOf(mockAiGenerationResult), actual) + coVerify(exactly = 1) { stubSwarmUiGenerationRepository.generateFromText(any()) } + } @Test - fun `given source is LOCAL_MICROSOFT_ONNX, expected local diffusion generation`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.LOCAL_MICROSOFT_ONNX - coEvery { stubLocalDiffusionGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult + fun `given source is LOCAL_MICROSOFT_ONNX, generation is requested, expected local diffusion generation`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.LOCAL_MICROSOFT_ONNX + coEvery { stubLocalDiffusionGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult - val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + // When - assertEquals(listOf(mockAiGenerationResult), actual) - coVerify(exactly = 1) { stubLocalDiffusionGenerationRepository.generateFromText(any()) } - } + val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + + // Then + + assertEquals(listOf(mockAiGenerationResult), actual) + coVerify(exactly = 1) { stubLocalDiffusionGenerationRepository.generateFromText(any()) } + } @Test - fun `given source is LOCAL_GOOGLE_MEDIA_PIPE, expected media pipe generation`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.LOCAL_GOOGLE_MEDIA_PIPE - coEvery { stubMediaPipeGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult + fun `given source is LOCAL_GOOGLE_MEDIA_PIPE, generation is requested, expected media pipe generation`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.LOCAL_GOOGLE_MEDIA_PIPE + coEvery { stubMediaPipeGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult - val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + // When - assertEquals(listOf(mockAiGenerationResult), actual) - coVerify(exactly = 1) { stubMediaPipeGenerationRepository.generateFromText(any()) } - } + val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + + // Then + + assertEquals(listOf(mockAiGenerationResult), actual) + coVerify(exactly = 1) { stubMediaPipeGenerationRepository.generateFromText(any()) } + } @Test - fun `given source is LOCAL_STABLE_DIFFUSION_CPP, expected stable diffusion cpp generation`() = + fun `given source is LOCAL_STABLE_DIFFUSION_CPP, generation is requested, expected stable diffusion cpp generation`() = runTest { + // Given every { stubPreferenceManager.source } returns ServerSource.LOCAL_STABLE_DIFFUSION_CPP coEvery { stubStableDiffusionCppGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult + // When + val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + // Then + assertEquals(listOf(mockAiGenerationResult), actual) coVerify(exactly = 1) { stubStableDiffusionCppGenerationRepository.generateFromText(any()) } } @Test - fun `given source is LOCAL_APPLE_CORE_ML, expected core ml generation`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.LOCAL_APPLE_CORE_ML - coEvery { stubCoreMlGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult + fun `given source is LOCAL_APPLE_CORE_ML, generation is requested, expected core ml generation`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.LOCAL_APPLE_CORE_ML + coEvery { stubCoreMlGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult - val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + // When - assertEquals(listOf(mockAiGenerationResult), actual) - coVerify(exactly = 1) { stubCoreMlGenerationRepository.generateFromText(any()) } - } + val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + + // Then + + assertEquals(listOf(mockAiGenerationResult), actual) + coVerify(exactly = 1) { stubCoreMlGenerationRepository.generateFromText(any()) } + } @Test - fun `given source is LOCAL_APPLE_BONSAI, expected bonsai generation`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.LOCAL_APPLE_BONSAI - coEvery { stubBonsaiGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult + fun `given source is LOCAL_APPLE_BONSAI, generation is requested, expected bonsai generation`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.LOCAL_APPLE_BONSAI + coEvery { stubBonsaiGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult - val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + // When - assertEquals(listOf(mockAiGenerationResult), actual) - coVerify(exactly = 1) { stubBonsaiGenerationRepository.generateFromText(any()) } - } + val actual = useCase(mockTextToImagePayload.copy(batchCount = 1)) + + // Then + + assertEquals(listOf(mockAiGenerationResult), actual) + coVerify(exactly = 1) { stubBonsaiGenerationRepository.generateFromText(any()) } + } @Test - fun `given automatic1111 batch count is 10, expected batch generated by repository`() = + fun `given automatic1111 batch count is 10, generation is requested, expected batch generated by repository`() = runTest { + // Given every { stubPreferenceManager.source } returns ServerSource.AUTOMATIC1111 coEvery { stubStableDiffusionGenerationRepository.generateFromText(any()) } returns List( 10 ) { mockAiGenerationResult } + // When + val actual = useCase(mockTextToImagePayload.copy(batchCount = 10)) + // Then + assertEquals(List(10) { mockAiGenerationResult }, actual) coVerify(exactly = 1) { stubStableDiffusionGenerationRepository.generateFromText(any()) } } @Test - fun `given non batch source batch count is 10, expected generation repeated 10 times`() = + fun `given non batch source batch count is 10, generation is requested, expected generation repeated 10 times`() = runTest { + // Given every { stubPreferenceManager.source } returns ServerSource.HORDE coEvery { stubHordeGenerationRepository.generateFromText(any()) } returns mockAiGenerationResult + // When + val actual = useCase(mockTextToImagePayload.copy(batchCount = 10)) + // Then + assertEquals(List(10) { mockAiGenerationResult }, actual) coVerify(exactly = 10) { stubHordeGenerationRepository.generateFromText(any()) } } @Test - fun `given fal ai batch count is 4, expected batch generated by repository`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.FAL_AI - coEvery { stubFalAiGenerationRepository.generateFromText(any()) } returns List(4) { mockAiGenerationResult } + fun `given fal ai batch count is 4, generation is requested, expected batch generated by repository`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.FAL_AI + coEvery { stubFalAiGenerationRepository.generateFromText(any()) } returns List(4) { mockAiGenerationResult } - val actual = useCase(mockTextToImagePayload.copy(batchCount = 4)) + // When - assertEquals(List(4) { mockAiGenerationResult }, actual) - coVerify(exactly = 1) { stubFalAiGenerationRepository.generateFromText(any()) } - } + val actual = useCase(mockTextToImagePayload.copy(batchCount = 4)) + + // Then + + assertEquals(List(4) { mockAiGenerationResult }, actual) + coVerify(exactly = 1) { stubFalAiGenerationRepository.generateFromText(any()) } + } @Test - fun `given arli ai batch count is 4, expected batch generated by repository`() = runTest { - every { stubPreferenceManager.source } returns ServerSource.ARLI_AI - coEvery { stubArliAiGenerationRepository.generateFromText(any()) } returns List(4) { mockAiGenerationResult } + fun `given arli ai batch count is 4, generation is requested, expected batch generated by repository`() = + runTest { + // Given + every { stubPreferenceManager.source } returns ServerSource.ARLI_AI + coEvery { stubArliAiGenerationRepository.generateFromText(any()) } returns List(4) { mockAiGenerationResult } - val actual = useCase(mockTextToImagePayload.copy(batchCount = 4)) + // When - assertEquals(List(4) { mockAiGenerationResult }, actual) - coVerify(exactly = 1) { stubArliAiGenerationRepository.generateFromText(any()) } - } + val actual = useCase(mockTextToImagePayload.copy(batchCount = 4)) + + // Then + + assertEquals(List(4) { mockAiGenerationResult }, actual) + coVerify(exactly = 1) { stubArliAiGenerationRepository.generateFromText(any()) } + } @Test - fun `given generation fails, expected error propagated`() = runTest { + fun `given generation fails, generation is requested, expected error propagated`() = runTest { + // Given every { stubPreferenceManager.source } returns ServerSource.AUTOMATIC1111 coEvery { stubStableDiffusionGenerationRepository.generateFromText(any()) } throws stubException + // When + val actual = runCatching { useCase(mockTextToImagePayload.copy(batchCount = 1)) } + // Then + assertSame(stubException, actual.exceptionOrNull()) } } diff --git a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/settings/SetServerConfigurationUseCaseImplTest.kt b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/settings/SetServerConfigurationUseCaseImplTest.kt index b6bb324cf..afda66c79 100644 --- a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/settings/SetServerConfigurationUseCaseImplTest.kt +++ b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/settings/SetServerConfigurationUseCaseImplTest.kt @@ -6,6 +6,8 @@ import com.shifthackz.aisdv1.domain.gateway.ProviderSelectionGuard import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationStore import com.shifthackz.aisdv1.domain.mocks.ConfigurationStoreStub import com.shifthackz.aisdv1.domain.mocks.mockConfiguration +import com.shifthackz.aisdv1.domain.gateway.backup.BackupPreferencesGateway +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage import com.shifthackz.aisdv1.domain.preference.PreferenceManager import io.mockk.coEvery import io.mockk.coVerify @@ -27,27 +29,32 @@ class DefaultSetServerConfigurationUseCaseImplTest { providerSelectionGuard = ProviderSelectionGuard(), authorizationStore = stubAuthorizationStore, preferenceManager = stubPreferenceManager, + backupPreferences = mockk { every { readStartupStage() } returns BackupStartupStage.COMPLETE }, ) @Test - fun `given configuration apply success, expected complete value`() = runTest { - coEvery { - stubAuthorizationStore.storeAuthorizationCredentials(any(), any()) - } coAnswers { - secondArg Unit>().invoke("configuration-test") - } - coEvery { - stubPreferenceManager.refresh() - } returns Unit + fun `given provider configuration, checked apply succeeds, expected complete saved value`() = + runTest { + // Given + coEvery { + stubAuthorizationStore.storeAuthorizationCredentials(any(), any()) + } coAnswers { + secondArg Unit>().invoke("configuration-test") + } + coEvery { + stubPreferenceManager.refresh() + } returns Unit - useCase(mockConfiguration) + // When + useCase(mockConfiguration) - assertEquals( - mockConfiguration, - stubConfigurationStore.getConfiguration(mockConfiguration.authCredentials) - ) - coVerify { - stubPreferenceManager.refresh() + // Then + assertEquals( + mockConfiguration, + stubConfigurationStore.getConfiguration(mockConfiguration.authCredentials) + ) + coVerify { + stubPreferenceManager.refresh() + } } - } } diff --git a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/splash/SplashNavigationUseCaseImplTest.kt b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/splash/SplashNavigationUseCaseImplTest.kt index 9b15a9662..47031df0d 100644 --- a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/splash/SplashNavigationUseCaseImplTest.kt +++ b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/splash/SplashNavigationUseCaseImplTest.kt @@ -1,114 +1,152 @@ package com.shifthackz.aisdv1.domain.usecase.splash -import com.nhaarman.mockitokotlin2.mock -import com.nhaarman.mockitokotlin2.whenever import com.shifthackz.aisdv1.domain.entity.ServerSource +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage +import com.shifthackz.aisdv1.domain.entity.backup.BackupRecovery +import com.shifthackz.aisdv1.domain.entity.backup.BackupRestoreRequest +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection +import com.shifthackz.aisdv1.domain.entity.backup.BackupInspection import com.shifthackz.aisdv1.domain.preference.PreferenceManager -import kotlinx.coroutines.runBlocking +import com.shifthackz.aisdv1.domain.usecase.backup.GetBackupStartupStageUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.LoadPendingBackupUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.GetPendingBackupExportUseCase +import io.mockk.coEvery +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Before import org.junit.Test class SplashNavigationUseCaseImplTest { - - private val stubPreferenceManager = mock() - - private val useCase = SplashNavigationUseCaseImpl(stubPreferenceManager) - - @Test - fun `given onBoardingComplete is false, expected LAUNCH_ONBOARDING`() { - whenever(stubPreferenceManager.onBoardingComplete) - .thenReturn(false) - - val result = runBlocking { useCase() } - - assert(result == SplashNavigationUseCase.Action.LAUNCH_ONBOARDING) + private val preferences = mockk(relaxed = true) + private val stage = mockk() + private val pending = mockk() + private val export = mockk() + private val useCase = SplashNavigationUseCaseImpl(preferences, stage, pending, export) + + @Before + fun setup() { + every { preferences.onBoardingComplete } returns true + every { preferences.source } returns ServerSource.AUTOMATIC1111 + every { preferences.automatic1111ServerUrl } returns "https://server" + every { stage() } returns BackupStartupStage.COMPLETE + coEvery { pending() } returns null + coEvery { export() } returns false } @Test - fun `given forceSetupAfterUpdate is true, expected LAUNCH_SERVER_SETUP`() { - whenever(stubPreferenceManager.onBoardingComplete) - .thenReturn(true) - - whenever(stubPreferenceManager.forceSetupAfterUpdate) - .thenReturn(true) - - val result = runBlocking { useCase() } - - assert(result == SplashNavigationUseCase.Action.LAUNCH_SERVER_SETUP) + fun `given first app launch, onboarding incomplete, expected onboarding route`() = runTest { + // Given + every { preferences.onBoardingComplete } returns false + // When + val action = useCase() + // Then + assertEquals(SplashNavigationUseCase.Action.LAUNCH_ONBOARDING, action) } @Test - fun `given source is AUTOMATIC1111 and server url empty, expected LAUNCH_SERVER_SETUP`() { - whenever(stubPreferenceManager.onBoardingComplete) - .thenReturn(true) - - whenever(stubPreferenceManager.forceSetupAfterUpdate) - .thenReturn(false) - - whenever(stubPreferenceManager.automatic1111ServerUrl) - .thenReturn("") - - whenever(stubPreferenceManager.source) - .thenReturn(ServerSource.AUTOMATIC1111) - - val result = runBlocking { useCase() } - - assert(result == SplashNavigationUseCase.Action.LAUNCH_SERVER_SETUP) - } + fun `given completed onboarding, invitation stage is pending, expected restore invitation`() = + runTest { + // Given + every { stage() } returns BackupStartupStage.INVITATION + // When + val action = useCase() + // Then + assertEquals(SplashNavigationUseCase.Action.LAUNCH_BACKUP_WELCOME, action) + } @Test - fun `given source is AUTOMATIC1111 and server url not empty, expected LAUNCH_HOME`() { - whenever(stubPreferenceManager.onBoardingComplete) - .thenReturn(true) - - whenever(stubPreferenceManager.forceSetupAfterUpdate) - .thenReturn(false) - - whenever(stubPreferenceManager.automatic1111ServerUrl) - .thenReturn("http://192.168.0.1:7860") - - whenever(stubPreferenceManager.source) - .thenReturn(ServerSource.AUTOMATIC1111) - - val result = runBlocking { useCase() } - - assert(result == SplashNavigationUseCase.Action.LAUNCH_HOME) + fun `given first launch restore, process restarts, expected restore only route`() = runTest { + // Given + every { stage() } returns BackupStartupStage.RESTORE + // When + val action = useCase() + // Then + assertEquals(SplashNavigationUseCase.Action.LAUNCH_INITIAL_RESTORE, action) } @Test - fun `given source is LOCAL, and server url is empty, expected LAUNCH_HOME`() { - whenever(stubPreferenceManager.onBoardingComplete) - .thenReturn(true) - - whenever(stubPreferenceManager.forceSetupAfterUpdate) - .thenReturn(false) + fun `given first launch recovery, user proceeds to configuration, expected setup even with restored fields`() = + runTest { + // Given + every { stage() } returns BackupStartupStage.CONFIGURATION + // When + val action = useCase() + // Then + assertEquals(SplashNavigationUseCase.Action.LAUNCH_SERVER_SETUP, action) + } - whenever(stubPreferenceManager.automatic1111ServerUrl) - .thenReturn("") - - whenever(stubPreferenceManager.source) - .thenReturn(ServerSource.LOCAL_MICROSOFT_ONNX) + @Test + fun `given existing configured installation, backup stage is complete, expected normal home route`() = + runTest { + // Given + every { stage() } returns BackupStartupStage.COMPLETE + // When + val action = useCase() + // Then + assertEquals(SplashNavigationUseCase.Action.LAUNCH_HOME, action) + } - val result = runBlocking { useCase() } + @Test + fun `given existing installation, provider setup required by update, expected setup route`() = + runTest { + // Given + every { preferences.forceSetupAfterUpdate } returns true + // When + val action = useCase() + // Then + assertEquals(SplashNavigationUseCase.Action.LAUNCH_SERVER_SETUP, action) + } - assert(result == SplashNavigationUseCase.Action.LAUNCH_HOME) + @Test + fun `given A1111 selection, endpoint is absent, expected setup route`() = runTest { + // Given + every { preferences.automatic1111ServerUrl } returns "" + // When + val action = useCase() + // Then + assertEquals(SplashNavigationUseCase.Action.LAUNCH_SERVER_SETUP, action) } @Test - fun `given source is LOCAL, and server url is not empty, expected LAUNCH_HOME`() { - whenever(stubPreferenceManager.onBoardingComplete) - .thenReturn(true) - - whenever(stubPreferenceManager.forceSetupAfterUpdate) - .thenReturn(false) - - whenever(stubPreferenceManager.automatic1111ServerUrl) - .thenReturn("http://192.168.0.1:7860") + fun `given local provider selection, A1111 endpoint absent, expected normal home route`() = + runTest { + // Given + every { preferences.source } returns ServerSource.LOCAL_MICROSOFT_ONNX + every { preferences.automatic1111ServerUrl } returns "" + // When + val action = useCase() + // Then + assertEquals(SplashNavigationUseCase.Action.LAUNCH_HOME, action) + } - whenever(stubPreferenceManager.source) - .thenReturn(ServerSource.LOCAL_MICROSOFT_ONNX) + @Test + fun `given interrupted settings restore, process restarts, expected pending restore before home`() = + runTest { + // Given + coEvery { pending() } returns BackupRecovery( + BackupRestoreRequest( + "archive", + BackupSelection(), + "session" + ), BackupInspection("archive", 1, "1", "IOS", emptyList(), emptySet()) + ) + // When + val action = useCase() + // Then + assertEquals(SplashNavigationUseCase.Action.LAUNCH_BACKUP_RESTORE, action) + } - val result = runBlocking { useCase() } + @Test + fun `given native export pending, process starts, expected backup route reconnects document result`() = + runTest { + // Given + coEvery { export() } returns true + // When + val action = useCase() + // Then + assertEquals(SplashNavigationUseCase.Action.LAUNCH_BACKUP_RESTORE, action) + } - assert(result == SplashNavigationUseCase.Action.LAUNCH_HOME) - } } 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 148b31ada..db7341b65 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 @@ -410,7 +410,14 @@ val coreDomainModule = module { timeProvider = get(), ) } - factory { SplashNavigationUseCaseImpl(preferenceManager = get()) } + factory { + SplashNavigationUseCaseImpl( + preferenceManager = get(), + getBackupStartupStage = get(), + loadPendingBackup = get(), + getPendingExport = get() + ) + } factory { ObserveLocalOnnxModelsUseCaseImpl(repository = get()) } @@ -450,6 +457,7 @@ val coreDomainModule = module { } factory { TextToImageUseCaseImpl( + generationRestoreGate = get(), generateEasyDiffusionUseCase = get(), captureEasyDiffusionConnectionUseCase = get(), stableDiffusionGenerationRepository = get(), @@ -473,6 +481,7 @@ val coreDomainModule = module { } factory { ImageToImageUseCaseImpl( + generationRestoreGate = get(), generateEasyDiffusionUseCase = get(), captureEasyDiffusionConnectionUseCase = get(), stableDiffusionGenerationRepository = get(), @@ -603,6 +612,7 @@ val coreDomainModule = module { } factory { DefaultSetServerConfigurationUseCaseImpl( + backupPreferences = get(), dispatchersProvider = get(), providerSelectionGuard = get(), configurationStore = get(), diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupCategory.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupCategory.kt new file mode 100644 index 000000000..82f269ccb --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupCategory.kt @@ -0,0 +1,11 @@ +package com.shifthackz.aisdv1.domain.entity.backup + + +/** + * Selectable portable data sections; wire identifiers remain stable across application versions. + * @param key Permanent section identifier stored in backup manifests. + * @author Dmitriy Moroz + */ +enum class BackupCategory(val key: String) { + PROVIDERS("providers"), GALLERY("gallery"), NETWORK("network"), SETTINGS("settings"); +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupEntry.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupEntry.kt new file mode 100644 index 000000000..22f9148fd --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupEntry.kt @@ -0,0 +1,15 @@ +package com.shifthackz.aisdv1.domain.entity.backup + + +/** + * One selectable inventory or inspected archive category. + * @param category Known section identity. + * @param itemCount Number of saved entries, not an estimated compressed size. + * @param isAvailable Whether the current build can import or export this section. + * @author Dmitriy Moroz + */ +data class BackupEntry( + val category: BackupCategory, + val itemCount: Long, + val isAvailable: Boolean = true, +) diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupExport.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupExport.kt new file mode 100644 index 000000000..6e76c7325 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupExport.kt @@ -0,0 +1,11 @@ +package com.shifthackz.aisdv1.domain.entity.backup + + +/** + * Complete staged backup ready for the native document export flow. + * @param document Opaque platform document reference, never shown as UI text. + * @param filename Suggested public filename ending in .sdaibackup. + * @param handle Generated staging identity persisted before document presentation. + * @author Dmitriy Moroz + */ +data class BackupExport(val document: String, val filename: String, val handle: String) diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupExportCompletion.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupExportCompletion.kt new file mode 100644 index 000000000..b50b6df97 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupExportCompletion.kt @@ -0,0 +1,33 @@ +package com.shifthackz.aisdv1.domain.entity.backup + +/** + * Native document outcomes tied to the staged source that launched their picker. + * @author Dmitriy Moroz + */ +sealed interface BackupExportCompletion { + /** App-owned staged identity captured before picker presentation. @author Dmitriy Moroz */ + val handle: String + + /** + * Android supplied a write-granted output document for this source. + * @param document Opaque destination associated with this export. + * @param handle App-owned source identity retained by the native launcher. + * @author Dmitriy Moroz + */ + data class DestinationSelected(val document: String, override val handle: String) : + BackupExportCompletion + + /** + * UIKit confirmed this source was copied to its selected destination. + * @param handle App-owned source identity retained by the native launcher. + * @author Dmitriy Moroz + */ + data class NativeCompleted(override val handle: String) : BackupExportCompletion + + /** + * This source's native picker was canceled before destination copying. + * @param handle App-owned source identity retained by the native launcher. + * @author Dmitriy Moroz + */ + data class Canceled(override val handle: String) : BackupExportCompletion +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupExportIntent.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupExportIntent.kt new file mode 100644 index 000000000..1305e0cad --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupExportIntent.kt @@ -0,0 +1,17 @@ +package com.shifthackz.aisdv1.domain.entity.backup + + +/** + * Durable export/result association written before the native document picker opens. + * @param handle Generated app-owned staging identity, without a platform path. + * @param filename Suggested public binary backup filename. + * @param status Last durably acknowledged export stage. + * @param destination Opaque selected output reference, retained for interrupted-copy retry. + * @author Dmitriy Moroz + */ +data class BackupExportIntent( + val handle: String, + val filename: String, + val status: BackupExportStatus = BackupExportStatus.READY, + val destination: String? = null, +) diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupExportOperation.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupExportOperation.kt new file mode 100644 index 000000000..d7da74a58 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupExportOperation.kt @@ -0,0 +1,13 @@ +package com.shifthackz.aisdv1.domain.entity.backup + + +/** + * Observable application-owned export state; successful status means native completion or completed byte copy. + * @param status Current durable operation stage. + * @param backup Resolved private export reference; no archive payload or credentials. + * @author Dmitriy Moroz + */ +data class BackupExportOperation( + val status: BackupExportStatus = BackupExportStatus.NONE, + val backup: BackupExport? = null +) diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupExportStatus.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupExportStatus.kt new file mode 100644 index 000000000..553e8a981 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupExportStatus.kt @@ -0,0 +1,8 @@ +package com.shifthackz.aisdv1.domain.entity.backup + + +/** + * Nonsecret lifecycle of one staged export, retained independently from a screen composition. + * @author Dmitriy Moroz + */ +enum class BackupExportStatus { NONE, PROCESSING, READY, COPYING, COMPLETE, FAILED, CANCELED } diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupImageBudget.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupImageBudget.kt new file mode 100644 index 000000000..60a8629f6 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupImageBudget.kt @@ -0,0 +1,21 @@ +package com.shifthackz.aisdv1.domain.entity.backup + +/** + * Shared gallery-backup admission applied before encoded allocation and native pixel decoding. + * @param maxEncodedBytes Maximum combined output/input encoded image bytes in one gallery record. + * @param maxPixels Maximum original pixel count accepted from native metadata. + * @param maxDecodedBytes Maximum conservative original decoded size, calculated with eight bytes per pixel. + * @param validationEdge Maximum edge of the sampled native content-validation bitmap. + * @author Dmitriy Moroz + */ +data class BackupImageBudget( + val maxEncodedBytes: Int, + val maxPixels: Long, + val maxDecodedBytes: Long, + val validationEdge: Int, +) { + init { + require(maxEncodedBytes > 0 && maxPixels > 0 && maxDecodedBytes > 0) + require(validationEdge in 1..1024) + } +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupInspection.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupInspection.kt new file mode 100644 index 000000000..5c5f20c21 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupInspection.kt @@ -0,0 +1,27 @@ +package com.shifthackz.aisdv1.domain.entity.backup + + +/** + * Validated archive summary; handle refers only to an app-owned staged copy. + * @param handle Opaque private archive identity; never a user-managed file path. + * @param createdAt Creation timestamp in UTC epoch milliseconds. + * @param appVersion Originating application version for display only. + * @param sourcePlatform Originating platform label. + * @param entries Compatible and unavailable known categories. + * @param providers Supported provider children present in the archive. + * @param skippedCount Number of unsupported section, provider or field entries. + * @param filename User-facing original filename, excluding its storage path. + * @param sourceLocation Native source path or provider document reference for display; never an archive payload field. + * @author Dmitriy Moroz + */ +data class BackupInspection( + val handle: String, + val createdAt: Long, + val appVersion: String, + val sourcePlatform: String, + val entries: List, + val providers: Set, + val skippedCount: Int = 0, + val filename: String = "", + val sourceLocation: String = "", +) diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupPreferences.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupPreferences.kt new file mode 100644 index 000000000..0d3a8b0bd --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupPreferences.kt @@ -0,0 +1,13 @@ +package com.shifthackz.aisdv1.domain.entity.backup + + +/** + * Allowlisted portable fields keyed by stable provider and field identifiers. Never log credential values. + * @param providers Saved portable fields for each represented provider. + * @param settings Saved user preferences, excluding lifecycle and device state. + * @author Dmitriy Moroz + */ +data class BackupPreferences( + val providers: Map>, + val settings: Map, +) diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupProgress.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupProgress.kt new file mode 100644 index 000000000..f2c96448c --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupProgress.kt @@ -0,0 +1,11 @@ +package com.shifthackz.aisdv1.domain.entity.backup + + +/** + * Progress emitted after bounded work, with committed restore counts distinguished by stage. + * @param category Current section, or null while staging/validating. + * @param completed Processed entry count in the current section. + * @param total Expected entries in the section. + * @author Dmitriy Moroz + */ +data class BackupProgress(val category: BackupCategory?, val completed: Long, val total: Long) diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupRecovery.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupRecovery.kt new file mode 100644 index 000000000..e41fc689d --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupRecovery.kt @@ -0,0 +1,10 @@ +package com.shifthackz.aisdv1.domain.entity.backup + + +/** + * Nonsecret restore state retained across application restarts. + * @param request Original operation and selection binding. + * @param inspection Revalidated staged archive summary. + * @author Dmitriy Moroz + */ +data class BackupRecovery(val request: BackupRestoreRequest, val inspection: BackupInspection) diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupRestoreNotice.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupRestoreNotice.kt new file mode 100644 index 000000000..5e91aa6a6 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupRestoreNotice.kt @@ -0,0 +1,15 @@ +package com.shifthackz.aisdv1.domain.entity.backup + + +/** + * Typed reasons for deliberately omitted restore data; no credential values are retained. + * @author Dmitriy Moroz + */ +sealed interface BackupRestoreNotice { + /** + * Shared Basic Auth stayed unchanged to protect configured providers outside the restore selection. + * @param providers Unselected configured provider IDs whose credentials were preserved. + * @author Dmitriy Moroz + */ + data class SharedCredentialsRetained(val providers: Set) : BackupRestoreNotice +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupRestoreRequest.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupRestoreRequest.kt new file mode 100644 index 000000000..3d0c9a111 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupRestoreRequest.kt @@ -0,0 +1,19 @@ +package com.shifthackz.aisdv1.domain.entity.backup + + +/** + * Immutable restore submission; retries retain the same session ID to avoid duplicate additive imports. + * @param handle Validated staged archive identity. + * @param selection Categories and providers explicitly selected by the user. + * @param sessionId Stable operation identity retained across retries and process recovery. + * @param confirmedFingerprint Opaque conflict revision previously confirmed, or null before consent. + * @param shouldProceedToConfiguration Whether a completed first-launch import must durably hand off to configuration. + * @author Dmitriy Moroz + */ +data class BackupRestoreRequest( + val handle: String, + val selection: BackupSelection, + val sessionId: String, + val confirmedFingerprint: String? = null, + val shouldProceedToConfiguration: Boolean = false, +) diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupRestoreResult.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupRestoreResult.kt new file mode 100644 index 000000000..d546dacea --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupRestoreResult.kt @@ -0,0 +1,34 @@ +package com.shifthackz.aisdv1.domain.entity.backup + +/** + * Explicit consent request or durable completion report; no secret values are exposed to UI state. + * @author Dmitriy Moroz + */ +sealed interface BackupRestoreResult { + /** + * Provider replacement requires confirmation of this exact source/destination revision. + * @param providers All configured provider names affected by the replacement. + * @param fingerprint Opaque consent revision invalidated by destination changes. + * @author Dmitriy Moroz + */ + + data class Conflict(val providers: Set, val fingerprint: String) : BackupRestoreResult + + /** + * Reports actual committed work after success or a recoverable category failure. + * @param completed Categories with durable section markers in the journal. + * @param skippedCount Unsupported or deliberately omitted entries. + * @param hasFailed Whether selected data remains unapplied after a category failure. + * @param importedCounts Committed entry counts retained across session retries. + * @param notices Typed explanations identifying deliberately preserved destination data. + * @author Dmitriy Moroz + */ + + data class Finished( + val completed: Set, + val skippedCount: Int, + val hasFailed: Boolean, + val importedCounts: Map = emptyMap(), + val notices: List = emptyList() + ) : BackupRestoreResult +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupSelection.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupSelection.kt new file mode 100644 index 000000000..f06c3e9b3 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupSelection.kt @@ -0,0 +1,13 @@ +package com.shifthackz.aisdv1.domain.entity.backup + + +/** + * Explicit user choices shared by create and restore screens. + * @param categories Selected available data categories. + * @param providers Selected provider wire identifiers beneath the providers category. + * @author Dmitriy Moroz + */ +data class BackupSelection( + val categories: Set = emptySet(), + val providers: Set = emptySet(), +) diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupStartupStage.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupStartupStage.kt new file mode 100644 index 000000000..f8db20075 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupStartupStage.kt @@ -0,0 +1,8 @@ +package com.shifthackz.aisdv1.domain.entity.backup + + +/** + * Durable post-onboarding recovery stage. Existing installations default to COMPLETE. + * @author Dmitriy Moroz + */ +enum class BackupStartupStage { INVITATION, RESTORE, CONFIGURATION, COMPLETE } diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupValue.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupValue.kt new file mode 100644 index 000000000..0ccf66985 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/backup/BackupValue.kt @@ -0,0 +1,35 @@ +package com.shifthackz.aisdv1.domain.entity.backup + +/** + * Typed portable preference primitives. Missing entries retain destination values; never log these objects. + * @author Dmitriy Moroz + */ +sealed interface BackupValue { + /** + * Preserves the presence of an unsupported encoded value without retaining its payload. + * Compatibility filtering can then count the skipped field instead of silently dropping its ID. + * @author Dmitriy Moroz + */ + data object Unsupported : BackupValue + + /** + * Portable string, including an explicitly saved empty value. + * @param value Exact field text, which may contain an API key or password. + * @author Dmitriy Moroz + */ + data class Text(val value: String) : BackupValue + + /** + * Portable boolean whose false value remains distinguishable from a missing field. + * @param isTrue Exact persisted boolean value. + * @author Dmitriy Moroz + */ + data class Flag(val isTrue: Boolean) : BackupValue + + /** + * Portable integral setting such as sampling steps or timeout seconds. + * @param value Exact stored integer; field-specific validation occurs during inspection. + * @author Dmitriy Moroz + */ + data class Integer(val value: Int) : BackupValue +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/GenerationRestoreGate.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/GenerationRestoreGate.kt new file mode 100644 index 000000000..fb52955fb --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/GenerationRestoreGate.kt @@ -0,0 +1,21 @@ +package com.shifthackz.aisdv1.domain.gateway + +/** + * Prevents provider/settings restore from invalidating active foreground or background generation. + * @author Dmitriy Moroz + */ +interface GenerationRestoreGate { + /** + * Runs generation after any active restore has completed; cancellation while waiting propagates. + * @param block Complete provider operation owned by one generation use case. + * @author Dmitriy Moroz + */ + suspend fun generating(block: suspend () -> T): T + + /** + * Rejects restore while generation owns the gate, then prevents new generation until restore finishes. + * @param block Serialized restore operation, including conflict comparison and data commits. + * @author Dmitriy Moroz + */ + suspend fun restoring(block: suspend () -> T): T +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/backup/BackupChangesGateway.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/backup/BackupChangesGateway.kt new file mode 100644 index 000000000..7c8f6a0af --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/backup/BackupChangesGateway.kt @@ -0,0 +1,16 @@ +package com.shifthackz.aisdv1.domain.gateway.backup + +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory + +/** + * Refreshes retained application readers after restore commits or checked preference recovery. + * @author Dmitriy Moroz + */ +interface BackupChangesGateway { + /** + * Refreshes settings, locale and storage snapshots against their current trusted persisted data. + * @param categories Categories affected by restore or pending preference recovery; empty requires no refresh. + * @author Dmitriy Moroz + */ + suspend fun notifyChanged(categories: Set) +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/backup/BackupExportStateStore.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/backup/BackupExportStateStore.kt new file mode 100644 index 000000000..39d9bbe3f --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/backup/BackupExportStateStore.kt @@ -0,0 +1,34 @@ +package com.shifthackz.aisdv1.domain.gateway.backup + +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportIntent + +/** + * Checked nonsecret export persistence isolated from provider and credential preferences. + * @author Dmitriy Moroz + */ +interface BackupExportStateStore { + /** + * Recovers only a pending export-state write before ownership or native outcomes are examined. + * @author Dmitriy Moroz + */ + fun recoverPendingWrite() + + /** + * Returns the pending source/result association, or null when no export owns staging. + * @author Dmitriy Moroz + */ + fun read(): BackupExportIntent? + + /** + * Checks durable publication before native presentation or destination copying starts. + * @param intent Nonsecret staged-source and output association. + * @author Dmitriy Moroz + */ + fun write(intent: BackupExportIntent) + + /** + * Acknowledges dismissal/cancellation before app-owned export staging may be removed. + * @author Dmitriy Moroz + */ + fun clear() +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/backup/BackupImageValidator.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/backup/BackupImageValidator.kt new file mode 100644 index 000000000..afa2ed612 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/backup/BackupImageValidator.kt @@ -0,0 +1,14 @@ +package com.shifthackz.aisdv1.domain.gateway.backup + +/** + * Checks native image dimensions before allocation and validates content through a bounded platform sample. + * @author Dmitriy Moroz + */ +interface BackupImageValidator { + /** + * Rejects over-budget dimensions, corrupt or unsupported images without decoding an original-size bitmap. + * @param bytes Complete bytes of one bounded gallery image. + * @author Dmitriy Moroz + */ + operator fun invoke(bytes: ByteArray) +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/backup/BackupPreferencesGateway.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/backup/BackupPreferencesGateway.kt new file mode 100644 index 000000000..37b976cf7 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/backup/BackupPreferencesGateway.kt @@ -0,0 +1,65 @@ +package com.shifthackz.aisdv1.domain.gateway.backup + +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.entity.backup.BackupPreferences +import com.shifthackz.aisdv1.domain.entity.backup.BackupValue +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage + +/** + * Strict portable preference persistence; transport and storage errors propagate to the caller. + * @author Dmitriy Moroz + */ +interface BackupPreferencesGateway { + /** + * Recovers an already-started checked batch and identifies changed portable preference categories. + * Authorization association and provider revision changes also report PROVIDERS, even without endpoint changes. + * The caller must reconcile protected credentials before publishing these invalidations. + * @author Dmitriy Moroz + */ + fun recoverPendingWrite(): Set + + /** + * Filters removed fields and unknown enum values while rejecting malformed known scalar types. + * @param preferences Portable fields decoded from an archive. + * @author Dmitriy Moroz + */ + fun filterSupported(preferences: BackupPreferences): BackupPreferences + + /** + * Reads meaningful provider or partial-setup groups with persisted field presence, plus effective app settings. + * Auto-written empty/default provider snapshots do not make a provider configured. + * @author Dmitriy Moroz + */ + fun read(): BackupPreferences + + /** + * Atomically persists selected provider fields without selecting a provider. + * @param providers Known provider fields to replace; absent values retain their destination state. + * @param authorizationCommitId New protected Basic Auth association, or null to preserve the existing association. + * @author Dmitriy Moroz + */ + fun writeProviders( + providers: Map>, + authorizationCommitId: String? + ) + + /** + * Atomically persists known user settings; unsupported fields must be ignored. + * @param settings Typed allowlisted field replacements. + * @author Dmitriy Moroz + */ + fun writeSettings(settings: Map) + + /** + * Reads the durable first-launch stage without changing completed existing installations. + * @author Dmitriy Moroz + */ + fun readStartupStage(): BackupStartupStage + + /** + * Persists post-onboarding progression before its route is replaced. + * @param stage New durable startup stage. + * @author Dmitriy Moroz + */ + fun writeStartupStage(stage: BackupStartupStage) +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/CancelBackupExportUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/CancelBackupExportUseCase.kt new file mode 100644 index 000000000..a461b3c12 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/CancelBackupExportUseCase.kt @@ -0,0 +1,14 @@ +package com.shifthackz.aisdv1.domain.usecase.backup + + +/** + * Cancels the active destination copy while retaining its staged source for retry. + * @author Dmitriy Moroz + */ +interface CancelBackupExportUseCase { + /** + * Cancels the active destination copy while retaining its staged source for retry. + * @author Dmitriy Moroz + */ + operator fun invoke() +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/CompleteBackupExportUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/CompleteBackupExportUseCase.kt new file mode 100644 index 000000000..739913ef8 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/CompleteBackupExportUseCase.kt @@ -0,0 +1,16 @@ +package com.shifthackz.aisdv1.domain.usecase.backup + +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportCompletion + +/** + * Queues native document results without depending on a screen initialization job. + * @author Dmitriy Moroz + */ +interface CompleteBackupExportUseCase { + /** + * Queues native document results without depending on a screen initialization job. + * @param completion Native outcome for the durably pending export. + * @author Dmitriy Moroz + */ + operator fun invoke(completion: BackupExportCompletion) +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/CreateBackupUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/CreateBackupUseCase.kt new file mode 100644 index 000000000..33d6698a7 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/CreateBackupUseCase.kt @@ -0,0 +1,22 @@ +package com.shifthackz.aisdv1.domain.usecase.backup + +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection +import com.shifthackz.aisdv1.domain.entity.backup.BackupProgress +import com.shifthackz.aisdv1.domain.entity.backup.BackupExport + +/** + * Streams selected app data into a complete private binary archive; failure never returns an export. + * @author Dmitriy Moroz + */ +interface CreateBackupUseCase { + /** + * Streams selected app data into a complete private binary archive; failure never returns an export. + * @param selection Available categories and provider children to include. + * @param onProgress Receives bounded work progress; callbacks contain no credentials. + * @author Dmitriy Moroz + */ + suspend operator fun invoke( + selection: BackupSelection, + onProgress: (BackupProgress) -> Unit + ): BackupExport +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/DiscardBackupUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/DiscardBackupUseCase.kt new file mode 100644 index 000000000..fc27e0e1f --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/DiscardBackupUseCase.kt @@ -0,0 +1,15 @@ +package com.shifthackz.aisdv1.domain.usecase.backup + + +/** + * Releases only app-owned staging for an abandoned or completed archive. + * @author Dmitriy Moroz + */ +interface DiscardBackupUseCase { + /** + * Releases only app-owned staging for an abandoned or completed archive. + * @param handle Opaque archive identity or its private document reference. + * @author Dmitriy Moroz + */ + suspend operator fun invoke(handle: String) +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/DismissBackupExportUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/DismissBackupExportUseCase.kt new file mode 100644 index 000000000..ee2249031 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/DismissBackupExportUseCase.kt @@ -0,0 +1,14 @@ +package com.shifthackz.aisdv1.domain.usecase.backup + + +/** + * Acknowledges a completed/abandoned export and releases only its private staging. + * @author Dmitriy Moroz + */ +interface DismissBackupExportUseCase { + /** + * Acknowledges a completed/abandoned export and releases only its private staging. + * @author Dmitriy Moroz + */ + suspend operator fun invoke() +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/ExportBackupUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/ExportBackupUseCase.kt new file mode 100644 index 000000000..5289a6d3b --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/ExportBackupUseCase.kt @@ -0,0 +1,16 @@ +package com.shifthackz.aisdv1.domain.usecase.backup + + +/** + * Copies a complete private archive to a user-selected Android destination; iOS exports the staged document natively. + * @author Dmitriy Moroz + */ +interface ExportBackupUseCase { + /** + * Copies a complete private archive to a user-selected Android destination; iOS exports the staged document natively. + * @param document Private archive reference produced by create. + * @param destination Opaque destination reference from the native document picker. + * @author Dmitriy Moroz + */ + suspend operator fun invoke(document: String, destination: String) +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/GetBackupStartupStageUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/GetBackupStartupStageUseCase.kt new file mode 100644 index 000000000..92ab87160 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/GetBackupStartupStageUseCase.kt @@ -0,0 +1,15 @@ +package com.shifthackz.aisdv1.domain.usecase.backup + +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage + +/** + * Reads durable recovery routing without starting work or changing the active provider. + * @author Dmitriy Moroz + */ +interface GetBackupStartupStageUseCase { + /** + * Reads durable recovery routing without starting work or changing the active provider. + * @author Dmitriy Moroz + */ + operator fun invoke(): BackupStartupStage +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/GetPendingBackupExportUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/GetPendingBackupExportUseCase.kt new file mode 100644 index 000000000..eb7e96df7 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/GetPendingBackupExportUseCase.kt @@ -0,0 +1,14 @@ +package com.shifthackz.aisdv1.domain.usecase.backup + + +/** + * Checks durable export intent so startup restores its dedicated route. + * @author Dmitriy Moroz + */ +interface GetPendingBackupExportUseCase { + /** + * Checks durable export intent so startup restores its dedicated route. + * @author Dmitriy Moroz + */ + suspend operator fun invoke(): Boolean +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/InspectBackupUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/InspectBackupUseCase.kt new file mode 100644 index 000000000..4f613e88d --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/InspectBackupUseCase.kt @@ -0,0 +1,21 @@ +package com.shifthackz.aisdv1.domain.usecase.backup + +import com.shifthackz.aisdv1.domain.entity.backup.BackupInspection +import com.shifthackz.aisdv1.domain.entity.backup.BackupProgress + +/** + * Copies a document into private staging and validates its binary container before any user-data mutation. + * @author Dmitriy Moroz + */ +interface InspectBackupUseCase { + /** + * Copies a document into private staging and validates its binary container before any user-data mutation. + * @param document Opaque reference returned by the native document picker. + * @param onProgress Receives staging and validation progress. + * @author Dmitriy Moroz + */ + suspend operator fun invoke( + document: String, + onProgress: (BackupProgress) -> Unit + ): BackupInspection +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/LoadBackupInventoryUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/LoadBackupInventoryUseCase.kt new file mode 100644 index 000000000..835b69a9c --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/LoadBackupInventoryUseCase.kt @@ -0,0 +1,15 @@ +package com.shifthackz.aisdv1.domain.usecase.backup + +import com.shifthackz.aisdv1.domain.entity.backup.BackupInspection + +/** + * Loads available portable categories without reading every gallery image. + * @author Dmitriy Moroz + */ +interface LoadBackupInventoryUseCase { + /** + * Loads available portable categories without reading every gallery image. + * @author Dmitriy Moroz + */ + suspend operator fun invoke(): BackupInspection +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/LoadPendingBackupUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/LoadPendingBackupUseCase.kt new file mode 100644 index 000000000..21b6e7441 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/LoadPendingBackupUseCase.kt @@ -0,0 +1,15 @@ +package com.shifthackz.aisdv1.domain.usecase.backup + +import com.shifthackz.aisdv1.domain.entity.backup.BackupRecovery + +/** + * Recovers unfinished checked preferences before allowing normal startup and returns resumable restore state. + * @author Dmitriy Moroz + */ +interface LoadPendingBackupUseCase { + /** + * Loads one durable pending operation, or null when startup may continue normally. + * @author Dmitriy Moroz + */ + suspend operator fun invoke(): BackupRecovery? +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/ObserveBackupExportUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/ObserveBackupExportUseCase.kt new file mode 100644 index 000000000..d03d9c65a --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/ObserveBackupExportUseCase.kt @@ -0,0 +1,16 @@ +package com.shifthackz.aisdv1.domain.usecase.backup + +import kotlinx.coroutines.flow.StateFlow +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportOperation + +/** + * Observes process-owned export progress across screen/activity recreation. + * @author Dmitriy Moroz + */ +interface ObserveBackupExportUseCase { + /** + * Observes process-owned export progress across screen/activity recreation. + * @author Dmitriy Moroz + */ + operator fun invoke(): StateFlow +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/RestoreBackupUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/RestoreBackupUseCase.kt new file mode 100644 index 000000000..51b64d203 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/RestoreBackupUseCase.kt @@ -0,0 +1,22 @@ +package com.shifthackz.aisdv1.domain.usecase.backup + +import com.shifthackz.aisdv1.domain.entity.backup.BackupProgress +import com.shifthackz.aisdv1.domain.entity.backup.BackupRestoreRequest +import com.shifthackz.aisdv1.domain.entity.backup.BackupRestoreResult + +/** + * Merges selected data with category-atomic commits and durable retry identity; cancellation propagates. + * @author Dmitriy Moroz + */ +interface RestoreBackupUseCase { + /** + * Merges selected data with category-atomic commits and durable retry identity; cancellation propagates. + * @param request Validated archive, selection and conflict consent. + * @param onProgress Receives current import stage progress. + * @author Dmitriy Moroz + */ + suspend operator fun invoke( + request: BackupRestoreRequest, + onProgress: (BackupProgress) -> Unit + ): BackupRestoreResult +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/SetBackupStartupStageUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/SetBackupStartupStageUseCase.kt new file mode 100644 index 000000000..37ade1859 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/backup/SetBackupStartupStageUseCase.kt @@ -0,0 +1,16 @@ +package com.shifthackz.aisdv1.domain.usecase.backup + +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage + +/** + * Persists a forward first-launch transition before navigation; stale earlier stages are ignored. + * @author Dmitriy Moroz + */ +interface SetBackupStartupStageUseCase { + /** + * Persists a forward first-launch transition before navigation; stale earlier stages are ignored. + * @param stage New recovery stage. + * @author Dmitriy Moroz + */ + operator fun invoke(stage: BackupStartupStage) +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/connectivity/ObserveSeverConnectivityUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/connectivity/ObserveSeverConnectivityUseCase.kt index c81617100..88277c419 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/connectivity/ObserveSeverConnectivityUseCase.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/connectivity/ObserveSeverConnectivityUseCase.kt @@ -5,30 +5,32 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged /** - * Executes the `function` step in the SDAI domain layer. + * Observes connectivity of the configured generation server. * * @author Dmitriy Moroz */ fun interface ObserveSeverConnectivityUseCase { + /** + * Emits the current connectivity state and later distinct changes. + * + * @author Dmitriy Moroz + */ operator fun invoke(): Flow } /** - * Implements `ObserveSeverConnectivityUseCase` behavior in the SDAI domain layer. + * Observes server connectivity while suppressing consecutive duplicate states. + * + * @param serverConnectivityGateway Supplies connectivity changes for the configured server. * * @author Dmitriy Moroz */ -class ObserveSeverConnectivityUseCaseImpl( - /** - * Exposes the `serverConnectivityGateway` value used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ +internal class ObserveSeverConnectivityUseCaseImpl( private val serverConnectivityGateway: ServerConnectivityGateway, ) : ObserveSeverConnectivityUseCase { /** - * Executes the `invoke` step in the SDAI domain layer. + * Emits the current connectivity state and subsequent distinct changes. * * @author Dmitriy Moroz */ diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/debug/DebugInsertBadBase64UseCaseImpl.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/debug/DebugInsertBadBase64UseCaseImpl.kt index 93232f5a1..61eebb712 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/debug/DebugInsertBadBase64UseCaseImpl.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/debug/DebugInsertBadBase64UseCaseImpl.kt @@ -5,27 +5,20 @@ import com.shifthackz.aisdv1.domain.entity.AiGenerationResult import com.shifthackz.aisdv1.domain.repository.GenerationResultRepository /** - * Implements `DebugInsertBadBase64UseCase` behavior in the SDAI domain layer. + * Adds a deliberately invalid gallery image for the developer diagnostics action. + * + * @param repository Persists the diagnostic gallery entry. + * @param timeProvider Supplies its creation timestamp and invalid image content. * * @author Dmitriy Moroz */ -class DebugInsertBadBase64UseCaseImpl( - /** - * Exposes the `repository` value used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ +internal class DebugInsertBadBase64UseCaseImpl( private val repository: GenerationResultRepository, - /** - * Exposes the `timeProvider` value used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ private val timeProvider: TimeProvider, ) : DebugInsertBadBase64UseCase { /** - * Executes the `invoke` step in the SDAI domain layer. + * Inserts one diagnostic gallery entry with intentionally invalid image bytes. * * @author Dmitriy Moroz */ @@ -33,16 +26,11 @@ class DebugInsertBadBase64UseCaseImpl( repository.insert(stubBadBase64Generation(timeProvider.currentTimeMillis())) } - /** - * Provides the `companion object` singleton used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ companion object { /** - * Executes the `stubBadBase64Generation` step in the SDAI domain layer. + * Builds an invalid-image entry with otherwise usable generation metadata. * - * @param now now value consumed by the API. + * @param now Creation timestamp also used as deliberately invalid Base64 content. * @author Dmitriy Moroz */ private fun stubBadBase64Generation(now: Long) = AiGenerationResult( diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/donate/FetchSupportersUseCaseImpl.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/donate/FetchSupportersUseCaseImpl.kt index d5cff2b3c..1fc62c335 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/donate/FetchSupportersUseCaseImpl.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/donate/FetchSupportersUseCaseImpl.kt @@ -4,21 +4,18 @@ import com.shifthackz.aisdv1.domain.entity.Supporter import com.shifthackz.aisdv1.domain.repository.SupportersRepository /** - * Implements `FetchSupportersUseCase` behavior in the SDAI domain layer. + * Refreshes the supporter list through its repository. + * + * @param repository Loads the current supporter list and its stored representation. * * @author Dmitriy Moroz */ -class FetchSupportersUseCaseImpl( - /** - * Exposes the `repository` value used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ +internal class FetchSupportersUseCaseImpl( private val repository: SupportersRepository, ) : FetchSupportersUseCase { /** - * Executes the `invoke` step in the SDAI domain layer. + * Returns supporters after the repository refresh completes. * * @author Dmitriy Moroz */ diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/gallery/GetMediaStoreInfoUseCaseImpl.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/gallery/GetMediaStoreInfoUseCaseImpl.kt index c8b10c1db..255175897 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/gallery/GetMediaStoreInfoUseCaseImpl.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/gallery/GetMediaStoreInfoUseCaseImpl.kt @@ -3,21 +3,18 @@ package com.shifthackz.aisdv1.domain.usecase.gallery import com.shifthackz.aisdv1.domain.gateway.MediaStoreGateway /** - * Implements `GetMediaStoreInfoUseCase` behavior in the SDAI domain layer. + * Reads storage information for the gallery export destination. + * + * @param mediaStoreGateway Provides platform-specific media storage information. * * @author Dmitriy Moroz */ -class GetMediaStoreInfoUseCaseImpl( - /** - * Exposes the `mediaStoreGateway` value used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ +internal class GetMediaStoreInfoUseCaseImpl( private val mediaStoreGateway: MediaStoreGateway, ) : GetMediaStoreInfoUseCase { /** - * Executes the `invoke` step in the SDAI domain layer. + * Returns the platform media storage information. * * @author Dmitriy Moroz */ diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/GetRandomImageUseCaseImpl.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/GetRandomImageUseCaseImpl.kt index 467167acf..c6d6f4dcc 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/GetRandomImageUseCaseImpl.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/GetRandomImageUseCaseImpl.kt @@ -3,21 +3,18 @@ package com.shifthackz.aisdv1.domain.usecase.generation import com.shifthackz.aisdv1.domain.repository.RandomImageRepository /** - * Implements `GetRandomImageUseCase` behavior in the SDAI domain layer. + * Loads a random reference image for the generation input. + * + * @param randomImageRepository Fetches and stores the random reference image. * * @author Dmitriy Moroz */ -class GetRandomImageUseCaseImpl( - /** - * Exposes the `randomImageRepository` value used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ +internal class GetRandomImageUseCaseImpl( private val randomImageRepository: RandomImageRepository, ) : GetRandomImageUseCase { /** - * Executes the `invoke` step in the SDAI domain layer. + * Returns the reference image supplied by the repository. * * @author Dmitriy Moroz */ diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/ImageToImageUseCaseImpl.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/ImageToImageUseCaseImpl.kt index 4b40de924..7cc364f67 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/ImageToImageUseCaseImpl.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/ImageToImageUseCaseImpl.kt @@ -7,6 +7,7 @@ import com.shifthackz.aisdv1.domain.usecase.easydiffusion.toEasyDiffusionRequest import kotlinx.coroutines.ensureActive import kotlin.coroutines.coroutineContext +import com.shifthackz.aisdv1.domain.gateway.GenerationRestoreGate import com.shifthackz.aisdv1.domain.entity.AiGenerationResult import com.shifthackz.aisdv1.domain.entity.ImageToImagePayload import com.shifthackz.aisdv1.domain.entity.ServerSource @@ -32,6 +33,7 @@ import com.shifthackz.aisdv1.domain.repository.SwarmUiGenerationRepository * @param falAiGenerationRepository Generation and result persistence for Fal.ai. * @param arliAiGenerationRepository Generation and result persistence for ArliAI. * @param preferenceManager Current provider selection and independent generation preferences. + * @param generationRestoreGate Serializes generation against portable backup restoration. * @param captureEasyDiffusionConnectionUseCase Captures endpoint/checkpoint under the provider-selection lock, retaining the submitted revision. * @param generateEasyDiffusionUseCase Owns captured-task batching, stream recovery, cancellation and deadlines. * @author Dmitriy Moroz @@ -55,6 +57,7 @@ internal class ImageToImageUseCaseImpl( private val arliAiGenerationRepository: ArliAiGenerationRepository, private val preferenceManager: PreferenceManager, + private val generationRestoreGate: GenerationRestoreGate, private val generateEasyDiffusionUseCase: GenerateEasyDiffusionUseCase, private val captureEasyDiffusionConnectionUseCase: CaptureEasyDiffusionConnectionUseCase, ) : ImageToImageUseCase { @@ -65,7 +68,15 @@ internal class ImageToImageUseCaseImpl( * @param payload Immutable supported generation inputs and captured provider identity. * @author Dmitriy Moroz */ - override suspend fun invoke(payload: ImageToImagePayload): List { + override suspend fun invoke(payload: ImageToImagePayload): List = + generationRestoreGate.generating { generate(payload) } + + /** + * Executes a captured image request while this operation owns generation admission. + * @param payload Immutable provider generation inputs and source image. + * @author Dmitriy Moroz + */ + private suspend fun generate(payload: ImageToImagePayload): List { coroutineContext.ensureActive() val source = payload.sourceSnapshot ?: preferenceManager.source check(source == preferenceManager.source) { "Generation source changed" } diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/TextToImageUseCaseImpl.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/TextToImageUseCaseImpl.kt index e3cc96e0b..126fcabe7 100755 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/TextToImageUseCaseImpl.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/TextToImageUseCaseImpl.kt @@ -7,6 +7,7 @@ import com.shifthackz.aisdv1.domain.usecase.easydiffusion.toEasyDiffusionRequest import kotlinx.coroutines.ensureActive import kotlin.coroutines.coroutineContext +import com.shifthackz.aisdv1.domain.gateway.GenerationRestoreGate import com.shifthackz.aisdv1.domain.entity.AiGenerationResult import com.shifthackz.aisdv1.domain.entity.ServerSource import com.shifthackz.aisdv1.domain.entity.TextToImagePayload @@ -49,6 +50,7 @@ import com.shifthackz.aisdv1.domain.repository.SwarmUiGenerationRepository * @param bonsaiGenerationRepository Generation and result persistence for Bonsai. * @param mnnGenerationRepository Isolated MNN request execution after fixed-profile and seed admission. * @param preferenceManager Current provider selection and independent generation preferences. + * @param generationRestoreGate Serializes generation against portable backup restoration. * @param generateEasyDiffusionUseCase Owns captured-task batching, stream recovery, cancellation and deadlines. * @param captureEasyDiffusionConnectionUseCase Captures endpoint/checkpoint under the provider-selection lock, retaining the submitted revision. * @@ -86,6 +88,7 @@ internal class TextToImageUseCaseImpl( private val mnnGenerationRepository: MnnGenerationRepository, private val preferenceManager: PreferenceManager, + private val generationRestoreGate: GenerationRestoreGate, private val generateEasyDiffusionUseCase: GenerateEasyDiffusionUseCase, private val captureEasyDiffusionConnectionUseCase: CaptureEasyDiffusionConnectionUseCase, ) : TextToImageUseCase { @@ -101,9 +104,15 @@ internal class TextToImageUseCaseImpl( * * @author Dmitriy Moroz */ - override suspend operator fun invoke( - payload: TextToImagePayload, - ): List { + override suspend operator fun invoke(payload: TextToImagePayload): List = + generationRestoreGate.generating { generate(payload) } + + /** + * Executes a captured text request while this operation owns generation admission. + * @param payload Immutable provider generation inputs. + * @author Dmitriy Moroz + */ + private suspend fun generate(payload: TextToImagePayload): List { val source = payload.sourceSnapshot ?: preferenceManager.source check(source == preferenceManager.source) { "Generation source changed" } if (source == ServerSource.LOCAL_MNN) { diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/huggingface/FetchHuggingFaceModelsUseCaseImpl.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/huggingface/FetchHuggingFaceModelsUseCaseImpl.kt index 95771b49a..cfd00debd 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/huggingface/FetchHuggingFaceModelsUseCaseImpl.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/huggingface/FetchHuggingFaceModelsUseCaseImpl.kt @@ -6,29 +6,22 @@ import com.shifthackz.aisdv1.domain.preference.PreferenceManager import com.shifthackz.aisdv1.domain.repository.HuggingFaceModelsRepository /** - * Implements `FetchHuggingFaceModelsUseCase` behavior in the SDAI domain layer. + * Loads Hugging Face models only while that provider is selected. + * + * @param preferenceManager Identifies the currently selected generation provider. + * @param repository Refreshes and reads the Hugging Face model catalog. * * @author Dmitriy Moroz */ -class FetchHuggingFaceModelsUseCaseImpl( - /** - * Exposes the `preferenceManager` value used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ +internal class FetchHuggingFaceModelsUseCaseImpl( private val preferenceManager: PreferenceManager, - /** - * Exposes the `repository` value used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ private val repository: HuggingFaceModelsRepository, ) : FetchHuggingFaceModelsUseCase { /** - * Executes the `invoke` step in the SDAI domain layer. + * Returns refreshed Hugging Face models, or an empty list for another provider. * - * @return Result produced by `invoke`. + * @return The catalog available for the current provider. * @author Dmitriy Moroz */ override suspend fun invoke(): List { diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/report/SendReportUseCaseImpl.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/report/SendReportUseCaseImpl.kt index 3a3dd3e81..642462383 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/report/SendReportUseCaseImpl.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/report/SendReportUseCaseImpl.kt @@ -4,25 +4,22 @@ import com.shifthackz.aisdv1.domain.entity.ReportReason import com.shifthackz.aisdv1.domain.repository.ReportRepository /** - * Implements `SendReportUseCase` behavior in the SDAI domain layer. + * Submits a user report with its reason and attached image. + * + * @param repository Delivers the report to the configured reporting destination. * * @author Dmitriy Moroz */ -class SendReportUseCaseImpl( - /** - * Exposes the `repository` value used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ +internal class SendReportUseCaseImpl( private val repository: ReportRepository, ) : SendReportUseCase { /** - * Executes the `invoke` step in the SDAI domain layer. + * Sends the supplied report and propagates delivery failures. * - * @param text text value consumed by the API. - * @param reason reason value consumed by the API. - * @param image image value consumed by the API. + * @param text User-provided description of the issue. + * @param reason Report category selected by the user. + * @param image Image attachment passed to the reporting repository. * @author Dmitriy Moroz */ override suspend fun invoke(text: String, reason: ReportReason, image: String) = diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/sdembedding/FetchAndGetEmbeddingsUseCaseImpl.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/sdembedding/FetchAndGetEmbeddingsUseCaseImpl.kt index 7a330c52c..aaa1bbf03 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/sdembedding/FetchAndGetEmbeddingsUseCaseImpl.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/sdembedding/FetchAndGetEmbeddingsUseCaseImpl.kt @@ -4,21 +4,18 @@ import com.shifthackz.aisdv1.domain.entity.Embedding import com.shifthackz.aisdv1.domain.repository.EmbeddingsRepository /** - * Implements `FetchAndGetEmbeddingsUseCase` behavior in the SDAI domain layer. + * Refreshes and reads the configured server embedding catalog. + * + * @param repository Refreshes embedding descriptors and reads the resulting catalog. * * @author Dmitriy Moroz */ -class FetchAndGetEmbeddingsUseCaseImpl( - /** - * Exposes the `repository` value used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ +internal class FetchAndGetEmbeddingsUseCaseImpl( private val repository: EmbeddingsRepository, ) : FetchAndGetEmbeddingsUseCase { /** - * Executes the `invoke` step in the SDAI domain layer. + * Returns the embedding catalog after its repository refresh. * * @author Dmitriy Moroz */ diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/sdlora/FetchAndGetLorasUseCaseImpl.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/sdlora/FetchAndGetLorasUseCaseImpl.kt index 46af5001f..a250d8ffd 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/sdlora/FetchAndGetLorasUseCaseImpl.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/sdlora/FetchAndGetLorasUseCaseImpl.kt @@ -3,21 +3,18 @@ package com.shifthackz.aisdv1.domain.usecase.sdlora import com.shifthackz.aisdv1.domain.repository.LorasRepository /** - * Implements `FetchAndGetLorasUseCase` behavior in the SDAI domain layer. + * Refreshes and reads the configured server LoRA catalog. + * + * @param lorasRepository Refreshes LoRA descriptors and reads the resulting catalog. * * @author Dmitriy Moroz */ -class FetchAndGetLorasUseCaseImpl( - /** - * Exposes the `lorasRepository` value used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ +internal class FetchAndGetLorasUseCaseImpl( private val lorasRepository: LorasRepository, ) : FetchAndGetLorasUseCase { /** - * Executes the `invoke` step in the SDAI domain layer. + * Returns the LoRA catalog after its repository refresh. * * @author Dmitriy Moroz */ diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/sdmodel/GetStableDiffusionModelsUseCaseImpl.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/sdmodel/GetStableDiffusionModelsUseCaseImpl.kt index 7d37c22fe..c223afc81 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/sdmodel/GetStableDiffusionModelsUseCaseImpl.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/sdmodel/GetStableDiffusionModelsUseCaseImpl.kt @@ -7,35 +7,24 @@ import com.shifthackz.aisdv1.domain.repository.ServerConfigurationRepository import com.shifthackz.aisdv1.domain.repository.StableDiffusionModelsRepository /** - * Implements `GetStableDiffusionModelsUseCase` behavior in the SDAI domain layer. + * Loads Automatic1111 checkpoints and marks the server-selected checkpoint. + * + * @param preferenceManager Identifies whether Automatic1111 is the selected provider. + * @param serverConfigurationRepository Reads the refreshed server checkpoint selection. + * @param sdModelsRepository Refreshes and reads available checkpoint descriptors. * * @author Dmitriy Moroz */ -class GetStableDiffusionModelsUseCaseImpl( - /** - * Exposes the `preferenceManager` value used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ +internal class GetStableDiffusionModelsUseCaseImpl( private val preferenceManager: PreferenceManager, - /** - * Exposes the `serverConfigurationRepository` value used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ private val serverConfigurationRepository: ServerConfigurationRepository, - /** - * Exposes the `sdModelsRepository` value used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ private val sdModelsRepository: StableDiffusionModelsRepository, ) : GetStableDiffusionModelsUseCase { /** - * Executes the `invoke` step in the SDAI domain layer. + * Returns checkpoints paired with their selected state, or an empty list for another provider. * - * @return Result produced by `invoke`. + * @return The catalog available for the current provider. * @author Dmitriy Moroz */ override suspend operator fun invoke(): List> { diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/sdsampler/GetStableDiffusionSamplersUseCaseImpl.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/sdsampler/GetStableDiffusionSamplersUseCaseImpl.kt index 33caf9bb5..e05fbc729 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/sdsampler/GetStableDiffusionSamplersUseCaseImpl.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/sdsampler/GetStableDiffusionSamplersUseCaseImpl.kt @@ -10,7 +10,7 @@ import kotlinx.coroutines.CancellationException * @param repository Fetches samplers from the configured server and reads their cache. * @author Dmitriy Moroz */ -class GetStableDiffusionSamplersUseCaseImpl( +internal class GetStableDiffusionSamplersUseCaseImpl( private val repository: StableDiffusionSamplersRepository, ) : GetStableDiffusionSamplersUseCase { diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/settings/DefaultSetServerConfigurationUseCaseImpl.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/settings/DefaultSetServerConfigurationUseCaseImpl.kt index 7fcaa78b8..12209bdf6 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/settings/DefaultSetServerConfigurationUseCaseImpl.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/settings/DefaultSetServerConfigurationUseCaseImpl.kt @@ -2,6 +2,8 @@ package com.shifthackz.aisdv1.domain.usecase.settings import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider import com.shifthackz.aisdv1.domain.entity.AuthorizationStorageFailure +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage +import com.shifthackz.aisdv1.domain.gateway.backup.BackupPreferencesGateway import com.shifthackz.aisdv1.domain.entity.Configuration import com.shifthackz.aisdv1.domain.entity.ServerSource import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationStore @@ -23,6 +25,7 @@ import kotlinx.coroutines.withContext * @param authorizationStore Commits protected Basic Auth before publishing its provider settings. * @param preferenceManager Refreshes observers after the complete transition. * @param providerSelectionGuard Serializes source changes and identity-sensitive publication. + * @param backupPreferences Completes first-launch recovery only after a real provider configuration commit. * @author Dmitriy Moroz */ internal class DefaultSetServerConfigurationUseCaseImpl( @@ -31,6 +34,7 @@ internal class DefaultSetServerConfigurationUseCaseImpl( private val authorizationStore: AuthorizationStore, private val preferenceManager: PreferenceManager, private val providerSelectionGuard: ProviderSelectionGuard, + private val backupPreferences: BackupPreferencesGateway, ) : SetServerConfigurationUseCase { /** * Commits Basic Auth only for providers that use it, preserving stored credentials otherwise. @@ -60,6 +64,9 @@ internal class DefaultSetServerConfigurationUseCaseImpl( configurationStore.getAuthorizationCommitId() ) } + if (backupPreferences.readStartupStage() == BackupStartupStage.CONFIGURATION) { + backupPreferences.writeStartupStage(BackupStartupStage.COMPLETE) + } preferenceManager.refresh() } } diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/settings/NetworkUsageUseCases.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/settings/NetworkUsageUseCases.kt index 9984824c7..cee7de19c 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/settings/NetworkUsageUseCases.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/settings/NetworkUsageUseCases.kt @@ -25,7 +25,7 @@ fun interface ObserveNetworkUsageUseCase { * * @author Dmitriy Moroz */ -class ObserveNetworkUsageUseCaseImpl( +internal class ObserveNetworkUsageUseCaseImpl( private val repository: NetworkUsageRepository, ) : ObserveNetworkUsageUseCase { override fun invoke(): Flow = repository.observe() @@ -52,7 +52,7 @@ fun interface ResetNetworkUsageUseCase { * * @author Dmitriy Moroz */ -class ResetNetworkUsageUseCaseImpl( +internal class ResetNetworkUsageUseCaseImpl( private val repository: NetworkUsageRepository, ) : ResetNetworkUsageUseCase { override suspend fun invoke() = repository.reset() diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/splash/SplashNavigationUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/splash/SplashNavigationUseCase.kt index b1a43bff3..f082a270c 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/splash/SplashNavigationUseCase.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/splash/SplashNavigationUseCase.kt @@ -1,70 +1,31 @@ package com.shifthackz.aisdv1.domain.usecase.splash -import com.shifthackz.aisdv1.domain.entity.ServerSource -import com.shifthackz.aisdv1.domain.preference.PreferenceManager /** - * Defines the `SplashNavigationUseCase` contract for the SDAI domain layer. + * Chooses startup routing from onboarding, recovery and saved provider state. * * @author Dmitriy Moroz */ interface SplashNavigationUseCase { /** - * Executes the `invoke` step in the SDAI domain layer. + * Returns the first route that can safely publish the current persisted configuration. * - * @return Result produced by `invoke`. + * @return Startup destination after pending restore checks. * @author Dmitriy Moroz */ suspend operator fun invoke(): Action /** - * Coordinates `Action` behavior in the SDAI domain layer. + * Startup destinations evaluated before normal provider loading. * * @author Dmitriy Moroz */ enum class Action { LAUNCH_ONBOARDING, + LAUNCH_BACKUP_WELCOME, + LAUNCH_BACKUP_RESTORE, + LAUNCH_INITIAL_RESTORE, LAUNCH_SERVER_SETUP, LAUNCH_HOME; } } - -/** - * Implements `SplashNavigationUseCase` behavior in the SDAI domain layer. - * - * @author Dmitriy Moroz - */ -class SplashNavigationUseCaseImpl( - /** - * Exposes the `preferenceManager` value used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ - private val preferenceManager: PreferenceManager, -) : SplashNavigationUseCase { - - /** - * Executes the `invoke` step in the SDAI domain layer. - * - * @return Result produced by `invoke`. - * @author Dmitriy Moroz - */ - override suspend fun invoke(): SplashNavigationUseCase.Action { - return when { - !preferenceManager.onBoardingComplete -> { - SplashNavigationUseCase.Action.LAUNCH_ONBOARDING - } - - preferenceManager.forceSetupAfterUpdate -> { - SplashNavigationUseCase.Action.LAUNCH_SERVER_SETUP - } - - preferenceManager.automatic1111ServerUrl.isEmpty() && - preferenceManager.source == ServerSource.AUTOMATIC1111 -> { - SplashNavigationUseCase.Action.LAUNCH_SERVER_SETUP - } - - else -> SplashNavigationUseCase.Action.LAUNCH_HOME - } - } -} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/splash/SplashNavigationUseCaseImpl.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/splash/SplashNavigationUseCaseImpl.kt new file mode 100644 index 000000000..97cd28531 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/splash/SplashNavigationUseCaseImpl.kt @@ -0,0 +1,38 @@ +package com.shifthackz.aisdv1.domain.usecase.splash + +import com.shifthackz.aisdv1.domain.entity.ServerSource +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage +import com.shifthackz.aisdv1.domain.preference.PreferenceManager +import com.shifthackz.aisdv1.domain.usecase.backup.GetBackupStartupStageUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.LoadPendingBackupUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.GetPendingBackupExportUseCase + +/** + * Routes unfinished recovery before publishing normal provider state; existing installations skip the invitation. + * + * @param preferenceManager Existing onboarding and provider prerequisites. + * @param getBackupStartupStage Durable fresh-install recovery progression. + * @param loadPendingBackup Revalidates pending restore intent and recovers checked credential associations. + * @param getPendingExport Checks for a staged native export that needs its backup route restored. + * + * @author Dmitriy Moroz + */ +internal class SplashNavigationUseCaseImpl( + private val preferenceManager: PreferenceManager, + private val getBackupStartupStage: GetBackupStartupStageUseCase, + private val loadPendingBackup: LoadPendingBackupUseCase, + private val getPendingExport: GetPendingBackupExportUseCase, +) : SplashNavigationUseCase { + + override suspend fun invoke(): SplashNavigationUseCase.Action = when { + !preferenceManager.onBoardingComplete -> SplashNavigationUseCase.Action.LAUNCH_ONBOARDING + loadPendingBackup() != null -> if (getBackupStartupStage() == BackupStartupStage.RESTORE) SplashNavigationUseCase.Action.LAUNCH_INITIAL_RESTORE else SplashNavigationUseCase.Action.LAUNCH_BACKUP_RESTORE + getBackupStartupStage() == BackupStartupStage.INVITATION -> SplashNavigationUseCase.Action.LAUNCH_BACKUP_WELCOME + getBackupStartupStage() == BackupStartupStage.RESTORE -> SplashNavigationUseCase.Action.LAUNCH_INITIAL_RESTORE + getBackupStartupStage() == BackupStartupStage.CONFIGURATION -> SplashNavigationUseCase.Action.LAUNCH_SERVER_SETUP + getPendingExport() -> SplashNavigationUseCase.Action.LAUNCH_BACKUP_RESTORE + preferenceManager.forceSetupAfterUpdate -> SplashNavigationUseCase.Action.LAUNCH_SERVER_SETUP + preferenceManager.automatic1111ServerUrl.isEmpty() && preferenceManager.source == ServerSource.AUTOMATIC1111 -> SplashNavigationUseCase.Action.LAUNCH_SERVER_SETUP + else -> SplashNavigationUseCase.Action.LAUNCH_HOME + } +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/stabilityai/FetchStabilityAiEnginesUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/stabilityai/FetchStabilityAiEnginesUseCase.kt index 3f0530cc2..be731846b 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/stabilityai/FetchStabilityAiEnginesUseCase.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/stabilityai/FetchStabilityAiEnginesUseCase.kt @@ -4,41 +4,38 @@ import com.shifthackz.aisdv1.domain.entity.StabilityAiEngine import com.shifthackz.aisdv1.domain.repository.StabilityAiEnginesRepository /** - * Defines the `FetchStabilityAiEnginesUseCase` contract for the SDAI domain layer. + * Loads the engines available to a Stability AI account. * * @author Dmitriy Moroz */ interface FetchStabilityAiEnginesUseCase { /** - * Executes the `invoke` step in the SDAI domain layer. + * Returns the engines available to the authenticated account. * - * @param apiKey api key value consumed by the API. - * @return Result produced by `invoke`. + * @param apiKey Account API key used to authenticate the engine request. + * @return The catalog available for the current provider. * @author Dmitriy Moroz */ suspend operator fun invoke(apiKey: String): List } /** - * Implements `FetchStabilityAiEnginesUseCase` behavior in the SDAI domain layer. + * Loads the Stability AI engines available to the supplied account. + * + * @param repository Fetches engine descriptors using the supplied API key. * * @author Dmitriy Moroz */ -class FetchStabilityAiEnginesUseCaseImpl( - /** - * Exposes the `repository` value used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ +internal class FetchStabilityAiEnginesUseCaseImpl( private val repository: StabilityAiEnginesRepository, ) : FetchStabilityAiEnginesUseCase { /** - * Executes the `invoke` step in the SDAI domain layer. + * Returns the engines available to the authenticated account. * - * @param apiKey api key value consumed by the API. - * @return Result produced by `invoke`. + * @param apiKey Account API key used to authenticate the engine request. + * @return The catalog available for the current provider. * @author Dmitriy Moroz */ override suspend fun invoke(apiKey: String): List = diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/stabilityai/ObserveStabilityAiCreditsUseCaseImpl.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/stabilityai/ObserveStabilityAiCreditsUseCaseImpl.kt index 1abcd3429..77f2ba6a8 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/stabilityai/ObserveStabilityAiCreditsUseCaseImpl.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/stabilityai/ObserveStabilityAiCreditsUseCaseImpl.kt @@ -4,21 +4,18 @@ import com.shifthackz.aisdv1.domain.repository.StabilityAiCreditsRepository import kotlinx.coroutines.flow.catch /** - * Implements `ObserveStabilityAiCreditsUseCase` behavior in the SDAI domain layer. + * Observes refreshed Stability AI credits, emitting zero when the credit stream fails. + * + * @param repository Refreshes and observes the account credit balance. * * @author Dmitriy Moroz */ -class ObserveStabilityAiCreditsUseCaseImpl( - /** - * Exposes the `repository` value used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ +internal class ObserveStabilityAiCreditsUseCaseImpl( private val repository: StabilityAiCreditsRepository, ) : ObserveStabilityAiCreditsUseCase { /** - * Executes the `invoke` step in the SDAI domain layer. + * Emits account credits, or zero if refreshing or observing fails. * * @author Dmitriy Moroz */ diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/swarmmodel/FetchSwarmUiModelsUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/swarmmodel/FetchSwarmUiModelsUseCase.kt index 5d83e40ed..38997c144 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/swarmmodel/FetchSwarmUiModelsUseCase.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/swarmmodel/FetchSwarmUiModelsUseCase.kt @@ -5,19 +5,19 @@ import com.shifthackz.aisdv1.domain.entity.SwarmUiModel import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationCredentials /** - * Defines the `FetchSwarmUiModelsUseCase` contract for the SDAI domain layer. + * Loads model descriptors from an authenticated Swarm UI session. * * @author Dmitriy Moroz */ interface FetchSwarmUiModelsUseCase { /** - * Executes the `invoke` step in the SDAI domain layer. + * Returns models reported by the selected Swarm UI session. * - * @param baseUrl base url value consumed by the API. - * @param sessionId session id value consumed by the API. - * @param credentials credentials value consumed by the API. - * @return Result produced by `invoke`. + * @param baseUrl Full API base URL of the selected Swarm UI server. + * @param sessionId Active Swarm UI session identifier. + * @param credentials Optional transport authorization for the server. + * @return The catalog available for the current provider. * @author Dmitriy Moroz */ suspend operator fun invoke( @@ -28,26 +28,23 @@ interface FetchSwarmUiModelsUseCase { } /** - * Implements `FetchSwarmUiModelsUseCase` behavior in the SDAI domain layer. + * Loads models from the selected Swarm UI server session. + * + * @param remoteDataSource Requests model descriptors with server session and transport credentials. * * @author Dmitriy Moroz */ -class FetchSwarmUiModelsUseCaseImpl( - /** - * Exposes the `remoteDataSource` value used by the SDAI domain layer. - * - * @author Dmitriy Moroz - */ +internal class FetchSwarmUiModelsUseCaseImpl( private val remoteDataSource: SwarmUiModelsRemoteDataSource, ) : FetchSwarmUiModelsUseCase { /** - * Executes the `invoke` step in the SDAI domain layer. + * Returns models reported by the selected Swarm UI session. * - * @param baseUrl base url value consumed by the API. - * @param sessionId session id value consumed by the API. - * @param credentials credentials value consumed by the API. - * @return Result produced by `invoke`. + * @param baseUrl Full API base URL of the selected Swarm UI server. + * @param sessionId Active Swarm UI session identifier. + * @param credentials Optional transport authorization for the server. + * @return The catalog available for the current provider. * @author Dmitriy Moroz */ override suspend fun invoke( diff --git a/feature/backup/build.gradle.kts b/feature/backup/build.gradle.kts new file mode 100644 index 000000000..13a47d089 --- /dev/null +++ b/feature/backup/build.gradle.kts @@ -0,0 +1,24 @@ +plugins { + alias(libs.plugins.generic.kmp.library) + alias(libs.plugins.jetbrains.kotlin.serialization) +} +android { namespace = "com.shifthackz.aisdv1.feature.backup" } +kotlin { + sourceSets { + commonMain.dependencies { + implementation(project(":domain")) + implementation(project(":storage")) + implementation(project(":core:common")) + implementation(libs.kotlinx.coroutines.core) + implementation(libs.kotlinx.serialization.json) + implementation(libs.koin.core) + implementation(libs.okio) + } + androidMain.dependencies { implementation(libs.koin.android) } + androidUnitTest.dependencies { + implementation(libs.test.junit) + implementation(libs.test.mockk) + implementation(libs.test.coroutines) + } + } +} diff --git a/feature/backup/src/androidMain/kotlin/com/shifthackz/aisdv1/feature/backup/di/BackupPlatformModule.android.kt b/feature/backup/src/androidMain/kotlin/com/shifthackz/aisdv1/feature/backup/di/BackupPlatformModule.android.kt new file mode 100644 index 000000000..785de1652 --- /dev/null +++ b/feature/backup/src/androidMain/kotlin/com/shifthackz/aisdv1/feature/backup/di/BackupPlatformModule.android.kt @@ -0,0 +1,14 @@ +package com.shifthackz.aisdv1.feature.backup.di + +import com.shifthackz.aisdv1.feature.backup.io.BackupFileStore +import com.shifthackz.aisdv1.feature.backup.io.AndroidBackupFileStore +import org.koin.core.module.Module +import org.koin.dsl.module +import org.koin.android.ext.koin.androidContext + +/** + * Binds native document transport while retaining the shared backup API. + * @author Dmitriy Moroz + */ +internal actual val backupPlatformModule: Module = + module { single { AndroidBackupFileStore(androidContext()) } } diff --git a/feature/backup/src/androidMain/kotlin/com/shifthackz/aisdv1/feature/backup/io/BackupFileStore.android.kt b/feature/backup/src/androidMain/kotlin/com/shifthackz/aisdv1/feature/backup/io/BackupFileStore.android.kt new file mode 100644 index 000000000..90161ed8c --- /dev/null +++ b/feature/backup/src/androidMain/kotlin/com/shifthackz/aisdv1/feature/backup/io/BackupFileStore.android.kt @@ -0,0 +1,75 @@ +package com.shifthackz.aisdv1.feature.backup.io + +import android.content.Context +import android.net.Uri +import android.os.Environment +import android.os.StatFs +import android.provider.DocumentsContract +import android.provider.OpenableColumns +import java.util.UUID +import java.io.File +import okio.Path +import okio.Path.Companion.toPath +import okio.buffer +import okio.source +import okio.sink + +/** + * Stages archives in app-private durable files and streams Storage Access Framework documents. + * @param context Application context used only for private files and document resolver access. + * @author Dmitriy Moroz + */ +internal class AndroidBackupFileStore(private val context: Context) : BackupFileStore { + override val root: Path get() = context.filesDir.resolve("backup").absolutePath.toPath() + + override fun documentReference(path: Path): String = + Uri.fromFile(File(path.toString())).toString() + + override fun documentPath(reference: String): Path { + val uri = Uri.parse(reference) + require(uri.scheme == "file") { "Not a private backup document" } + return checkNotNull(uri.path).toPath() + } + + override fun documentName(document: String): String { + val uri = Uri.parse(document) + return context.contentResolver.query( + uri, + arrayOf(OpenableColumns.DISPLAY_NAME), + null, + null, + null + )?.use { cursor -> + if (cursor.moveToFirst()) cursor.getString(0) else null + } ?: "SDAI.sdaibackup" + } + + override fun documentLocation(document: String): String { + val uri = Uri.parse(document) + if (uri.scheme == "file") return uri.path.orEmpty() + if (uri.authority == "com.android.externalstorage.documents" && DocumentsContract.isDocumentUri( + context, + uri + ) + ) { + val id = DocumentsContract.getDocumentId(uri) + if (id.startsWith("primary:")) { + return Environment.getExternalStorageDirectory().absolutePath + "/" + id.substringAfter( + ':' + ) + } + } + return Uri.decode(uri.buildUpon().clearQuery().fragment(null).build().toString()) + } + + override fun newId(): String = UUID.randomUUID().toString() + + override fun openDocument(document: String) = + checkNotNull(context.contentResolver.openInputStream(Uri.parse(document))).source().buffer() + + override fun writeDocument(document: String) = + checkNotNull(context.contentResolver.openOutputStream(Uri.parse(document), "wt")).sink() + .buffer() + + override fun availableBytes(): Long = StatFs(context.filesDir.absolutePath).availableBytes +} diff --git a/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/archive/BackupArchiveCreationTest.kt b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/archive/BackupArchiveCreationTest.kt new file mode 100644 index 000000000..9ceeb83df --- /dev/null +++ b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/archive/BackupArchiveCreationTest.kt @@ -0,0 +1,221 @@ +package com.shifthackz.aisdv1.feature.backup.archive + +import com.shifthackz.aisdv1.domain.entity.NetworkUsageBucket +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.entity.backup.BackupPreferences +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection +import com.shifthackz.aisdv1.domain.entity.backup.BackupValue +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationCredentials +import com.shifthackz.aisdv1.storage.db.persistent.entity.NetworkUsageEntity +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.verify +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.test.runTest +import okio.FileSystem +import okio.Path.Companion.toPath +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class BackupArchiveCreationTest { + @get:Rule + val temporary = TemporaryFolder() + private lateinit var fixture: BackupArchiveFixture + + @Before + fun setup() { + fixture = BackupArchiveFixture(temporary.newFolder("private").absolutePath.toPath()) + } + + @Test + fun `given settings backup, archive is created, expected only selected settings section and no auth read`() = + runTest { + // Given + val selection = BackupSelection(setOf(BackupCategory.SETTINGS)) + // When + val export = fixture.store.create(selection) {} + val staged = fixture.store.staged(export.handle) + // Then + assertEquals(listOf("settings"), staged.manifest.sections.map { it.id }) + assertEquals(123L, staged.manifest.createdAt) + assertEquals(fixture.snapshot.settings, fixture.store.preferences(staged).settings) + assertEquals(export, fixture.store.preparedExport(export.handle, export.filename)) + assertEquals( + listOf("archive.sdaibackup"), + FileSystem.SYSTEM.list(staged.path.parent!!).map { it.name }) + coVerify(exactly = 0) { fixture.authorization.getAuthorizationCredentials() } + coVerify(exactly = 1) { fixture.staging.prepare() } + } + + @Test + fun `given provider backup, one provider selected, expected its portable credentials without other providers`() = + runTest { + // Given + fixture.snapshot = BackupPreferences( + mapOf( + "custom" to mapOf("serverUrl" to BackupValue.Text("https://host")), + "swarm_ui" to mapOf("serverUrl" to BackupValue.Text("https://other")), + "removed" to emptyMap() + ), emptyMap() + ) + coEvery { fixture.authorization.getAuthorizationCredentials() } returns AuthorizationCredentials.HttpBasic( + "name", + "password" + ) + // When + val export = fixture.store.create( + BackupSelection( + setOf(BackupCategory.PROVIDERS), + setOf("custom") + ) + ) {} + val restored = fixture.store.preferences(fixture.store.staged(export.handle)) + // Then + assertEquals(setOf("custom"), restored.providers.keys) + assertEquals( + BackupValue.Text("name"), + restored.providers.getValue("custom")["basicLogin"] + ) + assertEquals( + BackupValue.Text("password"), + restored.providers.getValue("custom")["basicPassword"] + ) + assertTrue(restored.settings.isEmpty()) + } + + @Test + fun `given empty provider selection, create is requested, expected rejection and private partial cleanup`() = + runTest { + // Given + val selection = BackupSelection(setOf(BackupCategory.PROVIDERS)) + // When + val failure = runCatching { fixture.store.create(selection) {} }.exceptionOrNull() + // Then + assertTrue(failure is IllegalArgumentException) + assertTrue(FileSystem.SYSTEM.list(fixture.root).isEmpty()) + } + + @Test + fun `given no selected categories, create is requested, expected rejection before staging allocation`() = + runTest { + // Given + val selection = BackupSelection(emptySet()) + // When + val failure = runCatching { fixture.store.create(selection) {} }.exceptionOrNull() + // Then + assertTrue(failure is IllegalArgumentException) + verify(exactly = 0) { fixture.files.newId() } + assertTrue(FileSystem.SYSTEM.list(fixture.root).isEmpty()) + } + + @Test + fun `given supported and removed network buckets, snapshot is exported, expected only portable counters`() = + runTest { + // Given + val key = NetworkUsageBucket.entries.first().key + fixture.counters = + listOf(NetworkUsageEntity(key, 100), NetworkUsageEntity("removed", 200)) + // When + val export = fixture.store.create(BackupSelection(setOf(BackupCategory.NETWORK))) {} + val staged = fixture.store.staged(export.handle) + val text = fixture.codec.openSection(staged.path, staged.manifest, "network") + .use(fixture.codec::readJson) + // Then + assertEquals("{\"$key\":100}", text) + assertEquals(1L, staged.manifest.sections.single().itemCount) + } + + @Test + fun `given invalid negative saved counter, backup is created, expected failure and no remaining partial files`() = + runTest { + // Given + fixture.counters = + listOf(NetworkUsageEntity(NetworkUsageBucket.entries.first().key, -1)) + // When + val failure = + runCatching { fixture.store.create(BackupSelection(setOf(BackupCategory.NETWORK))) {} }.exceptionOrNull() + // Then + assertTrue(failure is IllegalArgumentException) + assertTrue(FileSystem.SYSTEM.list(fixture.root).isEmpty()) + } + + @Test + fun `given snapshot read cancellation, backup creation is interrupted, expected original cancellation and partial cleanup`() = + runTest { + // Given + val cancellation = CancellationException("canceled snapshot") + coEvery { fixture.database.readSnapshot(any()) } throws cancellation + // When + val failure = + runCatching { fixture.store.create(BackupSelection(setOf(BackupCategory.SETTINGS))) {} }.exceptionOrNull() + // Then + assertSame(cancellation, failure) + assertTrue(FileSystem.SYSTEM.list(fixture.root).isEmpty()) + } + + @Test + fun `given inventory with no gallery or network, selectable entries are loaded, expected zero categories disabled and no secrets read`() = + runTest { + // Given + fixture.snapshot = fixture.snapshot.copy(providers = mapOf("removed" to emptyMap())) + // When + val inventory = fixture.store.inventory() + // Then + assertTrue(inventory.providers.isEmpty()) + assertEquals( + setOf(BackupCategory.SETTINGS), + inventory.entries.filter { it.isAvailable }.map { it.category }.toSet() + ) + coVerify(exactly = 0) { fixture.authorization.getAuthorizationCredentials() } + } + + @Test + fun `given sparse gallery identities, selected gallery is exported, expected every row and metadata in stable order`() = + runTest { + // Given + val earlier = fixture.row(5).copy( + prompt = "first image", seed = "5", generationType = "img2img", + originalImageBase64 = "iVBORw0KGgoAAAAB", + ) + val later = fixture.row(71).copy(prompt = "second image", seed = "71") + fixture.rows = listOf(later, earlier) + val progress = mutableListOf() + // When + val export = + fixture.store.create(BackupSelection(setOf(BackupCategory.GALLERY))) { progress += it.completed } + val staged = fixture.store.staged(export.handle) + val restored = + fixture.codec.openSection(staged.path, staged.manifest, "gallery").use { source -> + List(2) { fixture.galleryCodec.read(source, "new-revision") } + } + // Then + assertEquals(listOf(1L, 2L), progress) + assertEquals(2L, staged.manifest.sections.single().itemCount) + assertEquals( + listOf( + earlier.copy(id = 0, imageRevision = "new-revision"), + later.copy(id = 0, imageRevision = "new-revision") + ), restored + ) + } + + @Test + fun `given gallery backup in progress, user cancels after first image, expected partial archive removed and gallery unchanged`() = + runTest { + // Given + fixture.rows = listOf(fixture.row(5), fixture.row(71)) + val cancellation = CancellationException("cancel gallery copy") + // When + val failure = + runCatching { fixture.store.create(BackupSelection(setOf(BackupCategory.GALLERY))) { throw cancellation } }.exceptionOrNull() + // Then + assertSame(cancellation, failure) + assertTrue(FileSystem.SYSTEM.list(fixture.root).isEmpty()) + assertEquals(listOf(5L, 71L), fixture.rows.map { it.id }) + } +} diff --git a/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/archive/BackupArchiveFixture.kt b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/archive/BackupArchiveFixture.kt new file mode 100644 index 000000000..7a9cbf285 --- /dev/null +++ b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/archive/BackupArchiveFixture.kt @@ -0,0 +1,174 @@ +package com.shifthackz.aisdv1.feature.backup.archive + +import com.shifthackz.aisdv1.core.common.appbuild.BuildInfoProvider +import com.shifthackz.aisdv1.core.common.time.TimeProvider +import com.shifthackz.aisdv1.domain.entity.backup.BackupPreferences +import com.shifthackz.aisdv1.domain.entity.backup.BackupValue +import com.shifthackz.aisdv1.domain.entity.backup.BackupImageBudget +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationCredentials +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationStore +import com.shifthackz.aisdv1.domain.gateway.ProviderSelectionGuard +import com.shifthackz.aisdv1.domain.gateway.backup.BackupPreferencesGateway +import com.shifthackz.aisdv1.domain.gateway.backup.BackupImageValidator +import com.shifthackz.aisdv1.feature.backup.codec.BinaryBackupArchiveCodec +import com.shifthackz.aisdv1.feature.backup.codec.BackupManifest +import com.shifthackz.aisdv1.feature.backup.codec.BackupSection +import com.shifthackz.aisdv1.feature.backup.codec.DefaultBackupPreferencesCodec +import com.shifthackz.aisdv1.feature.backup.codec.DefaultGalleryBackupCodec +import com.shifthackz.aisdv1.feature.backup.io.BackupFileStore +import com.shifthackz.aisdv1.storage.db.persistent.dao.GenerationResultDao +import com.shifthackz.aisdv1.storage.db.persistent.dao.NetworkUsageDao +import com.shifthackz.aisdv1.storage.db.persistent.entity.GenerationResultEntity +import com.shifthackz.aisdv1.storage.db.persistent.entity.NetworkUsageEntity +import com.shifthackz.aisdv1.storage.gateway.BackupStorage +import io.mockk.coEvery +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.flow.flowOf +import kotlinx.serialization.json.Json +import okio.FileSystem +import okio.Path +import okio.Path.Companion.toPath +import okio.buffer + +/** + * Exercises real archive framing, codecs and private files with isolated persistence/transport collaborators. + * @param root Private temporary directory owned by one unit-test case. + * @author Dmitriy Moroz + */ +internal class BackupArchiveFixture(val root: Path) { + val json = Json { encodeDefaults = true; ignoreUnknownKeys = true } + val codec = BinaryBackupArchiveCodec(json) + val fields = DefaultBackupPreferencesCodec(json) + val preferences = mockk() + val authorization = mockk() + val images = mockk() + val network = mockk() + val database = mockk() + val staging = mockk(relaxed = true) + val files = mockk() + var snapshot = BackupPreferences(emptyMap(), mapOf("autoSave" to BackupValue.Flag(true))) + var rows = emptyList() + var counters = emptyList() + var displayName = "selected.sdaibackup" + var location = "/Downloads/selected.sdaibackup" + private var nextId = 1 + + init { + FileSystem.SYSTEM.createDirectories(root) + every { files.root } returns root + every { files.newId() } answers { + "00000000-0000-0000-0000-${ + (nextId++).toString().padStart(12, '0') + }" + } + every { files.documentReference(any()) } answers { "file://${firstArg()}" } + every { files.documentPath(any()) } answers { + firstArg().removePrefix("file://").toPath() + } + every { files.documentName(any()) } answers { displayName } + every { files.documentLocation(any()) } answers { location } + every { files.openDocument(any()) } answers { + FileSystem.SYSTEM.source( + firstArg().removePrefix( + "file://" + ).toPath() + ).buffer() + } + every { files.writeDocument(any()) } answers { + FileSystem.SYSTEM.sink( + firstArg().removePrefix( + "file://" + ).toPath() + ).buffer() + } + every { files.availableBytes() } returns Long.MAX_VALUE + every { preferences.read() } answers { snapshot } + every { preferences.filterSupported(any()) } answers { firstArg() } + coEvery { authorization.getAuthorizationCredentials() } returns AuthorizationCredentials.None + every { database.generationResultDao() } returns images + every { database.networkUsageDao() } returns network + coEvery { database.readSnapshot(any()) } coAnswers { firstArg Unit>()() } + every { images.observeCount() } answers { flowOf(rows.size) } + coEvery { + images.queryBackupPage( + any(), + any() + ) + } answers { rows.filter { it.id > firstArg() }.sortedBy { it.id }.take(secondArg()) } + coEvery { network.query() } answers { counters } + } + + val galleryCodec = DefaultGalleryBackupCodec( + codec, + json, + mockk(relaxed = true), + BackupImageBudget(1024, 100, 4096, 16) + ) + val store = DefaultBackupArchiveStore( + files, + codec, + galleryCodec, + fields, + database, + preferences, + authorization, + ProviderSelectionGuard(), + BuildInfoProvider.stub, + mockk { every { currentTimeMillis() } returns 123L }, + json, + staging, + ) + + /** + * Creates a checksum-valid archive with one framed JSON section for compatibility/admission cases. + * @param id Stable or future section identifier. + * @param text JSON payload consumed by the section codec. + * @param transform Descriptor mutation for versions or record-count mismatches. + * @author Dmitriy Moroz + */ + suspend fun document( + id: String, + text: String, + transform: (BackupSection) -> BackupSection = { it }, + ): String { + val payload = root.parent!! / "payload" + FileSystem.SYSTEM.sink(payload).buffer().use { codec.writeJson(it, text) } + val section = transform(codec.describe(payload, id, 1)) + val document = root.parent!! / "source.sdaibackup" + codec.write( + document, + BackupManifest("snapshot", 123, "1", "IOS", listOf(section)), + listOf(payload) + ) + return "file://$document" + } + + /** + * Supplies portable gallery metadata; native image validation is isolated by the fixture collaborator. + * @param id Existing row identity, deliberately excluded by the portable codec. + * @author Dmitriy Moroz + */ + fun row(id: Long) = GenerationResultEntity( + id, "iVBORw0KGgoAAAAA", "", 100, "txt2img", "prompt", "negative", 1, 1, 0, 7.5f, + false, "Euler", "42", "9", 0.25f, 0.5f, true, true, "model", "old-revision", + ) + + /** + * Writes one valid gallery record while allowing an inconsistent declared count for admission testing. + * @param declaredCount Number of gallery records advertised in the checked manifest. + * @author Dmitriy Moroz + */ + suspend fun galleryDocument(declaredCount: Long): String { + val payload = root.parent!! / "gallery-payload" + FileSystem.SYSTEM.sink(payload).buffer().use { galleryCodec.write(it, row(71)) } + val section = codec.describe(payload, "gallery", declaredCount) + val document = root.parent!! / "gallery-source.sdaibackup" + codec.write( + document, + BackupManifest("snapshot", 123, "1", "IOS", listOf(section)), + listOf(payload) + ) + return "file://$document" + } +} diff --git a/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/archive/BackupArchiveInspectionTest.kt b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/archive/BackupArchiveInspectionTest.kt new file mode 100644 index 000000000..bec444c5c --- /dev/null +++ b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/archive/BackupArchiveInspectionTest.kt @@ -0,0 +1,246 @@ +package com.shifthackz.aisdv1.feature.backup.archive + +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.entity.backup.BackupPreferences +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection +import com.shifthackz.aisdv1.domain.entity.backup.BackupValue +import io.mockk.every +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.test.runTest +import okio.FileSystem +import okio.Path.Companion.toPath +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class BackupArchiveInspectionTest { + @get:Rule + val temporary = TemporaryFolder() + private lateinit var fixture: BackupArchiveFixture + + @Before + fun setup() { + fixture = BackupArchiveFixture(temporary.newFolder("private").absolutePath.toPath()) + } + + @Test + fun `given selected backup, inspection completes, expected private immutable copy and source details retained`() = + runTest { + // Given + val source = + fixture.document("settings", fixture.fields.encode(fixture.snapshot.settings)) + val progress = mutableListOf() + // When + val inspection = fixture.store.inspect(source) { progress += it.completed } + val staged = fixture.store.staged(inspection.handle) + // Then + assertEquals("selected.sdaibackup", inspection.filename) + assertEquals(fixture.location, inspection.sourceLocation) + assertEquals( + setOf(BackupCategory.SETTINGS), + inspection.entries.filter { it.isAvailable }.map { it.category }.toSet() + ) + assertTrue( + staged.path.toFile().readBytes() + .contentEquals(source.removePrefix("file://").toPath().toFile().readBytes()) + ) + assertTrue(progress.last() > 0) + assertEquals(0, inspection.skippedCount) + } + + @Test + fun `given long document labels, backup is selected, expected bounded persisted name and location`() = + runTest { + // Given + fixture.displayName = "n".repeat(600) + fixture.location = "p".repeat(3000) + val source = fixture.document("settings", "{}") + // When + val inspection = fixture.store.inspect(source) {} + // Then + assertEquals(512, inspection.filename.length) + assertEquals(2048, inspection.sourceLocation.length) + } + + @Test + fun `given old staged archive without display metadata, summary is recovered, expected safe fallback labels`() = + runTest { + // Given + val export = fixture.store.create(BackupSelection(setOf(BackupCategory.SETTINGS))) {} + // When + val inspection = fixture.store.summary(fixture.store.staged(export.handle)) + // Then + assertEquals("SDAI.sdaibackup", inspection.filename) + assertEquals("", inspection.sourceLocation) + } + + @Test + fun `given newer unknown section, compatible container is inspected, expected section skipped without decoding`() = + runTest { + // Given + val source = fixture.document("future_feature", "not JSON") + // When + val inspection = fixture.store.inspect(source) {} + // Then + assertTrue(inspection.entries.isEmpty()) + assertEquals(1, inspection.skippedCount) + } + + @Test + fun `given gallery requires newer reader, archive is inspected, expected unavailable gallery without reading unsupported payload`() = + runTest { + // Given + val source = + fixture.document("gallery", "future bytes") { it.copy(requiredReaderVersion = 2) } + // When + val inspection = fixture.store.inspect(source) {} + // Then + assertFalse(inspection.entries.single().isAvailable) + assertEquals(1, inspection.skippedCount) + } + + @Test + fun `given network uses future codec, archive is inspected, expected unavailable section without decoding`() = + runTest { + // Given + val source = fixture.document("network", "future bytes") { it.copy(codec = "future") } + // When + val inspection = fixture.store.inspect(source) {} + // Then + assertFalse(inspection.entries.single().isAvailable) + assertEquals(1, inspection.skippedCount) + } + + @Test + fun `given removed provider and field, compatible fields are filtered, expected supported values and skipped count`() = + runTest { + // Given + val source = fixture.document( + "providers", + fixture.fields.encodeProviders( + mapOf( + "custom" to mapOf( + "serverUrl" to BackupValue.Text( + "host" + ), "removed" to BackupValue.Text("old") + ), "future" to mapOf("token" to BackupValue.Text("old")) + ) + ) + ) + every { fixture.preferences.filterSupported(any()) } answers { + val value = firstArg() + value.copy(providers = value.providers.mapValues { (_, fields) -> fields.filterKeys { it == "serverUrl" } }) + } + // When + val inspection = fixture.store.inspect(source) {} + // Then + assertEquals(setOf("custom"), inspection.providers) + assertEquals(2, inspection.skippedCount) + } + + @Test + fun `given unsupported setting, compatibility filter removes it, expected skipped item and disabled empty category`() = + runTest { + // Given + val source = fixture.document( + "settings", + fixture.fields.encode(mapOf("removed" to BackupValue.Flag(true))) + ) + every { fixture.preferences.filterSupported(any()) } returns BackupPreferences( + emptyMap(), + emptyMap() + ) + // When + val inspection = fixture.store.inspect(source) {} + // Then + assertFalse(inspection.entries.single().isAvailable) + assertEquals(2, inspection.skippedCount) + } + + @Test + fun `given insufficient private space, source is selected, expected failure with staging removed and external source preserved`() = + runTest { + // Given + val source = fixture.document("settings", "{}") + every { fixture.files.availableBytes() } returns 1 + // When + val failure = runCatching { fixture.store.inspect(source) {} }.exceptionOrNull() + // Then + assertEquals("Not enough storage for backup", failure?.message) + assertTrue(FileSystem.SYSTEM.list(fixture.root).isEmpty()) + assertTrue(FileSystem.SYSTEM.exists(source.removePrefix("file://").toPath())) + } + + @Test + fun `given document transport error, import starts, expected same failure and no partial staging`() = + runTest { + // Given + val failure = IllegalStateException("document permission expired") + every { fixture.files.openDocument(any()) } throws failure + // When + val caught = + runCatching { fixture.store.inspect("content://provider/document") {} }.exceptionOrNull() + // Then + assertSame(failure, caught) + assertTrue(FileSystem.SYSTEM.list(fixture.root).isEmpty()) + } + + @Test + fun `given import progress cancellation, staging copy is interrupted, expected same cancellation and source preserved`() = + runTest { + // Given + val source = fixture.document("settings", "{}") + val cancellation = CancellationException("user canceled") + // When + val failure = + runCatching { fixture.store.inspect(source) { throw cancellation } }.exceptionOrNull() + // Then + assertSame(cancellation, failure) + assertTrue(FileSystem.SYSTEM.list(fixture.root).isEmpty()) + assertTrue(FileSystem.SYSTEM.exists(source.removePrefix("file://").toPath())) + } + + @Test + fun `given negative network bytes, selected archive is inspected, expected rejection before restoration`() = + runTest { + // Given + val source = fixture.document("network", "{\"inference\":-1}") + // When + val failure = runCatching { fixture.store.inspect(source) {} }.exceptionOrNull() + // Then + assertTrue(failure is IllegalArgumentException) + assertTrue(FileSystem.SYSTEM.list(fixture.root).isEmpty()) + } + + @Test + fun `given gallery record count exceeds payload, archive is inspected, expected rejection and staging cleanup`() = + runTest { + // Given + val source = fixture.galleryDocument(declaredCount = 2) + // When + val failure = runCatching { fixture.store.inspect(source) {} }.exceptionOrNull() + // Then + assertTrue(failure != null) + assertTrue(FileSystem.SYSTEM.list(fixture.root).isEmpty()) + } + + @Test + fun `given valid gallery archive, inspection reads each image, expected progress matches declared count`() = + runTest { + // Given + val source = fixture.galleryDocument(declaredCount = 1) + val validated = mutableListOf() + // When + val inspection = + fixture.store.inspect(source) { if (it.category == BackupCategory.GALLERY) validated += it.completed } + // Then + assertEquals(listOf(1L), validated) + assertEquals(BackupCategory.GALLERY, inspection.entries.single().category) + assertTrue(inspection.entries.single().isAvailable) + } +} diff --git a/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/archive/BackupArchiveTransportTest.kt b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/archive/BackupArchiveTransportTest.kt new file mode 100644 index 000000000..38cc1c2d2 --- /dev/null +++ b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/archive/BackupArchiveTransportTest.kt @@ -0,0 +1,135 @@ +package com.shifthackz.aisdv1.feature.backup.archive + +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection +import io.mockk.every +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.test.runTest +import okio.FileSystem +import okio.Path.Companion.toPath +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class BackupArchiveTransportTest { + @get:Rule + val temporary = TemporaryFolder() + private lateinit var fixture: BackupArchiveFixture + + @Before + fun setup() { + fixture = BackupArchiveFixture(temporary.newFolder("private").absolutePath.toPath()) + } + + @Test + fun `given staged backup, destination is selected, expected exact archive bytes copied and source retained`() = + runTest { + // Given + val export = fixture.store.create(BackupSelection(setOf(BackupCategory.SETTINGS))) {} + val destination = temporary.newFile().toPath() + // When + fixture.store.export(export.document, "file://$destination") + // Then + assertTrue( + destination.toFile().readBytes() + .contentEquals(fixture.files.documentPath(export.document).toFile().readBytes()) + ) + assertEquals(export.handle, fixture.store.staged(export.handle).handle) + } + + @Test + fun `given destination permission failure, export is requested, expected failure propagated and staged source retained`() = + runTest { + // Given + val export = fixture.store.create(BackupSelection(setOf(BackupCategory.SETTINGS))) {} + val failure = IllegalStateException("cannot write destination") + every { fixture.files.writeDocument(any()) } throws failure + // When + val caught = runCatching { + fixture.store.export( + export.document, + "destination" + ) + }.exceptionOrNull() + // Then + assertSame(failure, caught) + assertEquals(export.handle, fixture.store.staged(export.handle).handle) + } + + @Test + fun `given export destination cancellation, copy is requested, expected cancellation propagated and source retained`() = + runTest { + // Given + val export = fixture.store.create(BackupSelection(setOf(BackupCategory.SETTINGS))) {} + val cancellation = CancellationException("canceled") + every { fixture.files.writeDocument(any()) } throws cancellation + // When + val failure = runCatching { + fixture.store.export( + export.document, + "destination" + ) + }.exceptionOrNull() + // Then + assertSame(cancellation, failure) + assertTrue(FileSystem.SYSTEM.exists(fixture.files.documentPath(export.document))) + } + + @Test + fun `given archive outside app staging, export is requested, expected rejection without destination mutation`() = + runTest { + // Given + val external = temporary.newFile("archive.sdaibackup").apply { writeText("external") } + val destination = temporary.newFile().apply { writeText("untouched") } + // When + val failure = runCatching { + fixture.store.export( + "file://${external.absolutePath}", + "file://${destination.absolutePath}" + ) + }.exceptionOrNull() + // Then + assertTrue(failure is IllegalArgumentException) + assertEquals("untouched", destination.readText()) + assertEquals("external", external.readText()) + } + + @Test + fun `given staged backup URL, user discards operation, expected only private staging removed`() = + runTest { + // Given + val export = fixture.store.create(BackupSelection(setOf(BackupCategory.SETTINGS))) {} + val external = temporary.newFile("source").apply { writeText("keep") } + // When + fixture.store.discard(export.document) + // Then + assertTrue(FileSystem.SYSTEM.list(fixture.root).isEmpty()) + assertEquals("keep", external.readText()) + } + + @Test + fun `given invalid traversal handle, staging cleanup is requested, expected external files untouched`() { + // Given + val external = temporary.newFile("source").apply { writeText("keep") } + // When + val failure = runCatching { fixture.store.discard("../source") }.exceptionOrNull() + // Then + assertTrue(failure is IllegalArgumentException) + assertEquals("keep", external.readText()) + } + + @Test + fun `given missing staged archive, pending export is recovered, expected explicit failure`() { + // Given + val handle = "00000000-0000-0000-0000-000000000099" + // When + val failure = + runCatching { fixture.store.preparedExport(handle, "backup") }.exceptionOrNull() + // Then + assertEquals("Pending backup source is unavailable", failure?.message) + } +} diff --git a/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/archive/DefaultBackupStagingCleanerTest.kt b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/archive/DefaultBackupStagingCleanerTest.kt new file mode 100644 index 000000000..77dd9e9b8 --- /dev/null +++ b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/archive/DefaultBackupStagingCleanerTest.kt @@ -0,0 +1,216 @@ +package com.shifthackz.aisdv1.feature.backup.archive + +import com.shifthackz.aisdv1.feature.backup.io.BackupFileStore +import com.shifthackz.aisdv1.domain.gateway.backup.BackupExportStateStore +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportIntent +import com.shifthackz.aisdv1.storage.db.persistent.dao.RestoreSessionDao +import com.shifthackz.aisdv1.storage.db.persistent.entity.RestoreSessionEntity +import com.shifthackz.aisdv1.storage.gateway.BackupStorage +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import okio.FileSystem +import okio.Path +import okio.Path.Companion.toPath +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 +import java.nio.file.Files + +@OptIn(ExperimentalCoroutinesApi::class) +class DefaultBackupStagingCleanerTest { + @get:Rule + val temporary = TemporaryFolder() + + private val files = mockk() + private val database = mockk() + private val exports = mockk(relaxed = true) + private val ledger = mockk() + private lateinit var root: Path + private lateinit var cleaner: BackupStagingCleaner + + @Before + fun setup() { + root = temporary.newFolder("backup").absolutePath.toPath() + every { files.root } returns root + every { database.restoreSessionDao() } returns ledger + coEvery { ledger.pending() } returns emptyList() + every { exports.read() } returns null + cleaner = DefaultBackupStagingCleaner(files, database, exports) + } + + private fun staged(handle: String): Path { + val directory = root / handle + FileSystem.SYSTEM.createDirectories(directory) + (directory / "archive.sdaibackup").toFile().writeText("private archive") + return directory + } + + @Test + fun `given previous process staging, startup cleanup runs, expected only unreferenced generated directories removed`() = + runTest { + // Given + val orphan = staged(ORPHAN) + val retained = staged(RETAINED) + val unknown = staged("unrelated-entry") + val external = temporary.newFile("source.sdaibackup").apply { writeText("user source") } + coEvery { ledger.pending() } returns listOf( + RestoreSessionEntity( + "pending", + RETAINED, + "selection" + ) + ) + + // When + cleaner.prepare() + + // Then + assertFalse(FileSystem.SYSTEM.exists(orphan)) + assertTrue(FileSystem.SYSTEM.exists(retained / "archive.sdaibackup")) + assertTrue(FileSystem.SYSTEM.exists(unknown / "archive.sdaibackup")) + assertEquals("user source", external.readText()) + } + + @Test + fun `given staging initialized, later active operation creates files, expected repeated recovery calls never rescan them`() = + runTest { + // Given + cleaner.prepare() + val active = staged(ORPHAN) + + // When + cleaner.prepare() + + // Then + assertTrue(FileSystem.SYSTEM.exists(active / "archive.sdaibackup")) + coVerify(exactly = 1) { ledger.pending() } + } + + @Test + fun `given startup cleanup in progress, concurrent create awaits admission, expected new files created only after cleanup`() = + runTest { + // Given + val old = staged(ORPHAN) + val release = CompletableDeferred() + coEvery { ledger.pending() } coAnswers { + release.await() + emptyList() + } + val startup = async { cleaner.prepare() } + runCurrent() + var hasCreated = false + + // When + val create = async { + cleaner.prepare() + staged(RETAINED) + hasCreated = true + } + runCurrent() + + // Then + assertFalse(hasCreated) + release.complete(Unit) + startup.await() + create.await() + assertFalse(FileSystem.SYSTEM.exists(old)) + assertTrue(FileSystem.SYSTEM.exists(root / RETAINED / "archive.sdaibackup")) + coVerify(exactly = 1) { ledger.pending() } + } + + @Test + fun `given orphan directory contains external symlink, startup cleanup runs, expected linked user source remains untouched`() = + runTest { + // Given + val orphan = staged(ORPHAN) + val external = temporary.newFolder("user-model").apply { + resolve("model.bin").writeText("original model") + } + Files.createSymbolicLink((orphan / "linked-model").toFile().toPath(), external.toPath()) + + // When + cleaner.prepare() + + // Then + assertFalse(FileSystem.SYSTEM.exists(orphan)) + assertEquals("original model", external.resolve("model.bin").readText()) + } + + @Test + fun `given staging root is a symbolic link, startup cleanup runs, expected rejection without external deletion`() = + runTest { + // Given + val external = temporary.newFolder("outside") + val outsideArchive = + external.resolve(ORPHAN).apply { mkdir(); resolve("archive").writeText("keep") } + val link = temporary.root.resolve("linked-backup") + Files.createSymbolicLink(link.toPath(), external.toPath()) + every { files.root } returns link.absolutePath.toPath() + + // When + val failure = try { + cleaner.prepare() + null + } catch (error: IllegalStateException) { + error + } + + // Then + assertTrue(failure != null) + assertEquals("keep", outsideArchive.resolve("archive").readText()) + } + + @Test + fun `given restore ledger is unreadable, startup cleanup fails then retries, expected files retained until ownership can be read`() = + runTest { + // Given + val orphan = staged(ORPHAN) + coEvery { ledger.pending() } throws IllegalStateException("ledger unavailable") + + // When + val failure = try { + cleaner.prepare() + null + } catch (error: IllegalStateException) { + error + } + + // Then + assertTrue(failure != null) + assertTrue(FileSystem.SYSTEM.exists(orphan)) + coEvery { ledger.pending() } returns emptyList() + cleaner.prepare() + assertFalse(FileSystem.SYSTEM.exists(orphan)) + coVerify(exactly = 2) { ledger.pending() } + } + + @Test + fun `given native destination picker owns export, startup cleanup runs, expected pending export source retained`() = + runTest { + // Given + val retained = staged(RETAINED) + val orphan = staged(ORPHAN) + every { exports.read() } returns BackupExportIntent(RETAINED, "backup.sdaibackup") + // When + cleaner.prepare() + // Then + assertTrue(FileSystem.SYSTEM.exists(retained / "archive.sdaibackup")) + assertFalse(FileSystem.SYSTEM.exists(orphan)) + } + + private companion object { + const val ORPHAN = "11111111-1111-1111-1111-111111111111" + const val RETAINED = "22222222-2222-2222-2222-222222222222" + } +} diff --git a/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BackupPreferencesCodecTest.kt b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BackupPreferencesCodecTest.kt new file mode 100644 index 000000000..c43061f44 --- /dev/null +++ b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BackupPreferencesCodecTest.kt @@ -0,0 +1,34 @@ +package com.shifthackz.aisdv1.feature.backup.codec + +import com.shifthackz.aisdv1.domain.entity.backup.BackupValue +import kotlinx.serialization.json.Json +import org.junit.Assert.assertEquals +import org.junit.Test + +class BackupPreferencesCodecTest { + @Test + fun `given future preference shapes, structured and unsupported scalar fields decode, expected rejected identifiers retained for skipped counts`() { + // Given + val codec = DefaultBackupPreferencesCodec(Json) + val text = + """{"known":"value","object":{},"array":[],"fraction":1.5,"large":9223372036854775807,"null":null}""" + // When + val decoded = codec.decode(text) + // Then + assertEquals(6, decoded.size) + assertEquals(BackupValue.Text("value"), decoded["known"]) + assertEquals(5, decoded.values.count { it == BackupValue.Unsupported }) + } + + @Test + fun `given future provider group, provider has unknown structured contract, expected provider retained for skipped accounting`() { + // Given + val codec = DefaultBackupPreferencesCodec(Json) + // When + val decoded = codec.decodeProviders("""{"future":[],"known":{"setting":true}}""") + // Then + assertEquals(2, decoded.size) + assertEquals(BackupValue.Unsupported, decoded.getValue("future").getValue("")) + assertEquals(BackupValue.Flag(true), decoded.getValue("known").getValue("setting")) + } +} diff --git a/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BinaryBackupArchiveCodecTest.kt b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BinaryBackupArchiveCodecTest.kt new file mode 100644 index 000000000..bd84d2df7 --- /dev/null +++ b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BinaryBackupArchiveCodecTest.kt @@ -0,0 +1,158 @@ +package com.shifthackz.aisdv1.feature.backup.codec + +import kotlinx.serialization.json.Json +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.runBlocking +import okio.Path +import okio.Buffer +import okio.FileSystem +import okio.Path.Companion.toPath +import okio.buffer +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class BinaryBackupArchiveCodecTest { + @get:Rule + val temporary = TemporaryFolder() + private val codec = + BinaryBackupArchiveCodec(Json { ignoreUnknownKeys = true; encodeDefaults = true }) + + private suspend fun fixture( + id: String = "settings", + body: String = "portable fields" + ): Pair { + val payload = temporary.newFile().absolutePath.toPath() + FileSystem.SYSTEM.sink(payload).buffer().use { it.writeUtf8(body) } + val section = codec.describe(payload, id, 1) + val manifest = BackupManifest("archive", 100, "1.2.0", "ANDROID", listOf(section)) + val archive = temporary.newFile().absolutePath.toPath() + codec.write(archive, manifest, listOf(payload)) + return archive to manifest + } + + @Test + fun `given binary backup, archive round trips, expected stable manifest and section bytes`() = + runTest { + // Given + val (archive, expected) = fixture() + // When + val actual = codec.inspect(archive) + val body = codec.openSection(archive, actual, "settings").use { it.readUtf8() } + // Then + assertEquals(expected, actual) + assertEquals("portable fields", body) + } + + @Test + fun `given binary backup, payload byte is changed, expected checksum rejection`() = runTest { + // Given + val (archive, _) = fixture() + val bytes = archive.toFile().readBytes() + .also { it[it.lastIndex] = (it.last().toInt() xor 1).toByte() } + archive.toFile().writeBytes(bytes) + // When + val failure = + assertThrows(IllegalArgumentException::class.java) { runBlocking { codec.inspect(archive) } } + // Then + assertEquals("Backup checksum mismatch", failure.message) + } + + @Test + fun `given binary backup, file is truncated, expected rejection before restoration`() = + runTest { + // Given + val (archive, _) = fixture() + archive.toFile().writeBytes(archive.toFile().readBytes().dropLast(1).toByteArray()) + // When + val failure = assertThrows(IllegalArgumentException::class.java) { + runBlocking { + codec.inspect(archive) + } + } + // Then + assertEquals("Invalid section length", failure.message) + } + + @Test + fun `given future backup section, framing is compatible, expected integrity validation without field knowledge`() = + runTest { + // Given + val (archive, expected) = fixture("future_feature") + // When + val actual = codec.inspect(archive) + // Then + assertEquals(expected.sections, actual.sections) + } + + @Test + fun `given binary backup, duplicate section IDs exist, expected rejection`() = runTest { + // Given + val payload = temporary.newFile().absolutePath.toPath() + payload.toFile().writeText("data") + val section = codec.describe(payload, "gallery", 1) + val manifest = BackupManifest("archive", 100, "1", "IOS", listOf(section, section)) + val archive = temporary.newFile().absolutePath.toPath() + codec.write(archive, manifest, listOf(payload, payload)) + // When + val failure = + assertThrows(IllegalArgumentException::class.java) { runBlocking { codec.inspect(archive) } } + // Then + assertEquals("Duplicate backup sections", failure.message) + } + + @Test + fun `given binary backup, unsupported major framing is present, expected rejection`() = + runTest { + // Given + val (archive, _) = fixture() + archive.toFile().writeBytes(archive.toFile().readBytes().also { it[8] = 2 }) + // When + val failure = assertThrows(IllegalArgumentException::class.java) { + runBlocking { + codec.inspect(archive) + } + } + // Then + assertEquals("Unsupported backup container version", failure.message) + } + + @Test + fun `given binary backup, additive minor framing is present, expected compatible read`() = + runTest { + // Given + val (archive, manifest) = fixture() + archive.toFile().writeBytes(archive.toFile().readBytes().also { it[10] = 2 }) + // When + val actual = codec.inspect(archive) + // Then + assertEquals(manifest, actual) + } + + @Test + fun `given binary backup, bytes follow declared sections, expected rejection`() = runTest { + // Given + val (archive, _) = fixture() + archive.toFile().appendBytes(byteArrayOf(1)) + // When + val failure = + assertThrows(IllegalArgumentException::class.java) { runBlocking { codec.inspect(archive) } } + // Then + assertEquals("Unexpected trailing backup data", failure.message) + } + + @Test + fun `given binary section, decoder reaches its boundary, expected adjacent bytes remain inaccessible`() = + runTest { + // Given + val source = Buffer().writeUtf8("firstSECOND") + val section = BoundedBackupSource(source, 5).buffer() + // When + val text = section.readUtf8() + // Then + assertEquals("first", text) + assertEquals("SECOND", source.readUtf8()) + } +} diff --git a/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/codec/GalleryBackupCodecTest.kt b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/codec/GalleryBackupCodecTest.kt new file mode 100644 index 000000000..6829956f3 --- /dev/null +++ b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/codec/GalleryBackupCodecTest.kt @@ -0,0 +1,180 @@ +package com.shifthackz.aisdv1.feature.backup.codec + +import com.shifthackz.aisdv1.domain.gateway.backup.BackupImageValidator +import com.shifthackz.aisdv1.domain.entity.backup.BackupImageBudget +import com.shifthackz.aisdv1.storage.db.persistent.entity.GenerationResultEntity +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import kotlinx.serialization.json.Json +import okio.Buffer +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +class GalleryBackupCodecTest { + private val validator = + mockk { every { this@mockk.invoke(any()) } returns Unit } + private val codec = + DefaultGalleryBackupCodec( + BinaryBackupArchiveCodec(Json { encodeDefaults = true }), + Json { encodeDefaults = true; ignoreUnknownKeys = true }, + validator, + BackupImageBudget(24 * 1024 * 1024, 16_777_216L, 128L * 1024 * 1024, 256) + ) + private val row = GenerationResultEntity( + 17, + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aGXYAAAAASUVORK5CYII=", + "", + 100, + "txt2img", + "prompt", + "negative", + 1, + 1, + 20, + 7.5f, + false, + "Euler", + "42", + "9", + 0.25f, + 0.5f, + true, + true, + "model", + "old revision" + ) + + @Test + fun `given saved gallery row, binary record round trips, expected fresh identity and preserved history flags`() { + // Given + val source = Buffer() + codec.write(source, row) + // When + val imported = codec.read(source, "new revision")!! + // Then + assertEquals(0L, imported.id) + assertEquals("new revision", imported.imageRevision) + assertEquals(row.copy(id = 0, imageRevision = "new revision"), imported) + verify(exactly = 2) { validator(any()) } + } + + @Test + fun `given future generation type, next known gallery record follows, expected unknown row skipped without desynchronizing stream`() { + // Given + val source = Buffer() + codec.write(source, row.copy(generationType = "future")) + codec.write(source, row) + // When + val unknown = codec.read(source, "ignored") + val known = codec.read(source, "new") + // Then + assertNull(unknown) + assertEquals(row.prompt, known?.prompt) + assertEquals(true, source.exhausted()) + } + + @Test + fun `given archived image bytes, native decoder rejects input, expected gallery validation failure`() { + // Given + val source = Buffer() + codec.write(source, row) + every { validator(any()) } throws IllegalArgumentException("Image decoding failed") + // When + val failure = + assertThrows(IllegalArgumentException::class.java) { codec.read(source, "new") } + // Then + assertEquals("Image decoding failed", failure.message) + } + + @Test + fun `given OpenAI compatible gallery row, zero sampling steps round trip, expected saved metadata restored`() { + // Given + val original = row.copy(samplingSteps = 0) + val source = Buffer() + codec.write(source, original) + // When + val restored = codec.read(source, "imported") + // Then + assertEquals(original.copy(id = 0, imageRevision = "imported"), restored) + } + + @Test + fun `given oversized archived image record count, reader reaches image frame, expected rejection before allocating or reading payload`() { + // Given + val source = Buffer() + BinaryBackupArchiveCodec(Json).writeJson(source, "{}") + source.writeIntLe(24 * 1024 * 1024 + 1) + // When + val failure = + assertThrows(IllegalArgumentException::class.java) { codec.read(source, "revision") } + // Then + assertEquals("Backup image exceeds encoded record budget", failure.message) + assertTrue(source.exhausted()) + verify(exactly = 0) { validator(any()) } + } + + @Test + fun `given image bytes exceed a configured export budget, writer encodes row, expected rejection before native validation or image allocation`() { + // Given + val constrained = DefaultGalleryBackupCodec( + BinaryBackupArchiveCodec(Json), Json, validator, + BackupImageBudget(12, 16_777_216, 128L * 1024 * 1024, 256) + ) + // When + val failure = + assertThrows(IllegalArgumentException::class.java) { constrained.write(Buffer(), row) } + // Then + assertEquals("Backup image exceeds encoded record budget", failure.message) + verify(exactly = 0) { validator(any()) } + } + + @Test + fun `given individually admitted output and input images, combined gallery record exceeds budget, expected matching export and import rejection`() { + // Given + val admitted = Buffer().also { codec.write(it, row) } + val metadata = BinaryBackupArchiveCodec(Json).readJson(admitted) + val byteCount = admitted.readIntLe() + val constrained = DefaultGalleryBackupCodec( + BinaryBackupArchiveCodec(Json), Json, validator, + BackupImageBudget(byteCount, 16_777_216, 128L * 1024 * 1024, 256) + ) + val oversizedPair = Buffer() + BinaryBackupArchiveCodec(Json).writeJson(oversizedPair, metadata) + oversizedPair.writeIntLe(byteCount) + oversizedPair.write(admitted.readByteArray(byteCount.toLong())) + oversizedPair.writeIntLe(byteCount) + // When + val exportFailure = assertThrows(IllegalArgumentException::class.java) { + constrained.write( + Buffer(), + row.copy(originalImageBase64 = row.imageBase64) + ) + } + val importFailure = assertThrows(IllegalArgumentException::class.java) { + constrained.read( + oversizedPair, + "revision" + ) + } + // Then + assertEquals("Backup image exceeds encoded record budget", exportFailure.message) + assertEquals(exportFailure.message, importFailure.message) + } + + @Test + fun `given saved alternate Base64 alphabet, backup writer normalizes image bytes, expected equivalent standard image restored`() { + // Given + val alternate = row.imageBase64.replace('/', '_').replace('+', '-') + val source = Buffer() + // When + codec.write(source, row.copy(imageBase64 = alternate)) + val restored = codec.read(source, "imported") + // Then + assertEquals(row.copy(id = 0, imageRevision = "imported"), restored) + } + +} diff --git a/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/export/DefaultBackupExportCoordinatorTest.kt b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/export/DefaultBackupExportCoordinatorTest.kt new file mode 100644 index 000000000..49a527edb --- /dev/null +++ b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/export/DefaultBackupExportCoordinatorTest.kt @@ -0,0 +1,363 @@ +package com.shifthackz.aisdv1.feature.backup.export + +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import com.shifthackz.aisdv1.domain.entity.backup.BackupExport +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportCompletion +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportIntent +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportStatus +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection +import com.shifthackz.aisdv1.domain.gateway.backup.BackupExportStateStore +import com.shifthackz.aisdv1.domain.usecase.backup.ExportBackupUseCase +import com.shifthackz.aisdv1.feature.backup.archive.BackupArchiveStore +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class DefaultBackupExportCoordinatorTest { + private val archives = mockk(relaxed = true) + private val records = mockk(relaxed = true) + private val export = mockk() + private val backup = BackupExport( + "file:///private/staged", + "backup.sdaibackup", + "11111111-1111-1111-1111-111111111111" + ) + private var stored: BackupExportIntent? = null + + private fun TestScope.coordinator(): DefaultBackupExportCoordinator { + every { records.read() } answers { stored } + every { records.write(any()) } answers { stored = firstArg() } + every { records.clear() } answers { stored = null } + every { archives.preparedExport(backup.handle, backup.filename) } returns backup + val dispatcher = StandardTestDispatcher(testScheduler) + return DefaultBackupExportCoordinator( + archives, + records, + export, + mockk { every { io } returns dispatcher }) + } + + @Test + fun `given recreated host, native callback arrives before async recovery, expected complete destination copy bound to staged source`() = + runTest { + // Given + stored = BackupExportIntent(backup.handle, backup.filename) + coEvery { export(backup.document, "destination") } returns Unit + val owner = coordinator() + // When + owner.submit(BackupExportCompletion.DestinationSelected("destination", backup.handle)) + advanceUntilIdle() + // Then + assertEquals(BackupExportStatus.COMPLETE, stored?.status) + assertEquals(backup, owner.observe().value.backup) + coVerify(exactly = 1) { export(backup.document, "destination") } + verify(exactly = 0) { archives.discard(any()) } + owner.close() + } + + @Test + fun `given interrupted destination copy, graph restarts with durable destination, expected idempotent copy resumed and completion recorded`() = + runTest { + // Given + stored = BackupExportIntent( + backup.handle, + backup.filename, + BackupExportStatus.COPYING, + "destination" + ) + coEvery { export(backup.document, "destination") } returns Unit + // When + val owner = coordinator() + advanceUntilIdle() + // Then + assertEquals(BackupExportStatus.COMPLETE, stored?.status) + coVerify(exactly = 1) { export(backup.document, "destination") } + owner.close() + } + + @Test + fun `given pending source, destination copy fails, expected source retained and explicit failure without success`() = + runTest { + // Given + stored = BackupExportIntent(backup.handle, backup.filename) + coEvery { export(any(), any()) } throws IllegalStateException("write failed") + val owner = coordinator() + // When + owner.submit(BackupExportCompletion.DestinationSelected("destination", backup.handle)) + advanceUntilIdle() + // Then + assertEquals(BackupExportStatus.FAILED, stored?.status) + assertEquals(BackupExportStatus.FAILED, owner.observe().value.status) + assertEquals(backup, owner.observe().value.backup) + verify(exactly = 0) { archives.discard(any()); records.clear() } + owner.close() + } + + @Test + fun `given new export owns staging, old native cancellation arrives, expected newer source and association retained`() = + runTest { + // Given + stored = BackupExportIntent(backup.handle, backup.filename) + val owner = coordinator() + // When + owner.submit(BackupExportCompletion.Canceled("old-export")) + advanceUntilIdle() + // Then + assertEquals(backup.handle, stored?.handle) + assertEquals(BackupExportStatus.READY, owner.observe().value.status) + verify(exactly = 0) { records.clear(); archives.discard(any()) } + owner.close() + } + + @Test + fun `given native cancellation, result is queued before another prepare, expected canceled source acknowledged before new source created`() = + runTest { + // Given + stored = BackupExportIntent(backup.handle, backup.filename) + val owner = coordinator() + advanceUntilIdle() + // When + owner.submit(BackupExportCompletion.Canceled(backup.handle)) + // Then + assertEquals(BackupExportStatus.PROCESSING, owner.observe().value.status) + advanceUntilIdle() + assertNull(stored) + assertEquals(BackupExportStatus.NONE, owner.observe().value.status) + verify(exactly = 1) { archives.discard(backup.handle) } + owner.close() + } + + @Test + fun `given active export, screen is disposed while copying, expected graph owns completion and only explicit cancel interrupts copy`() = + runTest { + // Given + stored = BackupExportIntent(backup.handle, backup.filename) + val finish = CompletableDeferred() + coEvery { export(any(), any()) } coAnswers { finish.await() } + val owner = coordinator() + owner.submit(BackupExportCompletion.DestinationSelected("destination", backup.handle)) + runCurrent() + // When + owner.cancel() + advanceUntilIdle() + // Then + assertEquals(BackupExportStatus.CANCELED, stored?.status) + assertEquals(backup, owner.observe().value.backup) + verify(exactly = 0) { archives.discard(any()) } + owner.close() + } + + @Test + fun `given missing export association, native destination result arrives, expected explicit failure without empty saved success`() = + runTest { + // Given + val owner = coordinator() + // When + owner.submit( + BackupExportCompletion.DestinationSelected( + "destination", + "missing-export" + ) + ) + advanceUntilIdle() + // Then + assertEquals(BackupExportStatus.FAILED, owner.observe().value.status) + coVerify(exactly = 0) { export(any(), any()) } + owner.close() + } + + @Test + fun `given complete export record recovered after failed checked write, fresh picker chooses new destination, expected retained bytes copied again`() = + runTest { + // Given + stored = BackupExportIntent( + backup.handle, + backup.filename, + BackupExportStatus.COMPLETE, + "old-destination" + ) + coEvery { export(any(), any()) } returns Unit + val owner = coordinator() + // When + owner.submit( + BackupExportCompletion.DestinationSelected( + "new-destination", + backup.handle + ) + ) + advanceUntilIdle() + // Then + coVerify(exactly = 1) { export(backup.document, "new-destination") } + assertEquals(BackupExportStatus.COMPLETE, stored?.status) + assertEquals("new-destination", stored?.destination) + owner.close() + } + + @Test + fun `given previously completed export, fresh picker truncates same URI, expected exact source bytes copied again`() = + runTest { + // Given + stored = BackupExportIntent( + backup.handle, + backup.filename, + BackupExportStatus.COMPLETE, + "destination" + ) + coEvery { export(any(), any()) } returns Unit + val owner = coordinator() + // When + owner.submit(BackupExportCompletion.DestinationSelected("destination", backup.handle)) + advanceUntilIdle() + // Then + coVerify(exactly = 1) { export(backup.document, "destination") } + assertEquals(BackupExportStatus.COMPLETE, stored?.status) + owner.close() + } + + @Test + fun `given no pending export, preparation runs, expected archive created and durable association before picker`() = + runTest { + // Given + val owner = coordinator() + val selection = BackupSelection(setOf(BackupCategory.SETTINGS)) + coEvery { archives.create(selection, any()) } returns backup + // When + val result = owner.prepare(selection) {} + // Then + assertEquals(backup, result) + assertEquals(BackupExportIntent(backup.handle, backup.filename), stored) + assertEquals(BackupExportStatus.READY, owner.observe().value.status) + coVerify(exactly = 1) { archives.create(selection, any()) } + owner.close() + } + + @Test + fun `given retained pending export, preparation repeats after recreation, expected same source without new archive`() = + runTest { + // Given + stored = BackupExportIntent(backup.handle, backup.filename) + val owner = coordinator() + // When + val result = owner.prepare(BackupSelection(setOf(BackupCategory.SETTINGS))) {} + // Then + assertEquals(backup, result) + coVerify(exactly = 0) { archives.create(any(), any()) } + owner.close() + } + + @Test + fun `given created source, durable association write fails, expected source retained and original error propagated`() = + runTest { + // Given + val owner = coordinator() + advanceUntilIdle() + coEvery { archives.create(any(), any()) } returns backup + val failure = IllegalStateException("checked write failed") + every { records.write(any()) } throws failure + // When + val caught = + runCatching { owner.prepare(BackupSelection(setOf(BackupCategory.SETTINGS))) {} }.exceptionOrNull() + // Then + assertTrue(caught is IllegalStateException) + assertEquals(failure.message, caught?.message) + verify(exactly = 0) { archives.discard(any()); records.clear() } + owner.close() + } + + @Test + fun `given native platform copied archive, completion callback arrives, expected durable success without another copy`() = + runTest { + // Given + stored = BackupExportIntent(backup.handle, backup.filename) + val owner = coordinator() + // When + owner.submit(BackupExportCompletion.NativeCompleted(backup.handle)) + advanceUntilIdle() + // Then + assertEquals(BackupExportStatus.COMPLETE, stored?.status) + assertEquals(BackupExportStatus.COMPLETE, owner.observe().value.status) + coVerify(exactly = 0) { export(any(), any()) } + owner.close() + } + + @Test + fun `given owned source, picker returns blank destination, expected failure and retained source`() = + runTest { + // Given + stored = BackupExportIntent(backup.handle, backup.filename) + val owner = coordinator() + // When + owner.submit(BackupExportCompletion.DestinationSelected(" ", backup.handle)) + advanceUntilIdle() + // Then + assertEquals(BackupExportStatus.FAILED, owner.observe().value.status) + assertEquals(backup.handle, stored?.handle) + coVerify(exactly = 0) { export(any(), any()) } + verify(exactly = 0) { archives.discard(any()) } + owner.close() + } + + @Test + fun `given completed export, stale cancellation for same handle arrives, expected durable success preserved`() = + runTest { + // Given + stored = BackupExportIntent(backup.handle, backup.filename, BackupExportStatus.COMPLETE) + val owner = coordinator() + // When + owner.submit(BackupExportCompletion.Canceled(backup.handle)) + advanceUntilIdle() + // Then + assertEquals(BackupExportStatus.COMPLETE, stored?.status) + assertEquals(BackupExportStatus.COMPLETE, owner.observe().value.status) + verify(exactly = 0) { archives.discard(any()); records.clear() } + owner.close() + } + + @Test + fun `given pending source, checked clear fails during dismissal, expected source preserved for recovery`() = + runTest { + // Given + stored = BackupExportIntent(backup.handle, backup.filename) + val owner = coordinator() + advanceUntilIdle() + val failure = IllegalStateException("clear failed") + every { records.clear() } throws failure + // When + val caught = runCatching { owner.dismiss() }.exceptionOrNull() + // Then + assertTrue(caught is IllegalStateException) + assertEquals(failure.message, caught?.message) + assertEquals(backup.handle, stored?.handle) + verify(exactly = 0) { archives.discard(any()) } + owner.close() + } + + @Test + fun `given durable operation storage unreadable, coordinator initializes, expected visible failure without deleting source`() = + runTest { + // Given + val owner = coordinator() + every { records.recoverPendingWrite() } throws IllegalStateException("untrusted checked state") + // When + advanceUntilIdle() + // Then + assertEquals(BackupExportStatus.FAILED, owner.observe().value.status) + verify(exactly = 0) { records.clear(); archives.discard(any()) } + owner.close() + } +} diff --git a/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupImageFingerprintTest.kt b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupImageFingerprintTest.kt new file mode 100644 index 000000000..37c2118f8 --- /dev/null +++ b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupImageFingerprintTest.kt @@ -0,0 +1,128 @@ +package com.shifthackz.aisdv1.feature.backup.restore + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import kotlin.io.encoding.Base64 +import kotlin.io.encoding.ExperimentalEncodingApi + +@OptIn(ExperimentalEncodingApi::class) +class BackupImageFingerprintTest { + private val fingerprint = DefaultBackupImageFingerprint() + + @Test + fun `given same encoded image, Base64 alphabet whitespace padding and chunk sizes differ, expected identical fingerprint`() = + runTest { + // Given + val text = Base64.encode(byteArrayOf(1, 2, 3, -5, -1)) + val variant = text.trimEnd('=').replace('+', '-').replace('/', '_').chunked(2) + .joinToString(" \n\u2003") + + // When + val expected = identify(text, 65536) + val actual = identify(variant, 1) + + // Then + assertTrue(expected != null) + assertEquals(expected, actual) + } + + @Test + fun `given image content changes by one byte, fingerprints are read in bounded chunks, expected different identity`() = + runTest { + // Given + val first = Base64.encode(ByteArray(200000) { (it % 251).toByte() }) + val second = Base64.encode(ByteArray(200000) { ((it + 1) % 251).toByte() }) + + // When + val firstHash = identify(first, 65536) + val secondHash = identify(second, 7) + + // Then + assertNotEquals(firstHash, secondHash) + } + + @Test + fun `given malformed saved Base64, padding appears before trailing content, expected no identity`() = + runTest { + // Given + val text = "AQ==AQ==" + + // When + val identity = identify(text, 3) + + // Then + assertNull(identity) + } + + @Test + fun `given saved image is absent or empty, duplicate scan requests its content, expected no identity`() = + runTest { + // Given + val empty = " \n\t" + + // When + val missing = fingerprint { _, _ -> null } + val blank = identify(empty, 1) + + // Then + assertNull(missing) + assertNull(blank) + } + + @Test + fun `given duplicate scan source fails, content reader raises storage error, expected failure propagated`() = + runTest { + // Given + val failure = IllegalStateException("storage unavailable") + var caught: Throwable? = null + + // When + try { + fingerprint { _, _ -> throw failure } + } catch (error: IllegalStateException) { + caught = error + } + + // Then + assertEquals(failure, caught) + } + + @Test + fun `given duplicate scan is canceled, reader propagates cancellation, expected cancellation retained`() = + runTest { + // Given + val failure = CancellationException("cancel") + var caught: Throwable? = null + + // When + try { + fingerprint { _, _ -> throw failure } + } catch (error: CancellationException) { + caught = error + } + + // Then + assertEquals(failure, caught) + } + + /** + * Feeds text at controlled boundaries to exercise Base64 groups and multibyte UTF8 whitespace split across reads. + * @param text Encoded image text, including supported presentation whitespace. + * @param chunkSize Maximum UTF8 bytes returned per read, never exceeding the production request. + * @author Dmitriy Moroz + */ + private suspend fun identify(text: String, chunkSize: Int): String? { + val bytes = text.encodeToByteArray() + return fingerprint { offset, maxBytes -> + if (offset >= bytes.size) byteArrayOf() else bytes.copyOfRange( + offset.toInt(), + minOf(offset + minOf(chunkSize, maxBytes), bytes.size.toLong()).toInt() + ) + } + } +} diff --git a/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultBackupProviderPlannerTest.kt b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultBackupProviderPlannerTest.kt new file mode 100644 index 000000000..c17f18caa --- /dev/null +++ b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultBackupProviderPlannerTest.kt @@ -0,0 +1,181 @@ +package com.shifthackz.aisdv1.feature.backup.restore + +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.entity.backup.BackupPreferences +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection +import com.shifthackz.aisdv1.domain.entity.backup.BackupValue +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationCredentials +import com.shifthackz.aisdv1.feature.backup.codec.DefaultBackupPreferencesCodec +import kotlinx.serialization.json.Json +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Test + +class DefaultBackupProviderPlannerTest { + private val planner = DefaultBackupProviderPlanner(DefaultBackupPreferencesCodec(Json)) + private val selection = BackupSelection(setOf(BackupCategory.PROVIDERS), setOf("custom")) + private fun preferences(vararg values: Pair>) = + BackupPreferences(mapOf(*values), emptyMap()) + + private fun text(value: String) = BackupValue.Text(value) + + @Test + fun `given missing provider configuration, backup is selected, expected fill without conflict`() { + // Given + val incoming = preferences("custom" to mapOf("serverUrl" to text("https://server"))) + // When + val plan = planner.plan(preferences(), incoming, selection, AuthorizationCredentials.None) + // Then + assertEquals(incoming.providers, plan.providers) + assertEquals(emptySet(), plan.conflicts) + } + + @Test + fun `given existing saved default, different backup field is selected, expected provider conflict`() { + // Given + val current = preferences("custom" to mapOf("demoMode" to BackupValue.Flag(false))) + val incoming = preferences("custom" to mapOf("demoMode" to BackupValue.Flag(true))) + // When + val plan = planner.plan(current, incoming, selection, AuthorizationCredentials.None) + // Then + assertEquals(setOf("custom"), plan.conflicts) + } + + @Test + fun `given existing provider, backup omits a field, expected omitted field is not replaced`() { + // Given + val current = preferences( + "custom" to mapOf( + "serverUrl" to text("https://server"), + "model" to text("keep") + ) + ) + val incoming = preferences("custom" to mapOf("serverUrl" to text("https://server"))) + // When + val plan = planner.plan(current, incoming, selection, AuthorizationCredentials.None) + // Then + assertEquals(emptySet(), plan.conflicts) + assertEquals(setOf("serverUrl"), plan.providers.getValue("custom").keys) + } + + @Test + fun `given configured unselected provider, backup contains its fields, expected fields remain unselected`() { + // Given + val incoming = preferences("swarm_ui" to mapOf("serverUrl" to text("https://other"))) + // When + val plan = planner.plan(preferences(), incoming, selection, AuthorizationCredentials.None) + // Then + assertEquals(emptyMap>(), plan.providers) + } + + @Test + fun `given shared Basic Auth and unselected SwarmUI, A1111 credentials restore, expected shared credentials skipped`() { + // Given + val current = preferences( + "custom" to mapOf("serverUrl" to text("a")), + "swarm_ui" to mapOf("serverUrl" to text("b")) + ) + val incoming = preferences( + "custom" to mapOf( + "basicLogin" to text("new"), + "basicPassword" to text("new password") + ) + ) + // When + val plan = planner.plan( + current, + incoming, + selection, + AuthorizationCredentials.HttpBasic("old", "old password") + ) + // Then + assertNull(plan.credentials) + assertEquals(2, plan.skippedCount) + assertEquals(setOf("swarm_ui"), plan.retainedCredentialProviders) + assertEquals(emptySet(), plan.conflicts) + } + + @Test + fun `given shared Basic Auth and both providers selected, credentials differ, expected both named conflicts`() { + // Given + val current = preferences( + "custom" to mapOf("serverUrl" to text("a")), + "swarm_ui" to mapOf("serverUrl" to text("b")) + ) + val incoming = preferences( + "custom" to mapOf( + "basicLogin" to text("new"), + "basicPassword" to text("new password") + ) + ) + val all = selection.copy(providers = setOf("custom", "swarm_ui")) + // When + val plan = planner.plan( + current, + incoming, + all, + AuthorizationCredentials.HttpBasic("old", "old password") + ) + // Then + assertEquals(setOf("custom", "swarm_ui"), plan.conflicts) + assertEquals(AuthorizationCredentials.HttpBasic("new", "new password"), plan.credentials) + } + + @Test + fun `given Basic Auth with omitted password, login changes, expected destination password retained`() { + // Given + val incoming = preferences("custom" to mapOf("basicLogin" to text("new"))) + // When + val plan = planner.plan( + preferences(), + incoming, + selection, + AuthorizationCredentials.HttpBasic("old", "keep") + ) + // Then + assertEquals(AuthorizationCredentials.HttpBasic("new", "keep"), plan.credentials) + } + + @Test + fun `given provider conflict consent, destination changes afterward, expected fingerprint changes`() { + // Given + val incoming = preferences("custom" to mapOf("serverUrl" to text("import"))) + val before = planner.plan( + preferences("custom" to mapOf("serverUrl" to text("before"))), + incoming, + selection, + AuthorizationCredentials.None + ) + // When + val after = planner.plan( + preferences("custom" to mapOf("serverUrl" to text("after"))), + incoming, + selection, + AuthorizationCredentials.None + ) + // Then + assertNotEquals(before.fingerprint, after.fingerprint) + } + + @Test + fun `given two contradictory shared credential records, both selected, expected rejection`() { + // Given + val incoming = preferences( + "custom" to mapOf("basicLogin" to text("one")), + "swarm_ui" to mapOf("basicLogin" to text("two")) + ) + // When + val failure = assertThrows(IllegalArgumentException::class.java) { + planner.plan( + preferences(), + incoming, + selection.copy(providers = setOf("custom", "swarm_ui")), + AuthorizationCredentials.None + ) + } + // Then + assertEquals("Conflicting shared Basic Auth records", failure.message) + } +} diff --git a/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultGenerationRestoreGateTest.kt b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultGenerationRestoreGateTest.kt new file mode 100644 index 000000000..29f7010cf --- /dev/null +++ b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultGenerationRestoreGateTest.kt @@ -0,0 +1,86 @@ +package com.shifthackz.aisdv1.feature.backup.restore + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class DefaultGenerationRestoreGateTest { + @Test + fun `given active generation, restore attempts admission, expected rejection without disturbing generation`() = + runTest { + // Given + val gate = DefaultGenerationRestoreGate() + val finish = CompletableDeferred() + val generation = async { gate.generating { finish.await() } } + runCurrent() + // When + val failure = try { + gate.restoring { }; null + } catch (error: IllegalStateException) { + error + } + // Then + assertTrue(failure != null) + assertTrue(generation.isActive) + finish.complete(Unit) + generation.await() + } + + @Test + fun `given concurrent generation requests, both start before restore, expected existing concurrency preserved`() = + runTest { + // Given + val gate = DefaultGenerationRestoreGate() + val finish = CompletableDeferred() + var active = 0 + // When + val first = async { gate.generating { active++; finish.await() } } + val second = async { gate.generating { active++; finish.await() } } + runCurrent() + // Then + assertTrue(active == 2) + finish.complete(Unit) + first.await(); second.await() + } + + @Test + fun `given active restore, generation is submitted, expected dispatch waits until restore completes`() = + runTest { + // Given + val gate = DefaultGenerationRestoreGate() + val finish = CompletableDeferred() + val restoration = async { gate.restoring { finish.await() } } + runCurrent() + var hasDispatched = false + // When + val generation = async { gate.generating { hasDispatched = true } } + runCurrent() + // Then + assertFalse(hasDispatched) + finish.complete(Unit) + restoration.await(); generation.await() + assertTrue(hasDispatched) + } + + @Test + fun `given generation cancellation, its owner exits, expected subsequent restore admitted`() = + runTest { + // Given + val gate = DefaultGenerationRestoreGate() + val waiting = CompletableDeferred() + val generation = async { gate.generating { waiting.await() } } + runCurrent() + // When + generation.cancelAndJoin() + val hasRestored = gate.restoring { true } + // Then + assertTrue(hasRestored) + } +} diff --git a/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/restore/NetworkBackupRestoreWriterTest.kt b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/restore/NetworkBackupRestoreWriterTest.kt new file mode 100644 index 000000000..ce37d4723 --- /dev/null +++ b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/restore/NetworkBackupRestoreWriterTest.kt @@ -0,0 +1,248 @@ +package com.shifthackz.aisdv1.feature.backup.restore + +import com.shifthackz.aisdv1.domain.entity.NetworkUsageBucket +import com.shifthackz.aisdv1.domain.entity.backup.BackupImageBudget +import com.shifthackz.aisdv1.feature.backup.archive.StagedBackup +import com.shifthackz.aisdv1.feature.backup.codec.BackupManifest +import com.shifthackz.aisdv1.feature.backup.codec.BinaryBackupArchiveCodec +import com.shifthackz.aisdv1.storage.db.persistent.dao.NetworkUsageDao +import com.shifthackz.aisdv1.storage.db.persistent.dao.RestoreSessionDao +import com.shifthackz.aisdv1.storage.db.persistent.entity.NetworkUsageEntity +import com.shifthackz.aisdv1.storage.db.persistent.entity.RestoreSectionEntity +import com.shifthackz.aisdv1.storage.gateway.BackupStorage +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json +import okio.FileSystem +import okio.Path.Companion.toPath +import okio.buffer +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class NetworkBackupRestoreWriterTest { + @get:Rule + val temporary = TemporaryFolder() + private val json = Json { encodeDefaults = true } + private val codec = BinaryBackupArchiveCodec(json) + private val database = mockk() + private val network = mockk(relaxed = true) + private val ledger = mockk(relaxed = true) + private val firstBucket = NetworkUsageBucket.entries[0].key + private val secondBucket = NetworkUsageBucket.entries[1].key + private val writer = RoomBackupRestoreWriter( + database, + codec, + mockk(), + mockk(), + json, + DefaultBackupImageFingerprint(), + BackupImageBudget(1024, 100, 4096, 16) + ) + + @Before + fun setup() { + every { database.networkUsageDao() } returns network + every { database.restoreSessionDao() } returns ledger + coEvery { database.writeTransaction(any()) } coAnswers { firstArg Unit>()() } + coEvery { ledger.completed(any()) } returns emptyList() + coEvery { network.query() } returns emptyList() + } + + /** + * Builds real framing around network counters without involving native document transport. + * @param values Incoming typed network buckets, including future bucket names in compatibility cases. + * @param hasTrailingData Whether an extra byte follows the declared JSON record. + * @author Dmitriy Moroz + */ + private suspend fun archive( + values: Map, + hasTrailingData: Boolean = false + ): StagedBackup { + val payload = temporary.newFile().absolutePath.toPath() + FileSystem.SYSTEM.sink(payload).buffer().use { + codec.writeJson(it, json.encodeToString(values)) + if (hasTrailingData) it.writeByte(1) + } + val manifest = BackupManifest( + "snapshot", + 1, + "1", + "ANDROID", + listOf(codec.describe(payload, "network", values.size.toLong())) + ) + val path = temporary.newFile().absolutePath.toPath() + codec.write(path, manifest, listOf(payload)) + return StagedBackup("handle", path, manifest) + } + + @Test + fun `given existing traffic bucket, backup contains additional bytes, expected additive write with category ledger`() = + runTest { + // Given + coEvery { network.query() } returns listOf(NetworkUsageEntity(firstBucket, 100)) + val archive = archive(mapOf(firstBucket to 25, secondBucket to 50)) + // When + writer.network("session", archive) + // Then + coVerify(exactly = 1) { + network.addBytes( + firstBucket, + 25 + ); network.addBytes(secondBucket, 50) + } + coVerify { ledger.mark(RestoreSectionEntity("session", "network", 2, 0)) } + } + + @Test + fun `given future traffic bucket, restore runs, expected unknown bucket skipped and known bytes added`() = + runTest { + // Given + val archive = archive(mapOf(firstBucket to 10, "future" to Long.MAX_VALUE)) + // When + writer.network("session", archive) + // Then + coVerify { + network.addBytes( + firstBucket, + 10 + ); ledger.mark(RestoreSectionEntity("session", "network", 1, 1)) + } + coVerify(exactly = 0) { network.addBytes("future", any()) } + } + + @Test + fun `given committed network category, same session retries, expected no repeated counter writes`() = + runTest { + // Given + val archive = archive(mapOf(firstBucket to 10)) + coEvery { ledger.completed("session") } returns listOf("network") + // When + writer.network("session", archive) + // Then + coVerify(exactly = 0) { + network.query(); network.addBytes( + any(), + any() + ); ledger.mark(any()) + } + } + + @Test + fun `given maximum resulting counter, valid boundary restore runs, expected exact final increment allowed`() = + runTest { + // Given + val archive = archive(mapOf(firstBucket to 1)) + coEvery { network.query() } returns listOf( + NetworkUsageEntity( + firstBucket, + Long.MAX_VALUE - 1 + ) + ) + // When + writer.network("session", archive) + // Then + coVerify { network.addBytes(firstBucket, 1); ledger.mark(any()) } + } + + @Test + fun `given individual counter overflow, restore runs, expected rejection before any counter or ledger write`() = + runTest { + // Given + val archive = archive(mapOf(firstBucket to 1)) + coEvery { network.query() } returns listOf( + NetworkUsageEntity( + firstBucket, + Long.MAX_VALUE + ) + ) + // When + val failure = runCatching { writer.network("session", archive) }.exceptionOrNull() + // Then + assertEquals("Network counter overflow", failure?.message) + coVerify(exactly = 0) { network.addBytes(any(), any()); ledger.mark(any()) } + } + + @Test + fun `given aggregate overflow across valid buckets, restore runs, expected rejection before first write`() = + runTest { + // Given + val archive = archive(mapOf(secondBucket to 1)) + coEvery { network.query() } returns listOf( + NetworkUsageEntity( + firstBucket, + Long.MAX_VALUE + ) + ) + // When + val failure = runCatching { writer.network("session", archive) }.exceptionOrNull() + // Then + assertEquals("Network total overflow", failure?.message) + coVerify(exactly = 0) { network.addBytes(any(), any()); ledger.mark(any()) } + } + + @Test + fun `given negative archived counter, restore runs, expected rejection before transaction mutations`() = + runTest { + // Given + val archive = archive(mapOf(firstBucket to -1)) + // When + val failure = runCatching { writer.network("session", archive) }.exceptionOrNull() + // Then + assertTrue(failure is IllegalArgumentException) + coVerify(exactly = 0) { + database.writeTransaction(any()); network.addBytes( + any(), + any() + ); ledger.mark(any()) + } + } + + @Test + fun `given invalid existing counter, restore runs, expected rejection preserving stored data`() = + runTest { + // Given + val archive = archive(mapOf(firstBucket to 1)) + coEvery { network.query() } returns listOf(NetworkUsageEntity(firstBucket, -1)) + // When + val failure = runCatching { writer.network("session", archive) }.exceptionOrNull() + // Then + assertEquals("Network counter overflow", failure?.message) + coVerify(exactly = 0) { network.addBytes(any(), any()); ledger.mark(any()) } + } + + @Test + fun `given unexpected network payload suffix, restore runs, expected rejection without counter changes`() = + runTest { + // Given + val archive = archive(mapOf(firstBucket to 1), hasTrailingData = true) + // When + val failure = runCatching { writer.network("session", archive) }.exceptionOrNull() + // Then + assertEquals("Invalid network counter", failure?.message) + coVerify(exactly = 0) { network.addBytes(any(), any()); ledger.mark(any()) } + } + + @Test + fun `given network storage cancellation, restore reads current buckets, expected original cancellation and no completion marker`() = + runTest { + // Given + val archive = archive(mapOf(firstBucket to 1)) + val cancellation = CancellationException("storage canceled") + coEvery { network.query() } throws cancellation + // When + val failure = runCatching { writer.network("session", archive) }.exceptionOrNull() + // Then + assertSame(cancellation, failure) + coVerify(exactly = 0) { network.addBytes(any(), any()); ledger.mark(any()) } + } +} diff --git a/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/restore/RoomBackupRestoreWriterTest.kt b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/restore/RoomBackupRestoreWriterTest.kt new file mode 100644 index 000000000..41c5e35c9 --- /dev/null +++ b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/restore/RoomBackupRestoreWriterTest.kt @@ -0,0 +1,383 @@ +package com.shifthackz.aisdv1.feature.backup.restore + +import com.shifthackz.aisdv1.domain.entity.backup.BackupImageBudget +import com.shifthackz.aisdv1.domain.entity.backup.BackupProgress +import com.shifthackz.aisdv1.feature.backup.archive.StagedBackup +import com.shifthackz.aisdv1.feature.backup.codec.BackupArchiveCodec +import com.shifthackz.aisdv1.feature.backup.codec.BackupManifest +import com.shifthackz.aisdv1.feature.backup.codec.BackupSection +import com.shifthackz.aisdv1.feature.backup.codec.GalleryBackupCodec +import com.shifthackz.aisdv1.feature.backup.io.BackupFileStore +import com.shifthackz.aisdv1.storage.db.persistent.dao.GenerationResultDao +import com.shifthackz.aisdv1.storage.db.persistent.entity.GenerationResultEntity +import com.shifthackz.aisdv1.storage.db.persistent.entity.RestoreSectionEntity +import com.shifthackz.aisdv1.storage.db.persistent.dao.RestoreSessionDao +import com.shifthackz.aisdv1.storage.gateway.BackupStorage +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.Json +import okio.Buffer +import okio.Path.Companion.toPath +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class RoomBackupRestoreWriterTest { + private val budget = BackupImageBudget(24 * 1024 * 1024, 16_777_216L, 128L * 1024 * 1024, 256) + private val database = mockk() + private val ledger = mockk(relaxed = true) + private val codec = mockk() + private val gallery = mockk() + private val files = mockk { every { newId() } returns "revision" } + private val savedImages = mockk { + coEvery { queryImageIdsAfter(any(), any()) } returns emptyList() + } + private val archive = StagedBackup( + "handle", + "/private/archive".toPath(), + BackupManifest( + "id", + 1, + "1", + "IOS", + listOf( + BackupSection( + "gallery", + storedBytes = 1, + decodedBytes = 1, + sha256 = "a".repeat(64), + itemCount = 1 + ) + ) + ) + ) + + @Test + fun `given gallery transaction, rows process then commit fails, expected no durable completion progress`() = + runTest { + // Given + every { database.restoreSessionDao() } returns ledger + every { database.generationResultDao() } returns savedImages + coEvery { ledger.completed(any()) } returns emptyList() + every { codec.openSection(any(), any(), any()) } answers { Buffer() } + every { gallery.read(any(), any()) } returns null + coEvery { database.writeTransaction(any()) } coAnswers { + firstArg Unit>()() + throw IllegalStateException("commit failed") + } + val writer = RoomBackupRestoreWriter( + database, + codec, + gallery, + files, + Json, + DefaultBackupImageFingerprint(), + budget + ) + val progress = mutableListOf() + var hasFailed = false + // When + try { + writer.gallery("session", archive, progress::add) + } catch (_: IllegalStateException) { + hasFailed = true + } + // Then + assertTrue(hasFailed) + assertTrue(progress.isEmpty()) + } + + @Test + fun `given gallery transaction, category commit completes, expected progress published after transaction returns`() = + runTest { + // Given + every { database.restoreSessionDao() } returns ledger + every { database.generationResultDao() } returns savedImages + coEvery { ledger.completed(any()) } returns emptyList() + every { codec.openSection(any(), any(), any()) } answers { Buffer() } + every { gallery.read(any(), any()) } returns null + var hasCommitted = false + coEvery { database.writeTransaction(any()) } coAnswers { + firstArg Unit>()() + hasCommitted = true + } + val writer = RoomBackupRestoreWriter( + database, + codec, + gallery, + files, + Json, + DefaultBackupImageFingerprint(), + budget + ) + val progress = mutableListOf() + // When + writer.gallery("session", archive) { assertTrue(hasCommitted); progress += it } + // Then + assertEquals(1, progress.size) + assertEquals(0L, progress.single().completed) + } + + @Test + fun `given existing hidden gallery image, backup has same bytes with different metadata, expected existing row preserved and import skipped`() = + runTest { + // Given + val existing = row("AQIDBA==", id = 71, isHidden = true) + val incoming = + existing.copy(id = 0, prompt = "different prompt", liked = false, hidden = false) + val rows = mutableListOf(existing) + val outcomes = mutableListOf() + configureGallery(rows, outcomes) + every { gallery.read(any(), any()) } returns incoming + val writer = RoomBackupRestoreWriter( + database, + codec, + gallery, + files, + Json, + DefaultBackupImageFingerprint(), + budget + ) + + // When + writer.gallery("fresh-session", archive) {} + + // Then + assertEquals(listOf(existing), rows) + assertEquals(0L, outcomes.single().importedCount) + assertEquals(1L, outcomes.single().skippedCount) + coVerify(exactly = 0) { savedImages.insert(any()) } + } + + @Test + fun `given gallery backup restored once, same backup is restored as new session, expected gallery size unchanged`() = + runTest { + // Given + val rows = mutableListOf() + val outcomes = mutableListOf() + configureGallery(rows, outcomes) + every { gallery.read(any(), any()) } answers { row("AQIDBA==") } + val writer = RoomBackupRestoreWriter( + database, + codec, + gallery, + files, + Json, + DefaultBackupImageFingerprint(), + budget + ) + writer.gallery("first-session", archive) {} + + // When + writer.gallery("second-session", archive) {} + + // Then + assertEquals(1, rows.size) + assertEquals(listOf(1L, 0L), outcomes.map { it.importedCount }) + assertEquals(listOf(0L, 1L), outcomes.map { it.skippedCount }) + coVerify(exactly = 1) { savedImages.insert(any()) } + } + + @Test + fun `given archive contains duplicate outputs, restore reaches later copy, expected one fresh gallery row and one skipped entry`() = + runTest { + // Given + val rows = mutableListOf() + val outcomes = mutableListOf() + configureGallery(rows, outcomes) + every { gallery.read(any(), any()) } returnsMany listOf( + row("AQIDBA=="), + row("AQIDBA==").copy(prompt = "another metadata row") + ) + val doubled = + archive.copy(manifest = archive.manifest.copy(sections = archive.manifest.sections.map { + it.copy(itemCount = 2) + })) + val writer = RoomBackupRestoreWriter( + database, + codec, + gallery, + files, + Json, + DefaultBackupImageFingerprint(), + budget + ) + + // When + writer.gallery("session", doubled) {} + + // Then + assertEquals(1, rows.size) + assertEquals(1L, outcomes.single().importedCount) + assertEquals(1L, outcomes.single().skippedCount) + } + + @Test + fun `given existing gallery, backup contains distinct output bytes, expected new row added beside original`() = + runTest { + // Given + val existing = row("AQIDBA==", id = 71) + val rows = mutableListOf(existing) + val outcomes = mutableListOf() + configureGallery(rows, outcomes) + every { gallery.read(any(), any()) } returns row("AQIDBQ==") + val writer = RoomBackupRestoreWriter( + database, + codec, + gallery, + files, + Json, + DefaultBackupImageFingerprint(), + budget + ) + + // When + writer.gallery("session", archive) {} + + // Then + assertEquals(2, rows.size) + assertEquals(existing, rows.first()) + assertEquals(1L, outcomes.single().importedCount) + assertEquals(0L, outcomes.single().skippedCount) + } + + @Test + fun `given oversized wrapped Base64 representation, backup contains same admissible image, expected fallback detects duplicate`() = + runTest { + // Given + val rows = mutableListOf(row("AQID\nBA==", id = 71)) + val outcomes = mutableListOf() + configureGallery(rows, outcomes) + every { gallery.read(any(), any()) } returns row("AQIDBA==") + val writer = RoomBackupRestoreWriter( + database, codec, gallery, files, Json, + DefaultBackupImageFingerprint(), budget.copy(maxEncodedBytes = 4) + ) + + // When + writer.gallery("session", archive) {} + + // Then + assertEquals(1, rows.size) + assertEquals(0L, outcomes.single().importedCount) + assertEquals(1L, outcomes.single().skippedCount) + coVerify(atLeast = 1) { savedImages.queryImageChunk(71, any(), any()) } + } + + @Test + fun `given gallery spans multiple identity pages, duplicate exists after first page, expected image skipped without altering stored rows`() = + runTest { + // Given + val rows = + (1L..130L).map { id -> row(if (id == 130L) "AQIDBA==" else "AQIDBQ==", id = id) } + .toMutableList() + val original = rows.toList() + val outcomes = mutableListOf() + configureGallery(rows, outcomes) + every { gallery.read(any(), any()) } returns row("AQIDBA==") + val writer = RoomBackupRestoreWriter( + database, + codec, + gallery, + files, + Json, + DefaultBackupImageFingerprint(), + budget + ) + // When + writer.gallery("session", archive) {} + // Then + assertEquals(original, rows) + assertEquals(1L, outcomes.single().skippedCount) + assertEquals(0L, outcomes.single().importedCount) + coVerify { savedImages.queryImageIdsAfter(128, 128) } + coVerify(exactly = 0) { savedImages.insert(any()) } + } + + @Test + fun `given gallery category already committed, session retries, expected no gallery scan or duplicate insertion`() = + runTest { + // Given + val rows = mutableListOf(row("AQIDBA==", id = 71)) + val outcomes = mutableListOf() + configureGallery(rows, outcomes) + coEvery { ledger.completed("session") } returns listOf("gallery") + val writer = RoomBackupRestoreWriter( + database, + codec, + gallery, + files, + Json, + DefaultBackupImageFingerprint(), + budget + ) + val progress = mutableListOf() + // When + writer.gallery("session", archive, progress::add) + // Then + assertEquals(1, rows.size) + assertTrue(outcomes.isEmpty()) + assertTrue(progress.isEmpty()) + coVerify(exactly = 0) { + savedImages.queryImageIdsAfter( + any(), + any() + ); savedImages.insert(any()); ledger.mark(any()) + } + } + + /** + * Supplies the production writer with a paged image store and an observed commit ledger. + * @param rows Mutable persisted rows; fresh insert identities are assigned independently of the archive. + * @param outcomes Committed category reports recorded by the fake transaction boundary. + * @author Dmitriy Moroz + */ + private fun configureGallery( + rows: MutableList, + outcomes: MutableList + ) { + every { database.restoreSessionDao() } returns ledger + every { database.generationResultDao() } returns savedImages + coEvery { ledger.completed(any()) } returns emptyList() + coEvery { ledger.mark(any()) } answers { outcomes += firstArg() } + every { codec.openSection(any(), any(), any()) } answers { Buffer() } + coEvery { database.writeTransaction(any()) } coAnswers { firstArg Unit>()() } + coEvery { savedImages.queryImageIdsAfter(any(), any()) } answers { + val afterId = firstArg() + rows.filter { it.id > afterId }.sortedBy { it.id }.take(secondArg()).map { it.id } + } + coEvery { savedImages.queryImageTextForFingerprint(any(), any()) } answers { + rows.single { it.id == firstArg() }.imageBase64.takeIf { it.encodeToByteArray().size <= secondArg() } + } + coEvery { savedImages.queryImageChunk(any(), any(), any()) } answers { + val text = rows.single { it.id == firstArg() }.imageBase64.encodeToByteArray() + val start = secondArg().toInt() - 1 + if (start >= text.size) byteArrayOf() else text.copyOfRange( + start, + minOf(text.size, start + thirdArg()) + ) + } + coEvery { savedImages.insert(any()) } answers { + rows += firstArg().copy(id = (rows.maxOfOrNull { it.id } + ?: 0) + 1) + rows.last().id + } + } + + /** + * Builds gallery rows with different output-byte identities while keeping generation metadata usable. + * @param image Output Base64 content used by the duplicate-checking unit under test. + * @param id Existing identity, or zero for an archive-decoded row. + * @param isHidden Whether the existing image belongs only to generation history. + * @author Dmitriy Moroz + */ + private fun row(image: String, id: Long = 0, isHidden: Boolean = false) = + GenerationResultEntity( + id, image, "", 100, "txt2img", "prompt", "negative", 1, 1, 20, 7.5f, + false, "Euler", "42", "9", 0.25f, 0.5f, isHidden, true, "model", "revision", + ) + +} diff --git a/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/DiscardBackupUseCaseImplTest.kt b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/DiscardBackupUseCaseImplTest.kt new file mode 100644 index 000000000..9a14627b8 --- /dev/null +++ b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/DiscardBackupUseCaseImplTest.kt @@ -0,0 +1,121 @@ +package com.shifthackz.aisdv1.feature.backup.usecase + +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationStore +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationCredentials +import com.shifthackz.aisdv1.domain.gateway.ProviderSelectionGuard +import com.shifthackz.aisdv1.domain.gateway.backup.BackupChangesGateway +import com.shifthackz.aisdv1.domain.gateway.backup.BackupPreferencesGateway +import com.shifthackz.aisdv1.domain.preference.ConfigurationStore +import com.shifthackz.aisdv1.feature.backup.archive.BackupArchiveStore +import com.shifthackz.aisdv1.feature.backup.restore.DefaultBackupRestoreGuard +import com.shifthackz.aisdv1.feature.backup.restore.DefaultBackupSessionCodec +import com.shifthackz.aisdv1.storage.db.persistent.dao.RestoreSessionDao +import com.shifthackz.aisdv1.storage.db.persistent.entity.RestoreSessionEntity +import com.shifthackz.aisdv1.storage.gateway.BackupStorage +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.coVerifyOrder +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.Json +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class DiscardBackupUseCaseImplTest { + private val archives = mockk(relaxed = true) + private val database = mockk() + private val ledger = mockk(relaxed = true) + private val preferences = mockk(relaxed = true) + private val configuration = mockk(relaxed = true) + private val authorization = mockk(relaxed = true) + private val changes = mockk(relaxed = true) + private val sessions = DefaultBackupSessionCodec(Json) + private val useCase = DiscardBackupUseCaseImpl( + archives, + database, + preferences, + configuration, + authorization, + ProviderSelectionGuard(), + DefaultBackupRestoreGuard(), + mockk { every { io } returns Dispatchers.Unconfined }, + sessions, + changes + ) + + private fun pending(category: BackupCategory) { + every { database.restoreSessionDao() } returns ledger + coEvery { ledger.pending() } returns listOf( + RestoreSessionEntity( + "session", + "handle", + sessions.encode(BackupSelection(setOf(category))) + ) + ) + } + + @Test + fun `given quarantined settings without ledger marker, user abandons restore, expected recovered settings published before abandonment completes`() = + runTest { + // Given + pending(BackupCategory.SETTINGS) + every { preferences.recoverPendingWrite() } returns setOf(BackupCategory.SETTINGS) + var hasReconciled = false + var hasNotified = false + coEvery { authorization.getAuthorizationCredentials() } coAnswers { + hasReconciled = true; AuthorizationCredentials.None + } + coEvery { changes.notifyChanged(setOf(BackupCategory.SETTINGS)) } coAnswers { + assertTrue( + hasReconciled + ); hasNotified = true + } + coEvery { ledger.finish("session") } coAnswers { assertTrue(hasNotified) } + // When + useCase("handle") + // Then + coVerifyOrder { + preferences.recoverPendingWrite(); authorization.getAuthorizationCredentials(); changes.notifyChanged( + setOf(BackupCategory.SETTINGS) + ); ledger.finish("session"); archives.discard("handle") + } + } + + @Test + fun `given provider association replay without ordinary field changes, user abandons restore, expected provider readers refreshed`() = + runTest { + // Given + pending(BackupCategory.GALLERY) + every { preferences.recoverPendingWrite() } returns setOf(BackupCategory.PROVIDERS) + // When + useCase("handle") + // Then + coVerify { changes.notifyChanged(setOf(BackupCategory.PROVIDERS)) } + } + + @Test + fun `given previously recovered write without marker, notification fails during abandonment, expected recoverable journal and source retained`() = + runTest { + // Given + pending(BackupCategory.SETTINGS) + val failure = IllegalStateException("notify failed") + coEvery { changes.notifyChanged(any()) } throws failure + var caught: Throwable? = null + // When + try { + useCase("handle") + } catch (error: Throwable) { + caught = error + } + // Then + assertEquals(failure.message, caught?.message) + assertTrue(caught is IllegalStateException) + coVerify(exactly = 0) { ledger.finish(any()); archives.discard(any()) } + } +} diff --git a/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/LoadPendingBackupUseCaseImplTest.kt b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/LoadPendingBackupUseCaseImplTest.kt new file mode 100644 index 000000000..e54566f4d --- /dev/null +++ b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/LoadPendingBackupUseCaseImplTest.kt @@ -0,0 +1,138 @@ +package com.shifthackz.aisdv1.feature.backup.usecase + +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationStore +import com.shifthackz.aisdv1.domain.gateway.ProviderSelectionGuard +import com.shifthackz.aisdv1.domain.gateway.backup.BackupChangesGateway +import com.shifthackz.aisdv1.domain.gateway.backup.BackupPreferencesGateway +import com.shifthackz.aisdv1.domain.preference.ConfigurationStore +import com.shifthackz.aisdv1.feature.backup.archive.BackupArchiveStore +import com.shifthackz.aisdv1.feature.backup.archive.BackupStagingCleaner +import com.shifthackz.aisdv1.feature.backup.restore.DefaultBackupSessionCodec +import com.shifthackz.aisdv1.storage.db.persistent.dao.RestoreSessionDao +import com.shifthackz.aisdv1.storage.db.persistent.entity.RestoreSessionEntity +import com.shifthackz.aisdv1.storage.gateway.BackupStorage +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.Json +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +class LoadPendingBackupUseCaseImplTest { + private val database = mockk() + private val ledger = mockk(relaxed = true) + private val preferences = mockk(relaxed = true) + private val changes = mockk(relaxed = true) + private val archives = mockk(relaxed = true) + private val sessions = DefaultBackupSessionCodec(Json) + private var stage = BackupStartupStage.RESTORE + private var pending = RestoreSessionEntity( + "session", + "handle", + sessions.encode(BackupSelection(setOf(BackupCategory.GALLERY))), + requiresConfiguration = true + ) + private val useCase = LoadPendingBackupUseCaseImpl( + database, + preferences, + archives, + sessions, + mockk(relaxed = true), + mockk(relaxed = true), + ProviderSelectionGuard(), + mockk { every { io } returns Dispatchers.Unconfined }, + mockk(relaxed = true), + changes + ) + + @Before + fun setup() { + every { database.restoreSessionDao() } returns ledger + coEvery { ledger.pending() } answers { if (pending.requiresConfiguration) listOf(pending) else emptyList() } + coEvery { ledger.completed(any()) } returns listOf("gallery") + coEvery { ledger.finish(any()) } answers { pending = pending.copy(isComplete = true) } + coEvery { ledger.acknowledgeConfiguration(any()) } answers { + pending = pending.copy(requiresConfiguration = false) + } + every { preferences.readStartupStage() } answers { stage } + every { preferences.writeStartupStage(any()) } answers { stage = firstArg() } + } + + @Test + fun `given first launch last section committed before crash, session finish not recorded, expected configuration handoff without reimport`() = + runTest { + // Given + assertFalse(pending.isComplete) + // When + val recovery = useCase() + // Then + assertNull(recovery) + assertEquals(BackupStartupStage.CONFIGURATION, stage) + assertTrue(pending.isComplete) + assertFalse(pending.requiresConfiguration) + coVerify(exactly = 0) { archives.staged(any()) } + coVerify(exactly = 1) { archives.discard("handle") } + } + + @Test + fun `given completed first launch import, configuration write fails then startup retries, expected completion intent retained until checked acknowledgment`() = + runTest { + // Given + pending = pending.copy(isComplete = true) + every { preferences.writeStartupStage(any()) } throws IllegalStateException("checked write failed") + var hasFailed = false + // When + try { + useCase() + } catch (_: IllegalStateException) { + hasFailed = true + } + // Then + assertTrue(hasFailed) + assertTrue(pending.requiresConfiguration) + coVerify(exactly = 0) { ledger.acknowledgeConfiguration(any()); archives.discard(any()) } + every { preferences.writeStartupStage(any()) } answers { stage = firstArg() } + assertNull(useCase()) + assertEquals(BackupStartupStage.CONFIGURATION, stage) + assertFalse(pending.requiresConfiguration) + coVerify(exactly = 0) { archives.staged(any()) } + } + + @Test + fun `given replayed settings write without ledger marker, pending recovery succeeds, expected retained readers refreshed after association recovery`() = + runTest { + // Given + every { preferences.recoverPendingWrite() } returns setOf(BackupCategory.SETTINGS) + // When + useCase() + // Then + coVerify { changes.notifyChanged(setOf(BackupCategory.SETTINGS)) } + } + + @Test + fun `given setup already complete and restore handoff remains pending, startup recovers committed sections, expected completion acknowledged without stage downgrade`() = + runTest { + // Given + stage = BackupStartupStage.COMPLETE + pending = pending.copy(isComplete = true) + // When + val recovery = useCase() + // Then + assertNull(recovery) + assertEquals(BackupStartupStage.COMPLETE, stage) + assertFalse(pending.requiresConfiguration) + coVerify(exactly = 0) { preferences.writeStartupStage(any()) } + } + +} diff --git a/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/RestoreBackupUseCaseImplTest.kt b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/RestoreBackupUseCaseImplTest.kt new file mode 100644 index 000000000..4e3589ba4 --- /dev/null +++ b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/RestoreBackupUseCaseImplTest.kt @@ -0,0 +1,547 @@ +package com.shifthackz.aisdv1.feature.backup.usecase + +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.entity.backup.BackupEntry +import com.shifthackz.aisdv1.domain.entity.backup.BackupInspection +import com.shifthackz.aisdv1.domain.entity.backup.BackupPreferences +import com.shifthackz.aisdv1.domain.entity.backup.BackupRestoreRequest +import com.shifthackz.aisdv1.domain.entity.backup.BackupRestoreResult +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection +import com.shifthackz.aisdv1.domain.entity.backup.BackupValue +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationStore +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationCredentials +import com.shifthackz.aisdv1.domain.feature.work.BackgroundWorkObserver +import com.shifthackz.aisdv1.domain.gateway.ProviderSelectionGuard +import com.shifthackz.aisdv1.domain.gateway.backup.BackupPreferencesGateway +import com.shifthackz.aisdv1.domain.preference.ConfigurationStore +import com.shifthackz.aisdv1.domain.gateway.GenerationRestoreGate +import com.shifthackz.aisdv1.domain.gateway.backup.BackupChangesGateway +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import com.shifthackz.aisdv1.feature.backup.archive.BackupArchiveStore +import com.shifthackz.aisdv1.feature.backup.archive.StagedBackup +import com.shifthackz.aisdv1.feature.backup.codec.BackupManifest +import com.shifthackz.aisdv1.feature.backup.codec.BackupSection +import com.shifthackz.aisdv1.feature.backup.codec.DefaultBackupPreferencesCodec +import com.shifthackz.aisdv1.feature.backup.restore.DefaultBackupProviderPlanner +import com.shifthackz.aisdv1.feature.backup.restore.DefaultBackupRestoreGuard +import com.shifthackz.aisdv1.feature.backup.restore.DefaultBackupSessionCodec +import com.shifthackz.aisdv1.feature.backup.restore.BackupRestoreWriter +import com.shifthackz.aisdv1.storage.gateway.BackupStorage +import com.shifthackz.aisdv1.storage.db.persistent.dao.RestoreSessionDao +import com.shifthackz.aisdv1.storage.db.persistent.entity.RestoreSessionEntity +import com.shifthackz.aisdv1.storage.db.persistent.entity.RestoreSectionEntity +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import io.mockk.coVerifyOrder +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.Json +import okio.Path.Companion.toPath +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Assert.assertSame +import org.junit.Before +import org.junit.Test + +class RestoreBackupUseCaseImplTest { + private val archives = mockk() + private val preferences = mockk(relaxed = true) + private val configuration = mockk(relaxed = true) + private val authorization = mockk(relaxed = true) + private val writer = mockk() + private val database = mockk() + private val ledger = mockk() + private val work = mockk() + private val changes = mockk(relaxed = true) + private val gate = object : GenerationRestoreGate { + override suspend fun generating(block: suspend () -> T): T = block() + override suspend fun restoring(block: suspend () -> T): T = block() + } + private val sessions = DefaultBackupSessionCodec(Json) + private val committed = mutableListOf() + private val intents = mutableMapOf() + private val request = BackupRestoreRequest( + "11111111-1111-1111-1111-111111111111", + BackupSelection(setOf(BackupCategory.GALLERY, BackupCategory.NETWORK)), + "22222222-2222-2222-2222-222222222222" + ) + private val archive = StagedBackup( + request.handle, + "/private/archive".toPath(), + BackupManifest( + "archive", + 1, + "1", + "IOS", + BackupCategory.entries.map { + BackupSection( + it.key, + storedBytes = 1, + decodedBytes = 1, + sha256 = "a".repeat(64), + itemCount = 1 + ) + }) + ) + private val summary = BackupInspection( + request.handle, + 1, + "1", + "IOS", + BackupCategory.entries.map { BackupEntry(it, 1) }, + setOf("custom") + ) + private val useCase = RestoreBackupUseCaseImpl( + archives, + preferences, + configuration, + authorization, + ProviderSelectionGuard(), + DefaultBackupRestoreGuard(), + DefaultBackupProviderPlanner(DefaultBackupPreferencesCodec(Json)), + writer, + sessions, + database, + work, + changes, + gate, + mockk { every { io } returns Dispatchers.Unconfined }) + + @Before + fun setup() { + every { database.restoreSessionDao() } returns ledger + coEvery { archives.staged(request.handle) } returns archive + every { archives.summary(archive) } returns summary + every { archives.preferences(archive) } returns BackupPreferences(emptyMap(), emptyMap()) + every { preferences.read() } returns BackupPreferences(emptyMap(), emptyMap()) + coEvery { authorization.getAuthorizationCredentials() } returns AuthorizationCredentials.None + every { work.hasActiveTasks() } returns false + coEvery { ledger.get(any()) } answers { intents[firstArg()] } + coEvery { ledger.pending() } answers { intents.values.filter { !it.isComplete } } + coEvery { ledger.completed(any()) } answers { + committed.filter { it.sessionId == firstArg() }.map { it.category } + } + coEvery { ledger.results(any()) } answers { committed.filter { it.sessionId == firstArg() } } + coEvery { ledger.insert(any()) } answers { + val value = firstArg(); intents[value.id] = value + } + coEvery { ledger.mark(any()) } answers { committed += firstArg() } + coEvery { ledger.finish(any()) } answers { + val id = firstArg(); intents[id]?.let { + intents[id] = it.copy(isComplete = true) + }; Unit + } + coEvery { + writer.gallery( + any(), + any(), + any() + ) + } coAnswers { ledger.mark(RestoreSectionEntity(firstArg(), "gallery", 1)) } + coEvery { writer.network(any(), any()) } coAnswers { + ledger.mark( + RestoreSectionEntity( + firstArg(), + "network", + 1 + ) + ) + } + } + + @Test + fun `given gallery restore committed before interruption, same session retries, expected gallery not added twice`() = + runTest { + // Given + intents[request.sessionId] = RestoreSessionEntity( + request.sessionId, + request.handle, + sessions.encode(request.selection) + ) + committed += RestoreSectionEntity(request.sessionId, "gallery", 3) + // When + val result = useCase(request) {} as BackupRestoreResult.Finished + // Then + coVerify(exactly = 0) { writer.gallery(any(), any(), any()) } + coVerify(exactly = 1) { writer.network(request.sessionId, archive) } + assertEquals(3L, result.importedCounts[BackupCategory.GALLERY]) + assertFalse(result.hasFailed) + } + + @Test + fun `given two additive categories, second write fails, expected partial report preserving first commit`() = + runTest { + // Given + coEvery { writer.network(any(), any()) } throws IllegalStateException("storage failure") + // When + val result = useCase(request) {} as BackupRestoreResult.Finished + // Then + assertTrue(result.hasFailed) + assertEquals(setOf(BackupCategory.GALLERY), result.completed) + assertEquals(1L, result.importedCounts[BackupCategory.GALLERY]) + coVerify(exactly = 0) { ledger.finish(any()) } + } + + @Test + fun `given failed second category, user retries same session, expected only failed category applied`() = + runTest { + // Given + coEvery { writer.network(any(), any()) } throws IllegalStateException("storage failure") + useCase(request) {} + coEvery { writer.network(any(), any()) } coAnswers { + ledger.mark( + RestoreSectionEntity( + firstArg(), + "network", + 1 + ) + ) + } + // When + val result = useCase(request) {} as BackupRestoreResult.Finished + // Then + coVerify(exactly = 1) { writer.gallery(any(), any(), any()) } + assertFalse(result.hasFailed) + assertEquals(setOf(BackupCategory.GALLERY, BackupCategory.NETWORK), result.completed) + assertEquals(2, committed.size) + } + + @Test + fun `given gallery only restore, protected auth storage is unreadable, expected no credential access`() = + runTest { + // Given + coEvery { authorization.getAuthorizationCredentials() } throws IllegalStateException("unavailable") + // When + val result = useCase(request) {} as BackupRestoreResult.Finished + // Then + assertFalse(result.hasFailed) + coVerify(exactly = 0) { authorization.getAuthorizationCredentials() } + } + + @Test + fun `given conflicting provider and gallery selected, no consent exists, expected no mutation in any category`() = + runTest { + // Given + every { preferences.read() } returns BackupPreferences( + mapOf( + "custom" to mapOf( + "serverUrl" to BackupValue.Text( + "current" + ) + ) + ), emptyMap() + ) + every { archives.preferences(archive) } returns BackupPreferences( + mapOf( + "custom" to mapOf( + "serverUrl" to BackupValue.Text("incoming") + ) + ), emptyMap() + ) + val selected = request.copy( + selection = BackupSelection( + setOf( + BackupCategory.PROVIDERS, + BackupCategory.GALLERY + ), setOf("custom") + ) + ) + // When + val result = useCase(selected) {} as BackupRestoreResult.Conflict + // Then + assertEquals(setOf("custom"), result.providers) + coVerify(exactly = 0) { ledger.insert(any()); writer.gallery(any(), any(), any()) } + } + + @Test + fun `given completed restore, explicit new session starts, expected category writers evaluate independent request`() = + runTest { + // Given + useCase(request) {} + val repeated = request.copy(sessionId = "33333333-3333-3333-3333-333333333333") + // When + val result = useCase(repeated) {} as BackupRestoreResult.Finished + // Then + coVerify(exactly = 2) { writer.gallery(any(), any(), any()) } + coVerify(exactly = 2) { writer.network(any(), any()) } + assertFalse(result.hasFailed) + assertEquals(4, committed.size) + } + + @Test + fun `given pending provider batch, restore retries on same screen, expected exact batch recovered before auth read`() = + runTest { + // Given + val selected = request.copy( + selection = BackupSelection( + setOf(BackupCategory.PROVIDERS), + setOf("custom") + ) + ) + // When + useCase(selected) {} + // Then + coVerifyOrder { configuration.retryPendingConfiguration(); preferences.recoverPendingWrite(); authorization.getAuthorizationCredentials() } + } + + @Test + fun `given settings committed, next category is canceled, expected cancellation propagated and observers notified`() = + runTest { + // Given + val selected = request.copy( + selection = BackupSelection( + setOf( + BackupCategory.SETTINGS, + BackupCategory.GALLERY + ) + ) + ) + var wasCanceled = false + // When + try { + useCase(selected) { + if (it.category == BackupCategory.GALLERY) throw CancellationException( + "user canceled" + ) + } + } catch (_: CancellationException) { + wasCanceled = true + } + // Then + assertTrue(wasCanceled) + coVerify { changes.notifyChanged(setOf(BackupCategory.SETTINGS)) } + coVerify(exactly = 0) { writer.gallery(any(), any(), any()); ledger.finish(any()) } + } + + @Test + fun `given first launch final section committed, configuration navigation is not acknowledged, expected journal remains recoverable`() = + runTest { + // Given + val selected = request.copy(shouldProceedToConfiguration = true) + // When + useCase(selected) {} + // Then + assertTrue(intents.getValue(request.sessionId).isComplete) + assertTrue(intents.getValue(request.sessionId).requiresConfiguration) + } + + @Test + fun `given committed settings and primary cancellation, observer publication fails, expected original cancellation with suppressed notification failure`() = + runTest { + // Given + val selected = request.copy( + selection = BackupSelection( + setOf( + BackupCategory.SETTINGS, + BackupCategory.GALLERY + ) + ) + ) + val cancellation = CancellationException("cancel") + val notificationFailure = IllegalStateException("notification failed") + coEvery { changes.notifyChanged(any()) } throws notificationFailure + var caught: Throwable? = null + // When + try { + useCase(selected) { if (it.category == BackupCategory.GALLERY) throw cancellation } + } catch (failure: Throwable) { + caught = failure + } + // Then + assertSame(cancellation, caught) + assertEquals( + listOf(notificationFailure.message), + caught?.suppressedExceptions?.map { it.message }) + } + + @Test + fun `given completed restore and no primary failure, observer publication fails, expected failure propagated and retry intent retained`() = + runTest { + // Given + val notificationFailure = IllegalStateException("notification failed") + coEvery { changes.notifyChanged(any()) } throws notificationFailure + var caught: Throwable? = null + // When + try { + useCase(request) {} + } catch (failure: Throwable) { + caught = failure + } + // Then + assertEquals(notificationFailure.message, caught?.message) + assertTrue(caught is IllegalStateException) + coVerify(exactly = 0) { ledger.finish(request.sessionId) } + assertFalse(intents.getValue(request.sessionId).isComplete) + } + + @Test + fun `given invalid session identity, restore is requested, expected rejection before archive access`() = + runTest { + // Given + val invalid = request.copy(sessionId = "../invalid") + // When + val failure = runCatching { useCase(invalid) {} }.exceptionOrNull() + // Then + assertEquals("Invalid restore session", failure?.message) + coVerify(exactly = 0) { archives.staged(any()); ledger.insert(any()) } + } + + @Test + fun `given empty category selection, restore is requested, expected rejection without mutation`() = + runTest { + // Given + val invalid = request.copy(selection = BackupSelection(emptySet())) + // When + val failure = runCatching { useCase(invalid) {} }.exceptionOrNull() + // Then + assertEquals("Select restore data", failure?.message) + coVerify(exactly = 0) { ledger.insert(any()); writer.gallery(any(), any(), any()) } + } + + @Test + fun `given unavailable selected category, restore is requested, expected rejection before intent creation`() = + runTest { + // Given + every { archives.summary(archive) } returns summary.copy(entries = summary.entries.map { + it.copy( + isAvailable = false + ) + }) + // When + val failure = runCatching { useCase(request) {} }.exceptionOrNull() + // Then + assertEquals("Unavailable backup section", failure?.message) + coVerify(exactly = 0) { ledger.insert(any()) } + } + + @Test + fun `given unknown selected provider, restore is requested, expected rejection without preference mutation`() = + runTest { + // Given + val invalid = request.copy( + selection = BackupSelection( + setOf(BackupCategory.PROVIDERS), + setOf("removed") + ) + ) + // When + val failure = runCatching { useCase(invalid) {} }.exceptionOrNull() + // Then + assertEquals("Unavailable backup provider", failure?.message) + coVerify(exactly = 0) { preferences.writeProviders(any(), any()); ledger.insert(any()) } + } + + @Test + fun `given background generation is active, restore is requested, expected failure before writes or journal creation`() = + runTest { + // Given + every { work.hasActiveTasks() } returns true + // When + val failure = runCatching { useCase(request) {} }.exceptionOrNull() + // Then + assertEquals("Wait for generation to finish before restoring", failure?.message) + coVerify(exactly = 0) { + ledger.insert(any()); writer.gallery( + any(), + any(), + any() + ); preferences.writeSettings(any()) + } + } + + @Test + fun `given another pending session, new restore is requested, expected failure preserving original operation`() = + runTest { + // Given + intents["other"] = + RestoreSessionEntity("other", "retained", sessions.encode(request.selection)) + // When + val failure = runCatching { useCase(request) {} }.exceptionOrNull() + // Then + assertEquals("Finish or cancel the pending restore first", failure?.message) + coVerify(exactly = 0) { ledger.insert(any()); writer.gallery(any(), any(), any()) } + assertEquals(setOf("other"), intents.keys) + } + + @Test + fun `given session bound to another archive, restore reuses its identity, expected failure without reapplying data`() = + runTest { + // Given + intents[request.sessionId] = RestoreSessionEntity( + request.sessionId, + "different-handle", + sessions.encode(request.selection) + ) + // When + val failure = runCatching { useCase(request) {} }.exceptionOrNull() + // Then + assertEquals("Restore session belongs to another request", failure?.message) + coVerify(exactly = 0) { + writer.gallery(any(), any(), any()); writer.network( + any(), + any() + ) + } + } + + @Test + fun `given session bound to original selection, retry changes categories, expected rejection before writes`() = + runTest { + // Given + intents[request.sessionId] = RestoreSessionEntity( + request.sessionId, + request.handle, + sessions.encode(request.selection) + ) + val changed = request.copy(selection = BackupSelection(setOf(BackupCategory.SETTINGS))) + // When + val failure = runCatching { useCase(changed) {} }.exceptionOrNull() + // Then + assertEquals("Restore session belongs to another request", failure?.message) + coVerify(exactly = 0) { preferences.writeSettings(any()); ledger.finish(any()) } + } + + @Test + fun `given skipped gallery rows, category commits, expected imported and skipped counts from ledger`() = + runTest { + // Given + coEvery { writer.gallery(any(), any(), any()) } coAnswers { + ledger.mark(RestoreSectionEntity(firstArg(), "gallery", 2, 7)) + } + // When + val result = useCase(request) {} as BackupRestoreResult.Finished + // Then + assertEquals(2L, result.importedCounts[BackupCategory.GALLERY]) + assertEquals(7, result.skippedCount) + assertFalse(result.hasFailed) + coVerify { ledger.finish(request.sessionId) } + } + + @Test + fun `given settings write fails, restore includes gallery, expected partial failure and later categories untouched`() = + runTest { + // Given + val selected = request.copy( + selection = BackupSelection( + setOf( + BackupCategory.SETTINGS, + BackupCategory.GALLERY + ) + ) + ) + coEvery { preferences.writeSettings(any()) } throws IllegalStateException("checked write failed") + // When + val result = useCase(selected) {} as BackupRestoreResult.Finished + // Then + assertTrue(result.hasFailed) + assertTrue(result.completed.isEmpty()) + coVerify(exactly = 0) { writer.gallery(any(), any(), any()); ledger.finish(any()) } + assertFalse(intents.getValue(request.sessionId).isComplete) + } +} diff --git a/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/SetBackupStartupStageUseCaseImplTest.kt b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/SetBackupStartupStageUseCaseImplTest.kt new file mode 100644 index 000000000..3ecc09ffb --- /dev/null +++ b/feature/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/SetBackupStartupStageUseCaseImplTest.kt @@ -0,0 +1,34 @@ +package com.shifthackz.aisdv1.feature.backup.usecase + +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage +import com.shifthackz.aisdv1.domain.gateway.backup.BackupPreferencesGateway +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import org.junit.Test + +class SetBackupStartupStageUseCaseImplTest { + @Test + fun `given setup already complete, stale first launch screen requests configuration, expected durable completion preserved`() { + // Given + val preferences = + mockk(relaxed = true) { every { readStartupStage() } returns BackupStartupStage.COMPLETE } + val useCase = SetBackupStartupStageUseCaseImpl(preferences) + // When + useCase(BackupStartupStage.CONFIGURATION) + // Then + verify(exactly = 0) { preferences.writeStartupStage(any()) } + } + + @Test + fun `given invitation stage, user chooses restore, expected checked forward transition before navigation`() { + // Given + val preferences = + mockk(relaxed = true) { every { readStartupStage() } returns BackupStartupStage.INVITATION } + val useCase = SetBackupStartupStageUseCaseImpl(preferences) + // When + useCase(BackupStartupStage.RESTORE) + // Then + verify(exactly = 1) { preferences.writeStartupStage(BackupStartupStage.RESTORE) } + } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/archive/BackupArchiveStore.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/archive/BackupArchiveStore.kt new file mode 100644 index 000000000..637071461 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/archive/BackupArchiveStore.kt @@ -0,0 +1,79 @@ +package com.shifthackz.aisdv1.feature.backup.archive + +import com.shifthackz.aisdv1.domain.entity.backup.BackupExport +import com.shifthackz.aisdv1.domain.entity.backup.BackupInspection +import com.shifthackz.aisdv1.domain.entity.backup.BackupPreferences +import com.shifthackz.aisdv1.domain.entity.backup.BackupProgress +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection + +/** + * Strict archive operations; restore merge and recovery policy belongs to use-case implementations. + * @author Dmitriy Moroz + */ +internal interface BackupArchiveStore { + /** + * Resolves a retained staged source without persisting platform-specific private paths. + * @param handle Generated app-owned staging directory. + * @param filename Suggested export filename retained by the operation. + * @author Dmitriy Moroz + */ + fun preparedExport(handle: String, filename: String): BackupExport + + /** + * Reads current selectable counts and portable fields without requiring protected credentials. + * @author Dmitriy Moroz + */ + suspend fun inventory(): BackupInspection + + /** + * Captures selected portable settings and a paged gallery/statistics snapshot into private binary staging. + * @param selection Available categories and provider children. + * @param progress Nonsecret work-stage callback; failure never reports an exported file. + * @author Dmitriy Moroz + */ + suspend fun create(selection: BackupSelection, progress: (BackupProgress) -> Unit): BackupExport + + /** + * Stages a selected native document and validates all known payloads before any app-data writes. + * @param document Opaque native source reference; original source is never deleted. + * @param progress Bounded staging and validation progress. + * @author Dmitriy Moroz + */ + suspend fun inspect(document: String, progress: (BackupProgress) -> Unit): BackupInspection + + /** + * Revalidates the binary integrity of an existing private archive for retry or recovery. + * @param handle Generated private archive identity, never an external path. + * @author Dmitriy Moroz + */ + suspend fun staged(handle: String): StagedBackup + + /** + * Reads supported portable fields while ignoring removed providers/fields and retaining omitted values. + * @param archive Integrity-validated staged archive. + * @author Dmitriy Moroz + */ + fun preferences(archive: StagedBackup): BackupPreferences + + /** + * Describes readable sections and skipped data without exposing provider credentials. + * @param archive Validated staged archive and its manifest. + * @author Dmitriy Moroz + */ + fun summary(archive: StagedBackup): BackupInspection + + /** + * Streams complete staged bytes into the selected destination; write failure propagates. + * @param document App-owned staged export reference. + * @param destination Native user-selected output reference. + * @author Dmitriy Moroz + */ + suspend fun export(document: String, destination: String) + + /** + * Deletes only generated app-owned staging; the caller must resolve pending journal intent first. + * @param handle Generated staging identity or its private document reference. + * @author Dmitriy Moroz + */ + fun discard(handle: String) +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/archive/BackupStagingCleaner.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/archive/BackupStagingCleaner.kt new file mode 100644 index 000000000..d0cc7b0fc --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/archive/BackupStagingCleaner.kt @@ -0,0 +1,17 @@ +package com.shifthackz.aisdv1.feature.backup.archive + +/** + * Initializes private staging once per process before any archive operation may create files. + * Journal-owned archives survive cleanup; later calls never rescan files owned by active operations. + * + * @author Dmitriy Moroz + */ +internal interface BackupStagingCleaner { + /** + * Removes generated staging left by a previous process, preserving every pending restore handle. + * Concurrent callers wait for the same initialization; failure propagates without marking it complete. + * + * @author Dmitriy Moroz + */ + suspend fun prepare() +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/archive/DefaultBackupArchiveStore.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/archive/DefaultBackupArchiveStore.kt new file mode 100644 index 000000000..7526c870b --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/archive/DefaultBackupArchiveStore.kt @@ -0,0 +1,420 @@ +package com.shifthackz.aisdv1.feature.backup.archive + +import okio.use +import com.shifthackz.aisdv1.core.common.appbuild.BuildInfoProvider +import com.shifthackz.aisdv1.core.common.time.TimeProvider +import com.shifthackz.aisdv1.domain.entity.ServerSource +import com.shifthackz.aisdv1.domain.entity.NetworkUsageBucket +import com.shifthackz.aisdv1.domain.entity.setupAllowedModes +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.entity.backup.BackupEntry +import com.shifthackz.aisdv1.domain.entity.backup.BackupExport +import com.shifthackz.aisdv1.domain.entity.backup.BackupInspection +import com.shifthackz.aisdv1.domain.entity.backup.BackupPreferences +import com.shifthackz.aisdv1.domain.entity.backup.BackupProgress +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection +import com.shifthackz.aisdv1.domain.entity.backup.BackupValue +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationStore +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationCredentials +import com.shifthackz.aisdv1.domain.gateway.ProviderSelectionGuard +import com.shifthackz.aisdv1.domain.gateway.backup.BackupPreferencesGateway +import com.shifthackz.aisdv1.feature.backup.codec.BackupArchiveCodec +import com.shifthackz.aisdv1.feature.backup.codec.BackupManifest +import com.shifthackz.aisdv1.feature.backup.codec.BackupSection +import com.shifthackz.aisdv1.feature.backup.codec.BackupPreferencesCodec +import com.shifthackz.aisdv1.feature.backup.codec.GalleryBackupCodec +import com.shifthackz.aisdv1.feature.backup.io.BackupFileStore +import com.shifthackz.aisdv1.storage.gateway.BackupStorage +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.flow.first +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json +import okio.Buffer +import okio.FileSystem +import okio.Path +import okio.SYSTEM +import okio.buffer + +/** + * Creates consistent paged snapshots and validates immutable staged files before restore. + * @param files Platform document transport and durable private directory. + * @param codec Bounded binary framing and section integrity. + * @param galleryCodec Portable gallery record codec. + * @param preferencesCodec Portable scalar field codec. + * @param database Shared Room database used for consistent snapshot reads. + * @param preferencesGateway Strict allowlisted preference store. + * @param authorizationStore Protected portable Basic Auth source. + * @param selectionGuard Serializes provider snapshot reads with configuration publication. + * @param buildInfo Flavor/platform availability and source version. + * @param clock UTC archive timestamp. + * @param json Forward-compatible metadata serializer. + * @param staging Admits file creation only after one-time orphan cleanup has preserved pending restores. + * @author Dmitriy Moroz + */ +internal class DefaultBackupArchiveStore( + private val files: BackupFileStore, + private val codec: BackupArchiveCodec, + private val galleryCodec: GalleryBackupCodec, + private val preferencesCodec: BackupPreferencesCodec, + private val database: BackupStorage, + private val preferencesGateway: BackupPreferencesGateway, + private val authorizationStore: AuthorizationStore, + private val selectionGuard: ProviderSelectionGuard, + private val buildInfo: BuildInfoProvider, + private val clock: TimeProvider, + private val json: Json, + private val staging: BackupStagingCleaner, +) : BackupArchiveStore { + + override fun preparedExport(handle: String, filename: String): BackupExport { + val path = directory(handle) / ARCHIVE + check(FileSystem.SYSTEM.exists(path)) { "Pending backup source is unavailable" } + return BackupExport(files.documentReference(path), filename, handle) + } + + override suspend fun inventory(): BackupInspection { + val preferences = ordinarySnapshot() + return BackupInspection( + "", + 0, + "", + "", + listOf( + BackupEntry( + BackupCategory.PROVIDERS, + preferences.providers.size.toLong(), + preferences.providers.isNotEmpty() + ), + BackupEntry( + BackupCategory.GALLERY, + database.generationResultDao().observeCount().first().toLong() + ), + BackupEntry( + BackupCategory.NETWORK, + database.networkUsageDao().query().size.toLong() + ), + BackupEntry( + BackupCategory.SETTINGS, + preferences.settings.size.toLong(), + preferences.settings.isNotEmpty() + ), + ).map { if (it.itemCount == 0L) it.copy(isAvailable = false) else it }, + preferences.providers.keys + ) + } + + override suspend fun create( + selection: BackupSelection, + progress: (BackupProgress) -> Unit + ): BackupExport { + staging.prepare() + require(selection.categories.isNotEmpty()) { "Select backup data" } + val snapshot = + if (BackupCategory.PROVIDERS in selection.categories) portableSnapshot() else ordinarySnapshot() + val handle = files.newId() + val directory = directory(handle) + FileSystem.SYSTEM.createDirectories(directory) + try { + val sections = mutableListOf() + val payloads = mutableListOf() + suspend fun payload(category: BackupCategory, block: suspend (Path) -> Long) { + if (category !in selection.categories) return + currentCoroutineContext().ensureActive() + val path = directory / category.key + val count = block(path) + sections += codec.describe(path, category.key, count) + payloads += path + } + payload(BackupCategory.PROVIDERS) { path -> + val values = snapshot.providers.filterKeys { it in selection.providers } + require(values.isNotEmpty()) { "Select providers" } + FileSystem.SYSTEM.sink(path).buffer() + .use { codec.writeJson(it, preferencesCodec.encodeProviders(values)) } + values.size.toLong() + } + payload(BackupCategory.SETTINGS) { path -> + FileSystem.SYSTEM.sink(path).buffer() + .use { codec.writeJson(it, preferencesCodec.encode(snapshot.settings)) } + snapshot.settings.size.toLong() + } + database.readSnapshot { + payload(BackupCategory.GALLERY) { path -> + var offset = 0L + var afterId = 0L + FileSystem.SYSTEM.sink(path).buffer().use { sink -> + while (true) { + currentCoroutineContext().ensureActive() + val row = database.generationResultDao().queryBackupPage(afterId, 1) + .firstOrNull() ?: break + galleryCodec.write(sink, row) + offset++ + afterId = row.id + progress(BackupProgress(BackupCategory.GALLERY, offset, 0)) + } + } + offset + } + payload(BackupCategory.NETWORK) { path -> + val values = database.networkUsageDao().query() + .filter { NetworkUsageBucket.parse(it.category) != null } + .associate { it.category to it.bytes } + require(values.values.all { it >= 0 }) { "Invalid saved network counter" } + FileSystem.SYSTEM.sink(path).buffer() + .use { codec.writeJson(it, json.encodeToString(values)) } + values.size.toLong() + } + } + val manifest = BackupManifest( + handle, + clock.currentTimeMillis(), + buildInfo.version.toString(), + buildInfo.platform.name, + sections + ) + codec.write(directory / ARCHIVE, manifest, payloads) + payloads.forEach { FileSystem.SYSTEM.delete(it) } + return BackupExport( + files.documentReference(directory / ARCHIVE), + "SDAI-${manifest.createdAt}.sdaibackup", + handle + ) + } catch (failure: Throwable) { + FileSystem.SYSTEM.deleteRecursively(directory, mustExist = false) + throw failure + } + } + + override suspend fun inspect( + document: String, + progress: (BackupProgress) -> Unit + ): BackupInspection { + staging.prepare() + val handle = files.newId() + val directory = directory(handle) + FileSystem.SYSTEM.createDirectories(directory) + try { + val target = directory / ARCHIVE + val displayName = files.documentName(document).take(512) + FileSystem.SYSTEM.sink(directory / "name").buffer().use { it.writeUtf8(displayName) } + val sourceLocation = files.documentLocation(document).take(2048) + FileSystem.SYSTEM.sink(directory / "location").buffer() + .use { it.writeUtf8(sourceLocation) } + files.openDocument(document).use { source -> + FileSystem.SYSTEM.sink(target).buffer().use { sink -> + val buffer = Buffer() + var copied = 0L + while (true) { + currentCoroutineContext().ensureActive() + val read = source.read(buffer, 65536) + if (read == -1L) break + require(files.availableBytes() > read + 1024 * 1024) { "Not enough storage for backup" } + sink.write(buffer, read) + copied += read + progress(BackupProgress(null, copied, 0)) + } + } + } + val archive = staged(handle) + validatePayloads(archive, progress) + return summary(archive) + } catch (failure: Throwable) { + FileSystem.SYSTEM.deleteRecursively(directory, mustExist = false) + throw failure + } + } + + override suspend fun staged(handle: String): StagedBackup { + val path = directory(handle) / ARCHIVE + return StagedBackup(handle, path, codec.inspect(path)) + } + + override fun preferences(archive: StagedBackup): BackupPreferences { + val providers = if (compatible(archive, BackupCategory.PROVIDERS)) { + codec.openSection(archive.path, archive.manifest, BackupCategory.PROVIDERS.key) + .use { source -> + preferencesCodec.decodeProviders(codec.readJson(source)) + .also { require(source.exhausted()) { "Unexpected provider payload" } } + } + } else emptyMap() + val settings = if (compatible(archive, BackupCategory.SETTINGS)) { + codec.openSection(archive.path, archive.manifest, BackupCategory.SETTINGS.key) + .use { source -> + preferencesCodec.decode(codec.readJson(source)) + .also { require(source.exhausted()) { "Unexpected settings payload" } } + } + } else emptyMap() + val allowed = buildInfo.setupAllowedModes().map { it.key }.toSet() + val supported = preferencesGateway.filterSupported( + BackupPreferences( + providers.filterKeys { it in allowed }, + settings + ) + ) + val withCredentials = supported.providers.mapValues { (key, values) -> + val basic = + providers[key].orEmpty() + .filter { (field, value) -> key in BASIC_PROVIDERS && field in BASIC_FIELDS && value is BackupValue.Text } + values + basic + } + return supported.copy(providers = withCredentials.filterValues { it.isNotEmpty() }) + } + + override fun summary(archive: StagedBackup): BackupInspection { + val preferences = preferences(archive) + val entries = archive.manifest.sections.mapNotNull { section -> + val category = BackupCategory.entries.firstOrNull { it.key == section.id } + ?: return@mapNotNull null + val count = when (category) { + BackupCategory.PROVIDERS -> preferences.providers.size.toLong() + BackupCategory.SETTINGS -> preferences.settings.size.toLong() + else -> section.itemCount + } + BackupEntry( + category, + count, + section.codec == "stored" && section.requiredReaderVersion <= 1 && count > 0 + ) + } + var skipped = + archive.manifest.sections.count { section -> entries.none { it.category.key == section.id && it.isAvailable } } + if (compatible(archive, BackupCategory.PROVIDERS)) { + val original = codec.openSection(archive.path, archive.manifest, "providers") + .use { preferencesCodec.decodeProviders(codec.readJson(it)) } + skipped += original.entries.sumOf { (provider, fields) -> + val supported = preferences.providers[provider] + if (supported == null) 1 else fields.keys.count { it !in supported } + } + } + if (compatible(archive, BackupCategory.SETTINGS)) { + val original = codec.openSection(archive.path, archive.manifest, "settings") + .use { preferencesCodec.decode(codec.readJson(it)) } + skipped += original.keys.count { it !in preferences.settings } + } + val nameFile = archive.path.parent!! / "name" + val filename = + if (FileSystem.SYSTEM.exists(nameFile)) FileSystem.SYSTEM.source(nameFile).buffer() + .use { it.readUtf8() } else "SDAI.sdaibackup" + return BackupInspection( + archive.handle, + archive.manifest.createdAt, + archive.manifest.appVersion, + archive.manifest.sourcePlatform, + entries, + preferences.providers.keys, + skipped, + filename, + sourceLocation = (archive.path.parent!! / "location").let { location -> + if (FileSystem.SYSTEM.exists(location)) FileSystem.SYSTEM.source(location).buffer() + .use { it.readUtf8() } else "" + }, + ) + } + + override suspend fun export(document: String, destination: String) { + val path = privateDocument(document) + FileSystem.SYSTEM.source(path).buffer().use { source -> + files.writeDocument(destination).use { sink -> + val buffer = Buffer() + while (true) { + currentCoroutineContext().ensureActive() + val count = source.read(buffer, 65536) + if (count == -1L) break + sink.write(buffer, count) + } + } + } + } + + override fun discard(handle: String) { + val id = if (handle.startsWith("file://")) privateDocument(handle).parent!!.name else handle + // The discard use case resolves pending checked writes and abandons intent before cleanup. + FileSystem.SYSTEM.deleteRecursively(directory(id), mustExist = false) + } + + private fun ordinarySnapshot(): BackupPreferences { + val snapshot = preferencesGateway.read() + val allowed = buildInfo.setupAllowedModes().map { it.key }.toSet() + return snapshot.copy(providers = snapshot.providers.filterKeys { it in allowed }) + } + + private suspend fun portableSnapshot(): BackupPreferences = selectionGuard.withSelection { + val snapshot = preferencesGateway.read() + val allowed = buildInfo.setupAllowedModes().map { it.key }.toSet() + val providers = snapshot.providers.filterKeys { it in allowed }.toMutableMap() + val credentials = authorizationStore.getAuthorizationCredentials() + if (credentials is AuthorizationCredentials.HttpBasic) { + BASIC_PROVIDERS.filter { it in allowed }.forEach { key -> + providers[key] = providers[key].orEmpty() + mapOf( + "basicLogin" to BackupValue.Text(credentials.login), + "basicPassword" to BackupValue.Text(credentials.password) + ) + } + } + snapshot.copy(providers = providers) + } + + private suspend fun validatePayloads( + archive: StagedBackup, + progress: (BackupProgress) -> Unit + ) { + preferences(archive) + for (section in archive.manifest.sections) { + if (section.codec != "stored" || section.requiredReaderVersion > 1) continue + when (section.id) { + "gallery" -> codec.openSection(archive.path, archive.manifest, section.id) + .use { source -> + repeatCount(section.itemCount) { index -> + currentCoroutineContext().ensureActive() + galleryCodec.read(source, "validation") + progress( + BackupProgress( + BackupCategory.GALLERY, + index + 1, + section.itemCount + ) + ) + } + require(source.exhausted()) { "Unexpected gallery payload" } + } + + "network" -> codec.openSection(archive.path, archive.manifest, section.id) + .use { source -> + val counters = + json.decodeFromString>(codec.readJson(source)) + require(counters.values.all { it >= 0 } && source.exhausted()) { "Invalid network payload" } + } + } + } + } + + private fun compatible(archive: StagedBackup, category: BackupCategory) = + archive.manifest.sections.any { + it.id == category.key && it.codec == "stored" && it.requiredReaderVersion <= 1 + } + + private fun directory(handle: String): Path { + require(handle.matches(Regex("[0-9a-fA-F-]{36}"))) { "Invalid backup handle" } + return files.root / handle + } + + private fun privateDocument(document: String): Path { + val path = files.documentPath(document) + val parts = path.relativeTo(files.root).segments + require(parts.size == 2 && parts[1] == ARCHIVE) { "Invalid backup document" } + return directory(parts[0]) / ARCHIVE + } + + private suspend fun repeatCount(count: Long, block: suspend (Long) -> Unit) { + var index = 0L + while (index < count) { + block(index); index++ + } + } + + private companion object { + const val ARCHIVE = "archive.sdaibackup" + val BASIC_PROVIDERS = setOf("custom", "swarm_ui") + val BASIC_FIELDS = setOf("basicLogin", "basicPassword") + } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/archive/DefaultBackupStagingCleaner.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/archive/DefaultBackupStagingCleaner.kt new file mode 100644 index 000000000..2e80d32b5 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/archive/DefaultBackupStagingCleaner.kt @@ -0,0 +1,75 @@ +package com.shifthackz.aisdv1.feature.backup.archive + +import com.shifthackz.aisdv1.feature.backup.io.BackupFileStore +import com.shifthackz.aisdv1.domain.gateway.backup.BackupExportStateStore +import com.shifthackz.aisdv1.storage.gateway.BackupStorage +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import okio.FileSystem +import okio.Path +import okio.SYSTEM + +/** + * Cleans only generated directories under the app-owned backup root before new operations are admitted. + * A single initialization mutex prevents a concurrent create/import from allocating files during cleanup. + * + * @param files Platform-owned private staging root; user-selected documents are never inspected here. + * @param database Durable restore ledger identifying archives that must remain available for recovery. + * @param exports Durable native export ownership retained across host/process recreation. + * + * @author Dmitriy Moroz + */ +internal class DefaultBackupStagingCleaner( + private val files: BackupFileStore, + private val database: BackupStorage, + private val exports: BackupExportStateStore, +) : BackupStagingCleaner { + private val initialization = Mutex() + private var hasPrepared = false + + override suspend fun prepare() = initialization.withLock { + if (hasPrepared) return@withLock + exports.recoverPendingWrite() + val retained = + database.restoreSessionDao().pending().map { it.archiveHandle }.toSet() + listOfNotNull( + exports.read()?.handle + ) + val root = files.root + val metadata = FileSystem.SYSTEM.metadataOrNull(root) + if (metadata != null) { + check(metadata.isDirectory && metadata.symlinkTarget == null) { + "Private backup staging root is not an owned directory" + } + FileSystem.SYSTEM.list(root).forEach { child -> + currentCoroutineContext().ensureActive() + if (child.name.matches(GENERATED_HANDLE) && child.name !in retained) { + deleteOwnedEntry(child) + } + } + } + hasPrepared = true + } + + /** + * Deletes a private tree without following symbolic links into user-managed storage. + * + * @param path Entry below a generated app-owned staging directory. + * + * @author Dmitriy Moroz + */ + private suspend fun deleteOwnedEntry(path: Path) { + currentCoroutineContext().ensureActive() + val metadata = FileSystem.SYSTEM.metadata(path) + if (metadata.isDirectory && metadata.symlinkTarget == null) { + FileSystem.SYSTEM.list(path).forEach { child -> deleteOwnedEntry(child) } + } + FileSystem.SYSTEM.delete(path) + } + + private companion object { + val GENERATED_HANDLE = + Regex("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}") + } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/archive/StagedBackup.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/archive/StagedBackup.kt new file mode 100644 index 000000000..c8141dc09 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/archive/StagedBackup.kt @@ -0,0 +1,13 @@ +package com.shifthackz.aisdv1.feature.backup.archive + +import com.shifthackz.aisdv1.feature.backup.codec.BackupManifest +import okio.Path + +/** + * Verified immutable archive reference owned by private staging. + * @param handle Private generated directory name. + * @param path Private binary archive path. + * @param manifest Verified framing and integrity summary. + * @author Dmitriy Moroz + */ +internal data class StagedBackup(val handle: String, val path: Path, val manifest: BackupManifest) diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BackupArchiveCodec.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BackupArchiveCodec.kt new file mode 100644 index 000000000..9d14ef83e --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BackupArchiveCodec.kt @@ -0,0 +1,60 @@ +package com.shifthackz.aisdv1.feature.backup.codec + +import okio.Path +import okio.BufferedSink +import okio.BufferedSource + +/** + * Framing and integrity operations for the portable binary container. + * @author Dmitriy Moroz + */ +internal interface BackupArchiveCodec { + /** + * Writes a complete binary envelope from precomputed streamed sections; cancellation or write failure propagates. + * @param path Private target archive. + * @param manifest Descriptors whose lengths and digests match payload files. + * @param payloads Private section files in manifest order. + * @author Dmitriy Moroz + */ + suspend fun write(path: Path, manifest: BackupManifest, payloads: List) + + /** + * Checks framing, supported container major, lengths and every section digest before returning metadata. + * @param path Immutable staged archive; malformed or truncated input throws. + * @author Dmitriy Moroz + */ + suspend fun inspect(path: Path): BackupManifest + + /** + * Opens a bounded reader that cannot consume the next section; the caller owns closing it. + * @param path Validated staged archive. + * @param manifest Verified descriptor order and lengths. + * @param id Known section identifier to read. + * @author Dmitriy Moroz + */ + fun openSection(path: Path, manifest: BackupManifest, id: String): BufferedSource + + /** + * Computes the streamed SHA-256 and size descriptor without retaining the payload in memory. + * @param path Completed private section file. + * @param id Stable section wire key. + * @param count Number of records actually encoded. + * @author Dmitriy Moroz + */ + suspend fun describe(path: Path, id: String, count: Long): BackupSection + + /** + * Writes one bounded UTF8 metadata frame, rejecting records over the metadata limit. + * @param sink Owned binary section writer. + * @param text Typed metadata JSON, excluding binary image data. + * @author Dmitriy Moroz + */ + fun writeJson(sink: BufferedSink, text: String) + + /** + * Reads exactly one bounded metadata frame; invalid length or truncation throws. + * @param source Reader confined to the selected section. + * @author Dmitriy Moroz + */ + fun readJson(source: BufferedSource): String +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BackupManifest.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BackupManifest.kt new file mode 100644 index 000000000..0c7080c21 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BackupManifest.kt @@ -0,0 +1,23 @@ +package com.shifthackz.aisdv1.feature.backup.codec + +import kotlinx.serialization.Serializable + +/** + * Versioned archive metadata independent of Room entities and application versions. + * @param archiveId Unique exported snapshot identity. + * @param createdAt UTC epoch milliseconds. + * @param appVersion Display-only source version. + * @param sourcePlatform Source platform label. + * @param sections Ordered length-delimited section descriptors. + * @param schemaVersion Manifest schema version. + * @author Dmitriy Moroz + */ +@Serializable +internal data class BackupManifest( + val archiveId: String, + val createdAt: Long, + val appVersion: String, + val sourcePlatform: String, + val sections: List, + val schemaVersion: Int = 1, +) diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BackupPreferencesCodec.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BackupPreferencesCodec.kt new file mode 100644 index 000000000..7fbcdc5d1 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BackupPreferencesCodec.kt @@ -0,0 +1,37 @@ +package com.shifthackz.aisdv1.feature.backup.codec + +import com.shifthackz.aisdv1.domain.entity.backup.BackupValue + +/** + * Encodes portable scalar fields and preserves unsupported field identifiers for compatibility reporting. + * @author Dmitriy Moroz + */ +internal interface BackupPreferencesCodec { + /** + * Serializes only explicitly present typed scalar fields. + * @param values Stable field IDs and their portable scalar values. + * @author Dmitriy Moroz + */ + fun encode(values: Map): String + + /** + * Decodes scalar fields while retaining missing-entry semantics; unsupported value identifiers remain available for skipped-field accounting. + * @param text One bounded metadata JSON object. + * @author Dmitriy Moroz + */ + fun decode(text: String): Map + + /** + * Encodes independent provider groups using stable provider and field IDs. + * @param values Selected portable provider groups; may contain credentials and must not be logged. + * @author Dmitriy Moroz + */ + fun encodeProviders(values: Map>): String + + /** + * Decodes independent provider objects without requiring any currently mandatory setup fields. + * @param text Bounded provider-section metadata JSON. + * @author Dmitriy Moroz + */ + fun decodeProviders(text: String): Map> +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BackupSection.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BackupSection.kt new file mode 100644 index 000000000..250ff4dc2 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BackupSection.kt @@ -0,0 +1,27 @@ +package com.shifthackz.aisdv1.feature.backup.codec + +import kotlinx.serialization.Serializable + +/** + * Length-delimited manifest descriptor; digest covers the exact stored payload bytes. + * @param id Stable section key. + * @param schemaVersion Writer section schema. + * @param requiredReaderVersion Minimum compatible section reader. + * @param codec Payload encoding. + * @param storedBytes Exact payload byte length. + * @param decodedBytes Decoded byte length; identical for stored payloads. + * @param sha256 Lowercase SHA-256 integrity digest. + * @param itemCount Number of represented records. + * @author Dmitriy Moroz + */ +@Serializable +internal data class BackupSection( + val id: String, + val schemaVersion: Int = 1, + val requiredReaderVersion: Int = 1, + val codec: String = "stored", + val storedBytes: Long, + val decodedBytes: Long, + val sha256: String, + val itemCount: Long, +) diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BinaryBackupArchiveCodec.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BinaryBackupArchiveCodec.kt new file mode 100644 index 000000000..3e94e9dcd --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BinaryBackupArchiveCodec.kt @@ -0,0 +1,142 @@ +package com.shifthackz.aisdv1.feature.backup.codec + +import okio.use +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.serialization.json.Json +import okio.blackholeSink +import okio.Buffer +import okio.BufferedSink +import okio.BufferedSource +import okio.FileSystem +import okio.HashingSink +import okio.HashingSource +import okio.Path +import okio.SYSTEM +import okio.buffer + +/** + * Streams bounded, length-delimited sections with independently verified SHA-256 checksums. + * @param json Forward-compatible JSON metadata decoder; binary payloads never become one JSON document. + * @author Dmitriy Moroz + */ +internal class BinaryBackupArchiveCodec(private val json: Json) : BackupArchiveCodec { + + override suspend fun write(path: Path, manifest: BackupManifest, payloads: List) { + val bytes = json.encodeToString(manifest).encodeToByteArray() + require(bytes.size <= MAX_METADATA) { "Backup manifest is too large" } + FileSystem.SYSTEM.sink(path).buffer().use { sink -> + sink.write(MAGIC) + sink.writeShortLe(1) + sink.writeShortLe(0) + sink.writeIntLe(bytes.size) + sink.write(bytes) + payloads.forEach { payload -> + FileSystem.SYSTEM.source(payload).buffer().use { source -> + val buffer = Buffer() + while (true) { + currentCoroutineContext().ensureActive() + val count = source.read(buffer, 65536) + if (count == -1L) break + sink.write(buffer, count) + } + } + } + } + } + + override suspend fun inspect(path: Path): BackupManifest { + FileSystem.SYSTEM.source(path).buffer().use { source -> + require(source.readByteArray(8).contentEquals(MAGIC)) { "Not an SDAI backup" } + require(source.readShortLe().toInt() == 1) { "Unsupported backup container version" } + source.readShortLe() // Additive minor versions preserve framing. + val length = source.readIntLe() + require(length in 1..MAX_METADATA) { "Invalid backup manifest length" } + val manifest = json.decodeFromString(source.readUtf8(length.toLong())) + require(manifest.schemaVersion == 1 && manifest.sections.size <= 128) { "Unsupported backup manifest" } + require(manifest.archiveId.isNotBlank() && manifest.createdAt >= 0) { "Invalid backup metadata" } + require(manifest.sections.map { it.id } + .distinct().size == manifest.sections.size) { "Duplicate backup sections" } + var remaining = FileSystem.SYSTEM.metadata(path).size!! - 16L - length + manifest.sections.forEach { section -> + require(section.storedBytes >= 0 && section.storedBytes <= remaining && section.itemCount >= 0) { "Invalid section length" } + require(section.schemaVersion > 0 && section.requiredReaderVersion > 0) { "Invalid section version" } + require(section.sha256.matches(Regex("[0-9a-f]{64}"))) { "Invalid backup checksum" } + if (section.codec == "stored") require(section.decodedBytes == section.storedBytes) { "Invalid decoded length" } + val hashing = HashingSink.sha256(blackholeSink()) + val buffer = Buffer() + var left = section.storedBytes + hashing.use { output -> + while (left > 0) { + currentCoroutineContext().ensureActive() + val read = source.read(buffer, minOf(left, 65536L)) + require(read > 0) { "Truncated backup section" } + output.write(buffer, read) + left -= read + } + } + require(hashing.hash.hex() == section.sha256) { "Backup checksum mismatch" } + remaining -= section.storedBytes + } + require(remaining == 0L && source.exhausted()) { "Unexpected trailing backup data" } + return manifest + } + } + + override fun openSection(path: Path, manifest: BackupManifest, id: String): BufferedSource { + val source = FileSystem.SYSTEM.source(path).buffer() + try { + source.skip(12) + val size = source.readIntLe() + source.skip(size.toLong()) + for (section in manifest.sections) { + if (section.id == id) return BoundedBackupSource( + source, + section.storedBytes + ).buffer() + source.skip(section.storedBytes) + } + error("Backup section is absent") + } catch (failure: Throwable) { + source.close() + throw failure + } + } + + override suspend fun describe(path: Path, id: String, count: Long): BackupSection { + val hashing = HashingSource.sha256(FileSystem.SYSTEM.source(path)) + hashing.buffer().use { input -> + val buffer = Buffer() + while (input.read(buffer, 65536) != -1L) { + currentCoroutineContext().ensureActive() + buffer.clear() + } + } + val size = FileSystem.SYSTEM.metadata(path).size!! + return BackupSection( + id = id, + storedBytes = size, + decodedBytes = size, + sha256 = hashing.hash.hex(), + itemCount = count + ) + } + + override fun writeJson(sink: BufferedSink, text: String) { + val bytes = text.encodeToByteArray() + require(bytes.size <= MAX_METADATA) { "Backup record metadata is too large" } + sink.writeIntLe(bytes.size) + sink.write(bytes) + } + + override fun readJson(source: BufferedSource): String { + val count = source.readIntLe() + require(count in 0..MAX_METADATA) { "Invalid backup record metadata length" } + return source.readUtf8(count.toLong()) + } + + private companion object { + const val MAX_METADATA = 1024 * 1024 + val MAGIC = byteArrayOf(83, 68, 65, 73, 66, 65, 75, 0) + } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BoundedBackupSource.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BoundedBackupSource.kt new file mode 100644 index 000000000..6cad6633a --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/BoundedBackupSource.kt @@ -0,0 +1,28 @@ +package com.shifthackz.aisdv1.feature.backup.codec + +import okio.Source +import okio.Buffer +import okio.Timeout + +/** + * Prevents a section decoder from consuming adjacent binary sections. + * @param source Owned archive source positioned at a section boundary. + * @param remaining Validated length of the selected section. + * @author Dmitriy Moroz + */ +internal class BoundedBackupSource(private val source: Source, private var remaining: Long) : + Source { + + override fun read(sink: Buffer, byteCount: Long): Long { + require(byteCount >= 0) + if (remaining == 0L) return -1 + val read = source.read(sink, minOf(byteCount, remaining)) + check(read >= 0) { "Truncated backup section" } + remaining -= read + return read + } + + override fun timeout(): Timeout = source.timeout() + + override fun close() = source.close() +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/DefaultBackupPreferencesCodec.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/DefaultBackupPreferencesCodec.kt new file mode 100644 index 000000000..b1d745fbd --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/DefaultBackupPreferencesCodec.kt @@ -0,0 +1,53 @@ +package com.shifthackz.aisdv1.feature.backup.codec + +import com.shifthackz.aisdv1.domain.entity.backup.BackupValue +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.intOrNull + +/** + * Serializes portable scalar fields without leaking preference storage keys or inventing absent values. + * @param json Forward-compatible JSON parser. + * @author Dmitriy Moroz + */ +internal class DefaultBackupPreferencesCodec(private val json: Json) : BackupPreferencesCodec { + + override fun encode(values: Map): String = + JsonObject(values.mapValues { (_, value) -> + when (value) { + BackupValue.Unsupported -> error("Unsupported portable values cannot be exported") + is BackupValue.Text -> JsonPrimitive(value.value) + is BackupValue.Flag -> JsonPrimitive(value.isTrue) + is BackupValue.Integer -> JsonPrimitive(value.value) + } + }).toString() + + override fun decode(text: String): Map { + val values = + json.parseToJsonElement(text) as? JsonObject ?: error("Invalid backup preferences") + return values.mapNotNull { (key, value) -> + val scalar = value as? JsonPrimitive ?: return@mapNotNull key to BackupValue.Unsupported + val decoded = when { + scalar.isString -> BackupValue.Text(scalar.content) + scalar.booleanOrNull != null -> BackupValue.Flag(scalar.booleanOrNull!!) + scalar.intOrNull != null -> BackupValue.Integer(scalar.intOrNull!!) + else -> BackupValue.Unsupported + } + key to decoded + }.toMap() + } + + override fun encodeProviders(values: Map>): String = + JsonObject(values.mapValues { (_, fields) -> json.parseToJsonElement(encode(fields)) }).toString() + + override fun decodeProviders(text: String): Map> { + val values = + json.parseToJsonElement(text) as? JsonObject ?: error("Invalid backup providers") + return values.mapNotNull { (provider, fields) -> + if (fields !is JsonObject) return@mapNotNull provider to mapOf("" to BackupValue.Unsupported) + provider to decode(fields.toString()) + }.toMap() + } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/DefaultGalleryBackupCodec.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/DefaultGalleryBackupCodec.kt new file mode 100644 index 000000000..8baa0a213 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/DefaultGalleryBackupCodec.kt @@ -0,0 +1,161 @@ +package com.shifthackz.aisdv1.feature.backup.codec + +import com.shifthackz.aisdv1.storage.db.persistent.entity.GenerationResultEntity +import com.shifthackz.aisdv1.domain.gateway.backup.BackupImageValidator +import com.shifthackz.aisdv1.domain.entity.backup.BackupImageBudget +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json +import okio.BufferedSink +import okio.BufferedSource +import kotlin.io.encoding.Base64 +import kotlin.io.encoding.Base64.PaddingOption +import kotlin.io.encoding.ExperimentalEncodingApi + +/** + * Encodes one gallery row at a time without loading the whole gallery. + * @param archive Length-prefixed metadata codec. + * @param json Forward-compatible typed metadata serializer. + * @param imageValidator Budgeted native probe and sampled content validator. + * @param budget Shared encoded-record admission applied before allocating encoded image buffers. + * @author Dmitriy Moroz + */ +@OptIn(ExperimentalEncodingApi::class) +internal class DefaultGalleryBackupCodec( + private val archive: BackupArchiveCodec, + private val json: Json, + private val imageValidator: BackupImageValidator, + private val budget: BackupImageBudget, +) : GalleryBackupCodec { + + override fun write(sink: BufferedSink, row: GenerationResultEntity) { + val record = GalleryBackupRecord( + createdAt = row.createdAt, + generationType = row.generationType, + prompt = row.prompt, + negativePrompt = row.negativePrompt, + width = row.width, + height = row.height, + samplingSteps = row.samplingSteps, + cfgScale = row.cfgScale, + isRestoreFaces = row.restoreFaces, + sampler = row.sampler, + seed = row.seed, + subSeed = row.subSeed, + subSeedStrength = row.subSeedStrength, + denoisingStrength = row.denoisingStrength, + isHidden = row.hidden, + isLiked = row.liked, + modelName = row.modelName, + ) + archive.writeJson(sink, json.encodeToString(record)) + val outputBytes = writeImage(sink, row.imageBase64, false, budget.maxEncodedBytes) + writeImage(sink, row.originalImageBase64, true, budget.maxEncodedBytes - outputBytes) + } + + override fun read(source: BufferedSource, revision: String): GenerationResultEntity? { + val record = json.decodeFromString(archive.readJson(source)) + val (image, outputBytes) = readImage(source, false, budget.maxEncodedBytes) + val (original, _) = readImage(source, true, budget.maxEncodedBytes - outputBytes) + if (record.generationType !in setOf("txt2img", "img2img")) return null + require(record.width > 0 && record.height > 0 && record.samplingSteps >= 0 && record.cfgScale.isFinite()) { "Invalid gallery metadata" } + require(record.subSeedStrength.isFinite() && record.denoisingStrength.isFinite()) { "Invalid gallery metadata" } + return GenerationResultEntity( + id = 0, + imageBase64 = image, + originalImageBase64 = original, + imageRevision = revision, + createdAt = record.createdAt, + generationType = record.generationType, + prompt = record.prompt, + negativePrompt = record.negativePrompt, + width = record.width, + height = record.height, + samplingSteps = record.samplingSteps, + cfgScale = record.cfgScale, + restoreFaces = record.isRestoreFaces, + sampler = record.sampler, + seed = record.seed, + subSeed = record.subSeed, + subSeedStrength = record.subSeedStrength, + denoisingStrength = record.denoisingStrength, + hidden = record.isHidden, + liked = record.isLiked, + modelName = record.modelName, + ) + } + + /** + * Admits encoded text before allocating binary bytes and emits one validated image frame. + * @param sink Current gallery section writer. + * @param value Saved Base64 image text, including supported alternate alphabet or whitespace. + * @param canBeEmpty Whether this is the optional original input image. + * @param remainingBytes Encoded-byte allowance left in this output/input record. + * @author Dmitriy Moroz + */ + private fun writeImage( + sink: BufferedSink, + value: String, + canBeEmpty: Boolean, + remainingBytes: Int + ): Int { + // Admit the Base64 text before allocating its decoded byte array or a normalized copy. + val maxChars = ((remainingBytes.toLong() + 2) / 3) * 4 + require(value.length.toLong() <= maxChars) { "Backup image exceeds encoded record budget" } + val normalized = + if (value.any { it.isWhitespace() || it == '-' || it == '_' }) buildString(value.length) { + value.forEach { character -> + if (!character.isWhitespace()) append( + when (character) { + '-' -> '+'; '_' -> '/'; else -> character + } + ) + } + } else value + val bytes = + if (normalized.isEmpty()) byteArrayOf() else Base64.Default.withPadding(PaddingOption.PRESENT_OPTIONAL) + .decode(normalized) + require(bytes.size <= remainingBytes) { "Backup image exceeds encoded record budget" } + validateImage(bytes, canBeEmpty) + sink.writeIntLe(bytes.size) + sink.write(bytes) + return bytes.size + } + + /** + * Checks the frame length before allocation and returns Base64 text with its consumed binary byte count. + * @param source Bounded gallery section reader. + * @param canBeEmpty Whether the optional original input may be absent. + * @param remainingBytes Encoded-byte allowance left after preceding image frames. + * @author Dmitriy Moroz + */ + private fun readImage( + source: BufferedSource, + canBeEmpty: Boolean, + remainingBytes: Int + ): Pair { + val count = source.readIntLe() + require(count in 0..remainingBytes) { "Backup image exceeds encoded record budget" } + val bytes = source.readByteArray(count.toLong()) + validateImage(bytes, canBeEmpty) + return Base64.encode(bytes) to count + } + + /** + * Requires supported encoded formats and native budgeted content validation before accepting a frame. + * @param bytes Already-admitted encoded image bytes. + * @param canBeEmpty Whether a missing original input is allowed. + * @author Dmitriy Moroz + */ + private fun validateImage(bytes: ByteArray, canBeEmpty: Boolean) { + if (bytes.isEmpty() && canBeEmpty) return + require(bytes.size in 12..budget.maxEncodedBytes) { "Invalid image payload" } + val isPng = bytes.take(8) == listOf(137, 80, 78, 71, 13, 10, 26, 10).map(Int::toByte) + val isJpeg = + bytes[0] == 0xff.toByte() && bytes[1] == 0xd8.toByte() && bytes[2] == 0xff.toByte() + val isWebp = bytes.copyOfRange(0, 4).decodeToString() == "RIFF" && bytes.copyOfRange(8, 12) + .decodeToString() == "WEBP" + require(isPng || isJpeg || isWebp) { "Unsupported image payload" } + imageValidator(bytes) + } + +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/GalleryBackupCodec.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/GalleryBackupCodec.kt new file mode 100644 index 000000000..b85c34b13 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/GalleryBackupCodec.kt @@ -0,0 +1,27 @@ +package com.shifthackz.aisdv1.feature.backup.codec + +import okio.BufferedSink +import okio.BufferedSource +import com.shifthackz.aisdv1.storage.db.persistent.entity.GenerationResultEntity + +/** + * Frames gallery metadata and validated image bytes without carrying source database identities. + * @author Dmitriy Moroz + */ +internal interface GalleryBackupCodec { + /** + * Writes one metadata record and its binary output/input images without serializing local row identity. + * @param sink Section writer owned by the export operation. + * @param row Saved gallery row from a consistent database snapshot. + * @author Dmitriy Moroz + */ + fun write(sink: BufferedSink, row: GenerationResultEntity) + + /** + * Decodes and validates one row with a fresh destination ID/revision; unknown generation types are skipped. + * @param source Bounded gallery section reader. + * @param revision Fresh destination image revision unrelated to archived identity. + * @author Dmitriy Moroz + */ + fun read(source: BufferedSource, revision: String): GenerationResultEntity? +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/GalleryBackupRecord.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/GalleryBackupRecord.kt new file mode 100644 index 000000000..c8b98bed7 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/codec/GalleryBackupRecord.kt @@ -0,0 +1,46 @@ +package com.shifthackz.aisdv1.feature.backup.codec + +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerialName + +/** + * Portable image metadata. Images are separate binary frames; local IDs, revisions and transient guards are never serialized. + * @param createdAt Original creation time in epoch milliseconds. + * @param generationType Stable txt2img/img2img discriminator; future values are skipped. + * @param prompt Original positive generation prompt. + * @param negativePrompt Original negative generation prompt. + * @param width Positive output width in pixels. + * @param height Positive output height in pixels. + * @param samplingSteps Recorded sampling steps, including zero for providers that do not expose a sampler. + * @param cfgScale Finite guidance scale recorded by generation. + * @param isRestoreFaces Whether face restoration was requested. + * @param sampler Recorded sampler identifier; an empty value is preserved. + * @param seed Original textual seed without numeric reinterpretation. + * @param subSeed Original textual variation seed. + * @param subSeedStrength Finite variation strength recorded by generation. + * @param denoisingStrength Finite image-to-image denoising strength. + * @param isHidden Whether the history item is hidden from the gallery. + * @param isLiked Whether the history item is marked as a favorite. + * @param modelName Original generation model name without requiring that model on the destination. + * @author Dmitriy Moroz + */ +@Serializable +internal data class GalleryBackupRecord( + val createdAt: Long = 0, + val generationType: String = "txt2img", + val prompt: String = "", + val negativePrompt: String = "", + val width: Int = 512, + val height: Int = 512, + val samplingSteps: Int = 20, + val cfgScale: Float = 7f, + @SerialName("restoreFaces") val isRestoreFaces: Boolean = false, + val sampler: String = "", + val seed: String = "", + val subSeed: String = "", + val subSeedStrength: Float = 0f, + val denoisingStrength: Float = 0f, + @SerialName("hidden") val isHidden: Boolean = false, + @SerialName("liked") val isLiked: Boolean = false, + val modelName: String = "", +) diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/di/BackupModule.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/di/BackupModule.kt new file mode 100644 index 000000000..7431e90f6 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/di/BackupModule.kt @@ -0,0 +1,182 @@ +package com.shifthackz.aisdv1.feature.backup.di + +import com.shifthackz.aisdv1.feature.backup.archive.BackupArchiveStore +import com.shifthackz.aisdv1.feature.backup.archive.BackupStagingCleaner +import com.shifthackz.aisdv1.feature.backup.archive.DefaultBackupStagingCleaner +import com.shifthackz.aisdv1.feature.backup.archive.DefaultBackupArchiveStore +import com.shifthackz.aisdv1.feature.backup.codec.BackupArchiveCodec +import com.shifthackz.aisdv1.feature.backup.codec.BinaryBackupArchiveCodec +import com.shifthackz.aisdv1.feature.backup.codec.BackupPreferencesCodec +import com.shifthackz.aisdv1.feature.backup.codec.DefaultBackupPreferencesCodec +import com.shifthackz.aisdv1.feature.backup.codec.GalleryBackupCodec +import com.shifthackz.aisdv1.feature.backup.codec.DefaultGalleryBackupCodec +import com.shifthackz.aisdv1.feature.backup.restore.BackupProviderPlanner +import com.shifthackz.aisdv1.feature.backup.restore.DefaultBackupProviderPlanner +import com.shifthackz.aisdv1.feature.backup.restore.BackupRestoreGuard +import com.shifthackz.aisdv1.feature.backup.restore.DefaultBackupRestoreGuard +import com.shifthackz.aisdv1.feature.backup.restore.BackupImageFingerprint +import com.shifthackz.aisdv1.feature.backup.restore.DefaultBackupImageFingerprint +import com.shifthackz.aisdv1.feature.backup.restore.BackupRestoreWriter +import com.shifthackz.aisdv1.feature.backup.restore.RoomBackupRestoreWriter +import com.shifthackz.aisdv1.feature.backup.restore.BackupSessionCodec +import com.shifthackz.aisdv1.feature.backup.restore.DefaultBackupSessionCodec +import com.shifthackz.aisdv1.domain.usecase.backup.LoadBackupInventoryUseCase +import com.shifthackz.aisdv1.feature.backup.usecase.LoadBackupInventoryUseCaseImpl +import com.shifthackz.aisdv1.domain.usecase.backup.CreateBackupUseCase +import com.shifthackz.aisdv1.feature.backup.usecase.CreateBackupUseCaseImpl +import com.shifthackz.aisdv1.domain.usecase.backup.InspectBackupUseCase +import com.shifthackz.aisdv1.feature.backup.usecase.InspectBackupUseCaseImpl +import com.shifthackz.aisdv1.domain.usecase.backup.RestoreBackupUseCase +import com.shifthackz.aisdv1.feature.backup.usecase.RestoreBackupUseCaseImpl +import com.shifthackz.aisdv1.domain.usecase.backup.ExportBackupUseCase +import com.shifthackz.aisdv1.feature.backup.usecase.ExportBackupUseCaseImpl +import com.shifthackz.aisdv1.domain.usecase.backup.DiscardBackupUseCase +import com.shifthackz.aisdv1.feature.backup.usecase.DiscardBackupUseCaseImpl +import com.shifthackz.aisdv1.domain.usecase.backup.GetBackupStartupStageUseCase +import com.shifthackz.aisdv1.feature.backup.usecase.GetBackupStartupStageUseCaseImpl +import com.shifthackz.aisdv1.domain.usecase.backup.SetBackupStartupStageUseCase +import com.shifthackz.aisdv1.feature.backup.usecase.SetBackupStartupStageUseCaseImpl +import com.shifthackz.aisdv1.domain.usecase.backup.LoadPendingBackupUseCase +import com.shifthackz.aisdv1.feature.backup.usecase.LoadPendingBackupUseCaseImpl +import kotlinx.serialization.json.Json +import org.koin.core.module.Module +import org.koin.core.qualifier.named +import com.shifthackz.aisdv1.domain.gateway.GenerationRestoreGate +import com.shifthackz.aisdv1.feature.backup.restore.DefaultGenerationRestoreGate +import com.shifthackz.aisdv1.domain.usecase.backup.CompleteBackupExportUseCase +import com.shifthackz.aisdv1.feature.backup.usecase.CompleteBackupExportUseCaseImpl +import com.shifthackz.aisdv1.domain.usecase.backup.ObserveBackupExportUseCase +import com.shifthackz.aisdv1.feature.backup.usecase.ObserveBackupExportUseCaseImpl +import com.shifthackz.aisdv1.domain.usecase.backup.CancelBackupExportUseCase +import com.shifthackz.aisdv1.feature.backup.usecase.CancelBackupExportUseCaseImpl +import com.shifthackz.aisdv1.domain.usecase.backup.DismissBackupExportUseCase +import com.shifthackz.aisdv1.feature.backup.usecase.DismissBackupExportUseCaseImpl +import com.shifthackz.aisdv1.domain.usecase.backup.GetPendingBackupExportUseCase +import com.shifthackz.aisdv1.feature.backup.usecase.GetPendingBackupExportUseCaseImpl +import com.shifthackz.aisdv1.feature.backup.export.BackupExportCoordinator +import com.shifthackz.aisdv1.feature.backup.export.DefaultBackupExportCoordinator +import org.koin.dsl.module +import org.koin.dsl.onClose + +/** + * Installs platform file transport behind the same common backup contracts on both targets. + * @author Dmitriy Moroz + */ +internal expect val backupPlatformModule: Module + +/** + * Registers backup implementations without exposing feature dependencies to presentation leaves. + * @author Dmitriy Moroz + */ +val backupModule = module { + includes(backupPlatformModule) + single { DefaultGenerationRestoreGate() } + single(named("backupJson")) { Json { ignoreUnknownKeys = true; encodeDefaults = true } } + single { BinaryBackupArchiveCodec(get(named("backupJson"))) } + single { DefaultBackupPreferencesCodec(get(named("backupJson"))) } + single { + DefaultGalleryBackupCodec( + get(), + get(named("backupJson")), + get(), + get() + ) + } + single { DefaultBackupRestoreGuard() } + single { DefaultBackupProviderPlanner(get()) } + single { DefaultBackupSessionCodec(get(named("backupJson"))) } + single { DefaultBackupImageFingerprint() } + single { + RoomBackupRestoreWriter( + get(), + get(), + get(), + get(), + get(named("backupJson")), + get(), + get(), + ) + } + single { DefaultBackupStagingCleaner(get(), get(), get()) } + single { + DefaultBackupArchiveStore( + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(named("backupJson")), + get() + ) + } + factory { LoadBackupInventoryUseCaseImpl(get(), get()) } + single { + DefaultBackupExportCoordinator( + get(), + get(), + get(), + get() + ) + } onClose { it?.close() } + factory { CompleteBackupExportUseCaseImpl(get()) } + factory { ObserveBackupExportUseCaseImpl(get()) } + factory { CancelBackupExportUseCaseImpl(get()) } + factory { DismissBackupExportUseCaseImpl(get()) } + factory { GetPendingBackupExportUseCaseImpl(get(), get()) } + factory { CreateBackupUseCaseImpl(get(), get()) } + factory { InspectBackupUseCaseImpl(get(), get()) } + factory { ExportBackupUseCaseImpl(get(), get()) } + factory { GetBackupStartupStageUseCaseImpl(get()) } + factory { SetBackupStartupStageUseCaseImpl(get()) } + factory { + LoadPendingBackupUseCaseImpl( + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get() + ) + } + factory { + DiscardBackupUseCaseImpl( + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get() + ) + } + factory { + RestoreBackupUseCaseImpl( + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get() + ) + } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/export/BackupExportCoordinator.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/export/BackupExportCoordinator.kt new file mode 100644 index 000000000..45254a363 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/export/BackupExportCoordinator.kt @@ -0,0 +1,56 @@ +package com.shifthackz.aisdv1.feature.backup.export + +import com.shifthackz.aisdv1.domain.entity.backup.BackupExport +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportCompletion +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportOperation +import com.shifthackz.aisdv1.domain.entity.backup.BackupProgress +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection +import kotlinx.coroutines.flow.StateFlow + +/** + * Owns one process-scoped export; native callbacks are serialized independently from screen lifetimes. + * @author Dmitriy Moroz + */ +internal interface BackupExportCoordinator { + /** + * Creates or resumes a staged source and persists association before native picker presentation. + * @param selection Explicit data selection when creating a new source. + * @param progress Bounded source-creation progress. + * @author Dmitriy Moroz + */ + suspend fun prepare( + selection: BackupSelection, + progress: (BackupProgress) -> Unit + ): BackupExport + + /** + * Observes nonsecret pending/completed operation state across composition recreation. + * @author Dmitriy Moroz + */ + fun observe(): StateFlow + + /** + * Queues a native result even while screen initialization is running. + * @param completion Destination or native completion/cancellation outcome. + * @author Dmitriy Moroz + */ + fun submit(completion: BackupExportCompletion) + + /** + * Cancels only the currently active copy, preserving its source and explicit retry state. + * @author Dmitriy Moroz + */ + fun cancel() + + /** + * Acknowledges the current export before releasing its app-owned staged source. + * @author Dmitriy Moroz + */ + suspend fun dismiss() + + /** + * Closes the process owner when its Koin graph is stopped; durable intent remains recoverable. + * @author Dmitriy Moroz + */ + fun close() +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/export/DefaultBackupExportCoordinator.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/export/DefaultBackupExportCoordinator.kt new file mode 100644 index 000000000..de1788aff --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/export/DefaultBackupExportCoordinator.kt @@ -0,0 +1,216 @@ +package com.shifthackz.aisdv1.feature.backup.export + +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import com.shifthackz.aisdv1.domain.entity.backup.BackupExport +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportCompletion +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportIntent +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportOperation +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportStatus +import com.shifthackz.aisdv1.domain.entity.backup.BackupProgress +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection +import com.shifthackz.aisdv1.domain.gateway.backup.BackupExportStateStore +import com.shifthackz.aisdv1.domain.usecase.backup.ExportBackupUseCase +import com.shifthackz.aisdv1.feature.backup.archive.BackupArchiveStore +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.job +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** + * Keeps destination copying and its durable association alive when a screen/activity is recreated. + * @param archives Strict app-owned archive creation, source resolution and cleanup. + * @param records Dedicated checked nonsecret operation persistence. + * @param export Strict complete-byte destination writer. + * @param dispatchers Application IO dispatcher owned by this graph-scoped coordinator. + * @author Dmitriy Moroz + */ +internal class DefaultBackupExportCoordinator( + private val archives: BackupArchiveStore, + private val records: BackupExportStateStore, + private val export: ExportBackupUseCase, + private val dispatchers: DispatchersProvider, +) : BackupExportCoordinator { + private val scope = CoroutineScope(SupervisorJob() + dispatchers.io) + private val serialization = Mutex() + private val operation = MutableStateFlow(BackupExportOperation()) + private val queuedResults = MutableStateFlow(0) + private val copyingJob = MutableStateFlow(null) + + init { + scope.launch { + serialization.withLock { + try { + records.recoverPendingWrite() + val intent = records.read() + if (intent != null) { + if (intent.status == BackupExportStatus.COPYING && intent.destination != null) copy( + intent + ) + else publish(intent) + } + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + operation.value = BackupExportOperation(BackupExportStatus.FAILED) + } + } + } + } + + override suspend fun prepare( + selection: BackupSelection, + progress: (BackupProgress) -> Unit + ): BackupExport = withContext(dispatchers.io) { + serialization.withLock { + records.recoverPendingWrite() + records.read()?.let { + return@withLock publish(it).backup ?: error("Pending backup source is unavailable") + } + val backup = archives.create(selection, progress) + val intent = BackupExportIntent(backup.handle, backup.filename) + // Never delete this source on a failed checked write: its quarantined intent can be retried. + records.write(intent) + publish(intent) + backup + } + } + + override fun observe(): StateFlow = operation.asStateFlow() + + override fun submit(completion: BackupExportCompletion) { + queuedResults.update { it + 1 } + operation.value = operation.value.copy(status = BackupExportStatus.PROCESSING) + scope.launch { + serialization.withLock { + var hasFailed = false + try { + records.recoverPendingWrite() + val intent = + checkNotNull(records.read()) { "No staged export owns this document result" } + if (intent.handle != completion.handle) { + publish(intent) + return@withLock + } + when (completion) { + is BackupExportCompletion.DestinationSelected -> { + require(completion.document.isNotBlank()) { "Empty backup destination" } + // A fresh picker can truncate even a previously completed destination URI. + copy( + intent.copy( + destination = completion.document + ) + ) + } + + is BackupExportCompletion.NativeCompleted -> { + val complete = intent.copy(status = BackupExportStatus.COMPLETE) + records.write(complete) + publish(complete) + } + + is BackupExportCompletion.Canceled -> if (intent.status != BackupExportStatus.COMPLETE) dismissLocked( + intent + ) + } + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + hasFailed = true + operation.value = operation.value.copy(status = BackupExportStatus.FAILED) + } finally { + queuedResults.update { it - 1 } + if (queuedResults.value == 0) { + try { + val current = records.read() + if (current == null) operation.value = + BackupExportOperation(if (hasFailed) BackupExportStatus.FAILED else BackupExportStatus.NONE) + else { + publish(current) + if (hasFailed) operation.value = + operation.value.copy(status = BackupExportStatus.FAILED) + } + } catch (_: Exception) { + operation.value = + operation.value.copy(status = BackupExportStatus.FAILED) + } + } + } + } + } + } + + private suspend fun copy(intent: BackupExportIntent) { + val backup = archives.preparedExport(intent.handle, intent.filename) + val destination = checkNotNull(intent.destination) { "Missing backup destination" } + val copying = intent.copy(status = BackupExportStatus.COPYING) + withContext(NonCancellable) { records.write(copying) } + operation.value = BackupExportOperation(BackupExportStatus.COPYING, backup) + val owner = currentCoroutineContext().job + copyingJob.value = owner + try { + export(backup.document, destination) + withContext(NonCancellable) { + val completed = copying.copy(status = BackupExportStatus.COMPLETE) + records.write(completed) + publish(completed) + } + } catch (cancelled: CancellationException) { + withContext(NonCancellable) { + val canceled = copying.copy(status = BackupExportStatus.CANCELED) + records.write(canceled) + publish(canceled) + } + throw cancelled + } catch (failure: Exception) { + withContext(NonCancellable) { + val failed = copying.copy(status = BackupExportStatus.FAILED) + records.write(failed) + publish(failed) + } + throw failure + } finally { + if (copyingJob.value === owner) copyingJob.value = null + } + } + + override fun cancel() { + copyingJob.value?.cancel() + } + + override suspend fun dismiss() = withContext(dispatchers.io) { + serialization.withLock { + records.recoverPendingWrite() + records.read()?.let { dismissLocked(it) } + Unit + } + } + + private fun dismissLocked(intent: BackupExportIntent) { + records.clear() + operation.value = + BackupExportOperation(if (queuedResults.value > 0) BackupExportStatus.PROCESSING else BackupExportStatus.NONE) + archives.discard(intent.handle) + } + + private fun publish(intent: BackupExportIntent): BackupExportOperation = + BackupExportOperation( + if (queuedResults.value > 0) BackupExportStatus.PROCESSING else intent.status, + archives.preparedExport(intent.handle, intent.filename) + ).also { operation.value = it } + + override fun close() { + scope.cancel() + } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/io/BackupFileStore.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/io/BackupFileStore.kt new file mode 100644 index 000000000..c80b558bc --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/io/BackupFileStore.kt @@ -0,0 +1,68 @@ +package com.shifthackz.aisdv1.feature.backup.io + +import okio.Path +import okio.BufferedSource +import okio.BufferedSink + +/** + * Private durable archive staging and native document transport. User-selected sources are never deleted. + * @author Dmitriy Moroz + */ +internal interface BackupFileStore { + val root: Path + + /** + * Creates an escaped native file URL for a private completed archive. + * @param path App-owned private archive path. + * @author Dmitriy Moroz + */ + fun documentReference(path: Path): String + + /** + * Resolves a private native file URL without treating its encoded path as display text. + * @param reference Native file reference; non-file schemes are rejected. + * @author Dmitriy Moroz + */ + fun documentPath(reference: String): Path + + /** + * Reads only the display filename of a selected source, never its full storage path. + * @param document Native user-selected source reference. + * @author Dmitriy Moroz + */ + fun documentName(document: String): String + + /** + * Describes the selected source for display without inventing a filesystem path for cloud providers. + * @param document Read-granted native source reference selected by the user. + * @return Available native path or a document-provider reference with query/fragment removed. + * @author Dmitriy Moroz + */ + fun documentLocation(document: String): String + + /** + * Returns a fresh UUID for app-owned staging, sessions or imported image revisions. + * @author Dmitriy Moroz + */ + fun newId(): String + + /** + * Opens a read-granted native document stream; caller closes it after private staging. + * @param document Native URI or sandbox-copy URL selected by the user. + * @author Dmitriy Moroz + */ + fun openDocument(document: String): BufferedSource + + /** + * Opens the user-selected destination for complete export; failures propagate. + * @param document Native write-granted document reference. + * @author Dmitriy Moroz + */ + fun writeDocument(document: String): BufferedSink + + /** + * Returns current private-filesystem free bytes for bounded staging admission. + * @author Dmitriy Moroz + */ + fun availableBytes(): Long +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupImageFingerprint.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupImageFingerprint.kt new file mode 100644 index 000000000..698c54b3f --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupImageFingerprint.kt @@ -0,0 +1,16 @@ +package com.shifthackz.aisdv1.feature.backup.restore + +/** + * Identifies exact encoded image bytes independently of Base64 alphabet, whitespace, padding or gallery metadata. + * @author Dmitriy Moroz + */ +internal fun interface BackupImageFingerprint { + /** + * Streams bounded Base64 text into a SHA-256 identity without decoding image pixels. + * Invalid or absent existing image text has no identity; storage failures and cancellation propagate. + * @param readChunk Reads sequentially at most the requested UTF8 bytes at an increasing zero-based byte offset; empty means EOF, null means absent. + * @return Encoded-image byte identity, or null for missing, empty or malformed Base64. + * @author Dmitriy Moroz + */ + suspend operator fun invoke(readChunk: suspend (offset: Long, maxBytes: Int) -> ByteArray?): String? +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupProviderPlan.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupProviderPlan.kt new file mode 100644 index 000000000..3631c7d97 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupProviderPlan.kt @@ -0,0 +1,23 @@ +package com.shifthackz.aisdv1.feature.backup.restore + +import com.shifthackz.aisdv1.domain.entity.backup.BackupValue +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationCredentials + +/** + * Immutable selective provider merge prepared under the provider transition guard. + * @param providers Portable independent field replacements. + * @param credentials Shared Basic Auth replacement, or null to retain destination credentials. + * @param conflicts Configured providers whose existing values would change. + * @param fingerprint Opaque consent revision binding both source and destination. + * @param skippedCount Credential fields omitted to preserve unselected configured providers. + * @param retainedCredentialProviders Unselected configured providers that prevented shared credential replacement. + * @author Dmitriy Moroz + */ +internal data class BackupProviderPlan( + val providers: Map>, + val credentials: AuthorizationCredentials?, + val conflicts: Set, + val fingerprint: String, + val skippedCount: Int, + val retainedCredentialProviders: Set = emptySet(), +) diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupProviderPlanner.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupProviderPlanner.kt new file mode 100644 index 000000000..ecb0e5669 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupProviderPlanner.kt @@ -0,0 +1,26 @@ +package com.shifthackz.aisdv1.feature.backup.restore + +import com.shifthackz.aisdv1.domain.entity.backup.BackupPreferences +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationCredentials + +/** + * Determines provider conflicts and shared-credential eligibility without mutating storage. + * @author Dmitriy Moroz + */ +internal interface BackupProviderPlanner { + /** + * Builds a presence-aware selective merge and consent fingerprint without changing stored data. + * @param current Destination portable settings with persisted presence. + * @param incoming Supported archive fields including selected portable Basic Auth. + * @param selection Explicitly selected provider children. + * @param credentials Trusted destination Basic Auth snapshot used to protect other consumers. + * @author Dmitriy Moroz + */ + fun plan( + current: BackupPreferences, + incoming: BackupPreferences, + selection: BackupSelection, + credentials: AuthorizationCredentials + ): BackupProviderPlan +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupRestoreGuard.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupRestoreGuard.kt new file mode 100644 index 000000000..bb0221685 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupRestoreGuard.kt @@ -0,0 +1,14 @@ +package com.shifthackz.aisdv1.feature.backup.restore + +/** + * Serializes restore operations across screens and recovery entry points. + * @author Dmitriy Moroz + */ +internal interface BackupRestoreGuard { + /** + * Runs one restore or staging-discard operation at a time; cancellation while waiting propagates. + * @param block Complete operation that owns private staging and journal transitions. + * @author Dmitriy Moroz + */ + suspend fun exclusive(block: suspend () -> T): T +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupRestoreWriter.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupRestoreWriter.kt new file mode 100644 index 000000000..8fcded8bc --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupRestoreWriter.kt @@ -0,0 +1,32 @@ +package com.shifthackz.aisdv1.feature.backup.restore + +import com.shifthackz.aisdv1.feature.backup.archive.StagedBackup +import com.shifthackz.aisdv1.domain.entity.backup.BackupProgress + +/** + * Strict additive Room writes; exact gallery duplicates are skipped and each category commits with its ledger marker. + * @author Dmitriy Moroz + */ +internal interface BackupRestoreWriter { + /** + * Allocates fresh IDs only for output images absent from gallery/history and earlier archive rows. + * Existing metadata, favorites and visibility remain unchanged; imports and skipped counts commit atomically. + * @param sessionId Stable restore retry identity. + * @param archive Validated immutable staged archive. + * @param progress Processed-row progress; completion is acknowledged only after commit. + * @author Dmitriy Moroz + */ + suspend fun gallery( + sessionId: String, + archive: StagedBackup, + progress: (BackupProgress) -> Unit + ) + + /** + * Adds checked known byte buckets and their section marker atomically, never resetting existing counters. + * @param sessionId Stable restore retry identity. + * @param archive Validated immutable staged archive. + * @author Dmitriy Moroz + */ + suspend fun network(sessionId: String, archive: StagedBackup) +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupSessionCodec.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupSessionCodec.kt new file mode 100644 index 000000000..cae34ebbf --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/BackupSessionCodec.kt @@ -0,0 +1,23 @@ +package com.shifthackz.aisdv1.feature.backup.restore + +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection + +/** + * Typed BackupSessionCodec operations used by backup orchestration and implementations. + * @author Dmitriy Moroz + */ +internal interface BackupSessionCodec { + /** + * Produces deterministic nonsecret selection JSON for binding a retry session to its original choices. + * @param selection Selected category/provider IDs only. + * @author Dmitriy Moroz + */ + fun encode(selection: BackupSelection): String + + /** + * Restores known category/provider identifiers from the journal; unknown categories are ignored. + * @param value Persisted nonsecret selection JSON. + * @author Dmitriy Moroz + */ + fun decode(value: String): BackupSelection +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultBackupImageFingerprint.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultBackupImageFingerprint.kt new file mode 100644 index 000000000..31a6910e6 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultBackupImageFingerprint.kt @@ -0,0 +1,90 @@ +package com.shifthackz.aisdv1.feature.backup.restore + +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import okio.Buffer +import okio.HashingSink +import okio.blackholeSink +import okio.buffer +import okio.use +import kotlin.io.encoding.Base64 +import kotlin.io.encoding.Base64.PaddingOption + +/** + * Hashes decoded Base64 chunks so alternate valid text representations still identify the same saved image. + * At most one 64KiB UTF8 chunk and its decoded bytes are held in addition to the caller's data. + * @author Dmitriy Moroz + */ +internal class DefaultBackupImageFingerprint : BackupImageFingerprint { + + override suspend fun invoke(readChunk: suspend (Long, Int) -> ByteArray?): String? { + val hashing = HashingSink.sha256(blackholeSink()) + var hasBytes = false + hashing.buffer().use { sink -> + var offset = 0L + var pending = "" + val utf8 = Buffer() + while (true) { + currentCoroutineContext().ensureActive() + val chunk = readChunk(offset, CHUNK_BYTES) ?: return null + if (chunk.isEmpty()) { + if (!utf8.exhausted()) return null + break + } + offset += chunk.size + utf8.write(chunk) + val normalized = buildString(pending.length + chunk.size) { + append(pending) + while (!utf8.exhausted()) { + val lead = utf8[0].toInt() and 0xff + val byteCount = when { + lead < 0x80 -> 1 + lead and 0xe0 == 0xc0 -> 2 + lead and 0xf0 == 0xe0 -> 3 + lead and 0xf8 == 0xf0 -> 4 + else -> return null + } + if (utf8.size < byteCount) break + val codePoint = utf8.readUtf8CodePoint() + if (codePoint > Char.MAX_VALUE.code) return null + val character = codePoint.toChar() + if (!character.isWhitespace()) append( + when (character) { + '-' -> '+' + '_' -> '/' + else -> character + } + ) + } + } + // Retain the final quartet until EOF; padding is valid only at the end of the whole image. + val completeChars = ((normalized.length - 4).coerceAtLeast(0) / 4) * 4 + val complete = normalized.substring(0, completeChars) + if ('=' in complete) return null + val decoded = decode(complete) ?: return null + sink.write(decoded) + hasBytes = hasBytes || decoded.isNotEmpty() + pending = normalized.substring(completeChars) + } + val decoded = decode(pending) ?: return null + sink.write(decoded) + hasBytes = hasBytes || decoded.isNotEmpty() + } + return hashing.hash.hex().takeIf { hasBytes } + } + + /** + * Treats malformed image text as unidentifiable without masking storage or cancellation failures. + * @param value Complete Base64 quartets or the final optionally padded group. + * @author Dmitriy Moroz + */ + private fun decode(value: String): ByteArray? = try { + Base64.Default.withPadding(PaddingOption.PRESENT_OPTIONAL).decode(value) + } catch (_: IllegalArgumentException) { + null + } + + private companion object { + const val CHUNK_BYTES = 65536 + } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultBackupProviderPlanner.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultBackupProviderPlanner.kt new file mode 100644 index 000000000..168233d2c --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultBackupProviderPlanner.kt @@ -0,0 +1,91 @@ +package com.shifthackz.aisdv1.feature.backup.restore + +import com.shifthackz.aisdv1.domain.entity.backup.BackupPreferences +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection +import com.shifthackz.aisdv1.domain.entity.backup.BackupValue +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationCredentials +import com.shifthackz.aisdv1.feature.backup.codec.BackupPreferencesCodec +import okio.ByteString.Companion.encodeUtf8 + +/** + * Preserves absent fields and every unselected provider, including shared Basic Auth consumers. + * @param codec Deterministic portable preference encoding for opaque consent fingerprints. + * @author Dmitriy Moroz + */ +internal class DefaultBackupProviderPlanner(private val codec: BackupPreferencesCodec) : + BackupProviderPlanner { + + override fun plan( + current: BackupPreferences, + incoming: BackupPreferences, + selection: BackupSelection, + credentials: AuthorizationCredentials + ): BackupProviderPlan { + val selected = incoming.providers.filterKeys { it in selection.providers } + val conflicts = mutableSetOf() + val fields = selected.mapValues { (provider, values) -> + values.filterKeys { it !in BASIC_FIELDS }.also { changes -> + val existing = current.providers[provider].orEmpty() + if (changes.any { (key, value) -> existing.containsKey(key) && existing[key] != value }) conflicts += provider + } + } + val credentialValues = + selected.filterKeys { it in BASIC_PROVIDERS }.values.map { it.filterKeys { key -> key in BASIC_FIELDS } } + .filter { it.isNotEmpty() }.distinct() + require(credentialValues.size <= 1) { "Conflicting shared Basic Auth records" } + val incomingBasic = credentialValues.firstOrNull() + val affected = current.providers.keys.intersect(BASIC_PROVIDERS) + var replacement: AuthorizationCredentials? = null + var skipped = 0 + var retainedCredentialProviders = emptySet() + if (incomingBasic != null) { + if (!selection.providers.containsAll(affected)) { + skipped += incomingBasic.size + retainedCredentialProviders = affected - selection.providers + } else { + val old = credentials as? AuthorizationCredentials.HttpBasic + val login = (incomingBasic["basicLogin"] as? BackupValue.Text)?.value + ?: old?.login.orEmpty() + val password = (incomingBasic["basicPassword"] as? BackupValue.Text)?.value + ?: old?.password.orEmpty() + val candidate = AuthorizationCredentials.HttpBasic(login, password) + if (candidate != credentials) { + replacement = candidate + if (credentials !is AuthorizationCredentials.None) conflicts += affected.ifEmpty { + selected.keys.intersect( + BASIC_PROVIDERS + ) + } + } + } + } + val credentialSnapshot = when (credentials) { + AuthorizationCredentials.None -> emptyMap() + is AuthorizationCredentials.HttpBasic -> mapOf( + "login" to BackupValue.Text(credentials.login), + "password" to BackupValue.Text(credentials.password) + ) + } + val fingerprint = (codec.encodeProviders( + current.providers.filterKeys { it in selection.providers }.toList() + .sortedBy { it.first }.toMap() + .mapValues { it.value.toList().sortedBy { it.first }.toMap() }) + + codec.encodeProviders( + selected.toList().sortedBy { it.first }.toMap().mapValues { + it.value.toList().sortedBy { it.first }.toMap() + }) + codec.encode(credentialSnapshot)).encodeUtf8().sha256().hex() + return BackupProviderPlan( + fields, + replacement, + conflicts, + fingerprint, + skipped, + retainedCredentialProviders + ) + } + + private companion object { + val BASIC_PROVIDERS = setOf("custom", "swarm_ui") + val BASIC_FIELDS = setOf("basicLogin", "basicPassword") + } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultBackupRestoreGuard.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultBackupRestoreGuard.kt new file mode 100644 index 000000000..c0f21b5e8 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultBackupRestoreGuard.kt @@ -0,0 +1,14 @@ +package com.shifthackz.aisdv1.feature.backup.restore + +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** + * Owns one process-wide restore lock; no user-data work escapes its operation scope. + * @author Dmitriy Moroz + */ +internal class DefaultBackupRestoreGuard : BackupRestoreGuard { + private val mutex = Mutex() + + override suspend fun exclusive(block: suspend () -> T): T = mutex.withLock { block() } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultBackupSessionCodec.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultBackupSessionCodec.kt new file mode 100644 index 000000000..69f2ef127 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultBackupSessionCodec.kt @@ -0,0 +1,27 @@ +package com.shifthackz.aisdv1.feature.backup.restore + +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json + +/** + * Encodes journal selection IDs only; no credentials or application payloads enter the restore ledger. + * @param json Serializer for nonsecret selection lists. + * @author Dmitriy Moroz + */ +internal class DefaultBackupSessionCodec(private val json: Json) : BackupSessionCodec { + + override fun encode(selection: BackupSelection): String = json.encodeToString( + mapOf( + "categories" to selection.categories.map { it.key }.sorted(), + "providers" to selection.providers.sorted(), + ) + ) + + override fun decode(value: String): BackupSelection { + val entries = json.decodeFromString>>(value) + return BackupSelection(BackupCategory.entries.filter { it.key in entries["categories"].orEmpty() } + .toSet(), entries["providers"].orEmpty().toSet()) + } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultGenerationRestoreGate.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultGenerationRestoreGate.kt new file mode 100644 index 000000000..55147cc8d --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/DefaultGenerationRestoreGate.kt @@ -0,0 +1,49 @@ +package com.shifthackz.aisdv1.feature.backup.restore + +import com.shifthackz.aisdv1.domain.gateway.GenerationRestoreGate + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.withContext +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** + * Allows existing concurrent generation while admitting restore only when every generation owner is idle. + * New generation waits cancellably while restore owns the exclusive transition. + * @author Dmitriy Moroz + */ +internal class DefaultGenerationRestoreGate : GenerationRestoreGate { + private val state = Mutex() + private var activeGenerations = 0 + private var restoration: CompletableDeferred? = null + + override suspend fun generating(block: suspend () -> T): T { + while (true) { + val pendingRestore = state.withLock { + restoration.also { if (it == null) activeGenerations++ } + } + if (pendingRestore == null) break + pendingRestore.await() + } + return try { + block() + } finally { + withContext(NonCancellable) { state.withLock { activeGenerations-- } } + } + } + + override suspend fun restoring(block: suspend () -> T): T { + state.withLock { + check(activeGenerations == 0 && restoration == null) { "Wait for generation to finish before restoring" } + restoration = CompletableDeferred() + } + return try { + block() + } finally { + withContext(NonCancellable) { + state.withLock { restoration?.complete(Unit); restoration = null } + } + } + } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/RoomBackupRestoreWriter.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/RoomBackupRestoreWriter.kt new file mode 100644 index 000000000..d738415a8 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/restore/RoomBackupRestoreWriter.kt @@ -0,0 +1,163 @@ +package com.shifthackz.aisdv1.feature.backup.restore + +import okio.use +import com.shifthackz.aisdv1.domain.entity.NetworkUsageBucket +import com.shifthackz.aisdv1.domain.entity.backup.BackupImageBudget +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.entity.backup.BackupProgress +import com.shifthackz.aisdv1.feature.backup.archive.StagedBackup +import com.shifthackz.aisdv1.feature.backup.codec.BackupArchiveCodec +import com.shifthackz.aisdv1.feature.backup.codec.GalleryBackupCodec +import com.shifthackz.aisdv1.feature.backup.io.BackupFileStore +import com.shifthackz.aisdv1.storage.gateway.BackupStorage +import com.shifthackz.aisdv1.storage.db.persistent.entity.RestoreSectionEntity +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.serialization.json.Json + +/** + * Imports unique output images directly into Room, preserving existing rows and avoiding generation-save auto-export. + * @param database Destination database and category commit ledger. + * @param codec Validated length-delimited section reader. + * @param galleryCodec Per-image metadata and binary image decoder. + * @param files Fresh imported image revision identities. + * @param json Typed network counter decoder. + * @param fingerprint Streams saved output-image identities for exact duplicate suppression. + * @param budget Admits one ordinary image text before hashing; oversized legacy representations use chunked reads. + * @author Dmitriy Moroz + */ +internal class RoomBackupRestoreWriter( + private val database: BackupStorage, + private val codec: BackupArchiveCodec, + private val galleryCodec: GalleryBackupCodec, + private val files: BackupFileStore, + private val json: Json, + private val fingerprint: BackupImageFingerprint, + private val budget: BackupImageBudget, +) : BackupRestoreWriter { + + override suspend fun gallery( + sessionId: String, + archive: StagedBackup, + progress: (BackupProgress) -> Unit + ) { + val descriptor = archive.manifest.sections.single { it.id == "gallery" } + var committedCount: Long? = null + database.writeTransaction { + if ("gallery" in database.restoreSessionDao() + .completed(sessionId) + ) return@writeTransaction + val knownImages = mutableSetOf() + val gallery = database.generationResultDao() + var afterId = 0L + while (true) { + currentCoroutineContext().ensureActive() + val ids = gallery.queryImageIdsAfter(afterId, 128) + if (ids.isEmpty()) break + ids.forEach { id -> + existingImageFingerprint(id)?.let(knownImages::add) + } + afterId = ids.last() + } + var count = 0L + var skipped = 0L + codec.openSection(archive.path, archive.manifest, "gallery").use { source -> + var index = 0L + while (index < descriptor.itemCount) { + currentCoroutineContext().ensureActive() + val row = galleryCodec.read(source, files.newId()) + if (row == null) skipped++ else { + val identity = checkNotNull(imageFingerprint(row.imageBase64)) { + "Validated backup image has invalid Base64" + } + if (knownImages.add(identity)) { + gallery.insert(row) + count++ + } else skipped++ + } + index++ + } + require(source.exhausted()) { "Unexpected gallery payload" } + } + database.restoreSessionDao() + .mark(RestoreSectionEntity(sessionId, "gallery", count, skipped)) + committedCount = count + } + committedCount?.let { + progress( + BackupProgress( + BackupCategory.GALLERY, + it, + descriptor.itemCount + ) + ) + } + } + + /** + * Reads ordinary images once; exceptionally long wrapped text retains the exact-comparison fallback. + * @param id Existing gallery/history identity inside the category transaction. + * @author Dmitriy Moroz + */ + private suspend fun existingImageFingerprint(id: Long): String? { + val gallery = database.generationResultDao() + val maxTextBytes = ((budget.maxEncodedBytes.toLong() + 2) / 3) * 4 + val text = gallery.queryImageTextForFingerprint(id, maxTextBytes) + return if (text != null) imageFingerprint(text) else { + fingerprint { offset, maxBytes -> gallery.queryImageChunk(id, offset + 1, maxBytes) } + } + } + + /** + * Encodes an admitted string into small UTF8 chunks without allocating another full-image byte array. + * @param text Existing admitted image or canonical Base64 returned by the validated archive decoder. + * @author Dmitriy Moroz + */ + private suspend fun imageFingerprint(text: String): String? { + var characterOffset = 0 + var byteOffset = 0L + return fingerprint { offset, maxBytes -> + check(offset == byteOffset) { "Image fingerprint reader must advance sequentially" } + val end = minOf(text.length, characterOffset + maxOf(1, maxBytes / 4)) + val bytes = text.substring(characterOffset, end).encodeToByteArray() + characterOffset = end + byteOffset += bytes.size + bytes + } + } + + override suspend fun network(sessionId: String, archive: StagedBackup) { + val values = codec.openSection(archive.path, archive.manifest, "network").use { source -> + val counters = json.decodeFromString>(codec.readJson(source)) + require(source.exhausted() && counters.values.all { it >= 0 }) { "Invalid network counter" } + counters + } + database.writeTransaction { + if ("network" in database.restoreSessionDao() + .completed(sessionId) + ) return@writeTransaction + val current = database.networkUsageDao().query().associate { it.category to it.bytes } + val supported = values.filterKeys { NetworkUsageBucket.parse(it) != null } + supported.forEach { (key, bytes) -> + val old = current[key] ?: 0 + require(old >= 0 && bytes <= Long.MAX_VALUE - old) { "Network counter overflow" } + } + // Also protect the existing totalBytes aggregate from overflow. + var total = 0L + NetworkUsageBucket.entries.forEach { bucket -> + val bytes = (current[bucket.key] ?: 0) + (supported[bucket.key] ?: 0) + require(bytes >= 0 && bytes <= Long.MAX_VALUE - total) { "Network total overflow" } + total += bytes + } + supported.forEach { (key, bytes) -> database.networkUsageDao().addBytes(key, bytes) } + database.restoreSessionDao().mark( + RestoreSectionEntity( + sessionId, + "network", + supported.size.toLong(), + (values.size - supported.size).toLong() + ) + ) + } + } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/CancelBackupExportUseCaseImpl.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/CancelBackupExportUseCaseImpl.kt new file mode 100644 index 000000000..30bb8ac00 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/CancelBackupExportUseCaseImpl.kt @@ -0,0 +1,15 @@ +package com.shifthackz.aisdv1.feature.backup.usecase + +import com.shifthackz.aisdv1.domain.usecase.backup.CancelBackupExportUseCase +import com.shifthackz.aisdv1.feature.backup.export.BackupExportCoordinator + +/** + * Interrupts active destination copying while retaining a durable source for an explicit retry. + * @param coordinator Owns durable export association independently from screen lifetimes. + * @author Dmitriy Moroz + */ +internal class CancelBackupExportUseCaseImpl(private val coordinator: BackupExportCoordinator) : + CancelBackupExportUseCase { + + override fun invoke(): Unit = coordinator.cancel() +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/CompleteBackupExportUseCaseImpl.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/CompleteBackupExportUseCaseImpl.kt new file mode 100644 index 000000000..e54864c43 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/CompleteBackupExportUseCaseImpl.kt @@ -0,0 +1,16 @@ +package com.shifthackz.aisdv1.feature.backup.usecase + +import com.shifthackz.aisdv1.domain.usecase.backup.CompleteBackupExportUseCase +import com.shifthackz.aisdv1.feature.backup.export.BackupExportCoordinator +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportCompletion + +/** + * Queues native outcomes through the graph owner, including results delivered before screen initialization. + * @param coordinator Owns durable export association independently from screen lifetimes. + * @author Dmitriy Moroz + */ +internal class CompleteBackupExportUseCaseImpl(private val coordinator: BackupExportCoordinator) : + CompleteBackupExportUseCase { + + override fun invoke(completion: BackupExportCompletion): Unit = coordinator.submit(completion) +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/CreateBackupUseCaseImpl.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/CreateBackupUseCaseImpl.kt new file mode 100644 index 000000000..8384bb11d --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/CreateBackupUseCaseImpl.kt @@ -0,0 +1,26 @@ +package com.shifthackz.aisdv1.feature.backup.usecase + +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection +import com.shifthackz.aisdv1.domain.entity.backup.BackupProgress +import com.shifthackz.aisdv1.domain.entity.backup.BackupExport +import com.shifthackz.aisdv1.domain.usecase.backup.CreateBackupUseCase +import com.shifthackz.aisdv1.feature.backup.export.BackupExportCoordinator +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import kotlinx.coroutines.withContext + +/** + * Runs the strict create archive operation on the IO dispatcher. + * @param coordinator Owns source creation and durable association before document presentation. + * @param dispatchers Runs file and database work off the UI thread. + * @author Dmitriy Moroz + */ +internal class CreateBackupUseCaseImpl( + private val coordinator: BackupExportCoordinator, + private val dispatchers: DispatchersProvider +) : CreateBackupUseCase { + + override suspend operator fun invoke( + selection: BackupSelection, + onProgress: (BackupProgress) -> Unit + ): BackupExport = withContext(dispatchers.io) { coordinator.prepare(selection, onProgress) } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/DiscardBackupUseCaseImpl.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/DiscardBackupUseCaseImpl.kt new file mode 100644 index 000000000..c7bc5ac41 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/DiscardBackupUseCaseImpl.kt @@ -0,0 +1,73 @@ +package com.shifthackz.aisdv1.feature.backup.usecase + +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.gateway.backup.BackupChangesGateway +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationStore +import com.shifthackz.aisdv1.domain.gateway.backup.BackupPreferencesGateway +import com.shifthackz.aisdv1.domain.gateway.ProviderSelectionGuard +import com.shifthackz.aisdv1.domain.preference.ConfigurationStore +import com.shifthackz.aisdv1.domain.usecase.backup.DiscardBackupUseCase +import com.shifthackz.aisdv1.feature.backup.archive.BackupArchiveStore +import com.shifthackz.aisdv1.feature.backup.restore.BackupRestoreGuard +import com.shifthackz.aisdv1.feature.backup.restore.BackupSessionCodec +import com.shifthackz.aisdv1.storage.gateway.BackupStorage +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.withContext + +/** + * Abandons an unfinished operation only after checked configuration/credentials are trusted; removes private staging only. + * @param archives Owns generated private archive paths. + * @param preferences Recovers an already-started checked typed settings batch before startup or abandonment. + * @param database Durable pending intent records. + * @param configuration Checked preference quarantine owner. + * @param authorization Protected Basic Auth recovery owner. + * @param selectionGuard Serializes association recovery before abandonment. + * @param restoreGuard Prevents deletion during active import. + * @param dispatchers Runs cleanup on IO. + * @param sessions Reads category intent when a previous replay committed without a section marker. + * @param changes Refreshes retained preference readers after protected association recovery. + * @author Dmitriy Moroz + */ +internal class DiscardBackupUseCaseImpl( + private val archives: BackupArchiveStore, + private val database: BackupStorage, + private val preferences: BackupPreferencesGateway, + private val configuration: ConfigurationStore, + private val authorization: AuthorizationStore, + private val selectionGuard: ProviderSelectionGuard, + private val restoreGuard: BackupRestoreGuard, + private val dispatchers: DispatchersProvider, + private val sessions: BackupSessionCodec, + private val changes: BackupChangesGateway, +) : DiscardBackupUseCase { + + override suspend fun invoke(handle: String) = withContext(dispatchers.io) { + restoreGuard.exclusive { + val pending = + database.restoreSessionDao().pending().filter { it.archiveHandle == handle } + if (pending.isNotEmpty()) selectionGuard.withSelection { + val recovered = pending.flatMap { sessions.decode(it.selection).categories } + .filter { it == BackupCategory.PROVIDERS || it == BackupCategory.SETTINGS } + .toMutableSet() + if (configuration.retryPendingConfiguration()) recovered += BackupCategory.PROVIDERS + recovered += preferences.recoverPendingWrite() + authorization.getAuthorizationCredentials() + withContext(NonCancellable) { changes.notifyChanged(recovered) } + if (pending.any { it.requiresConfiguration } && preferences.readStartupStage() in setOf( + BackupStartupStage.INVITATION, + BackupStartupStage.RESTORE + )) preferences.writeStartupStage( + BackupStartupStage.CONFIGURATION + ) + pending.forEach { + database.restoreSessionDao().finish(it.id) + if (it.requiresConfiguration) database.restoreSessionDao() + .acknowledgeConfiguration(it.id) + } + } + archives.discard(handle) + } + } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/DismissBackupExportUseCaseImpl.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/DismissBackupExportUseCaseImpl.kt new file mode 100644 index 000000000..8cf7bafae --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/DismissBackupExportUseCaseImpl.kt @@ -0,0 +1,15 @@ +package com.shifthackz.aisdv1.feature.backup.usecase + +import com.shifthackz.aisdv1.domain.usecase.backup.DismissBackupExportUseCase +import com.shifthackz.aisdv1.feature.backup.export.BackupExportCoordinator + +/** + * Acknowledges export state before releasing private source ownership. + * @param coordinator Process-owned serialized export lifecycle. + * @author Dmitriy Moroz + */ +internal class DismissBackupExportUseCaseImpl(private val coordinator: BackupExportCoordinator) : + DismissBackupExportUseCase { + + override suspend fun invoke() = coordinator.dismiss() +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/ExportBackupUseCaseImpl.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/ExportBackupUseCaseImpl.kt new file mode 100644 index 000000000..cce7c407f --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/ExportBackupUseCaseImpl.kt @@ -0,0 +1,21 @@ +package com.shifthackz.aisdv1.feature.backup.usecase + +import com.shifthackz.aisdv1.domain.usecase.backup.ExportBackupUseCase +import com.shifthackz.aisdv1.feature.backup.archive.BackupArchiveStore +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import kotlinx.coroutines.withContext + +/** + * Runs the strict export archive operation on the IO dispatcher. + * @param archives Injected archive framing and staging owner. + * @param dispatchers Runs file and database work off the UI thread. + * @author Dmitriy Moroz + */ +internal class ExportBackupUseCaseImpl( + private val archives: BackupArchiveStore, + private val dispatchers: DispatchersProvider +) : ExportBackupUseCase { + + override suspend operator fun invoke(document: String, destination: String): Unit = + withContext(dispatchers.io) { archives.export(document, destination) } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/GetBackupStartupStageUseCaseImpl.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/GetBackupStartupStageUseCaseImpl.kt new file mode 100644 index 000000000..cb052d71a --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/GetBackupStartupStageUseCaseImpl.kt @@ -0,0 +1,16 @@ +package com.shifthackz.aisdv1.feature.backup.usecase + +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage +import com.shifthackz.aisdv1.domain.gateway.backup.BackupPreferencesGateway +import com.shifthackz.aisdv1.domain.usecase.backup.GetBackupStartupStageUseCase + +/** + * Persists or reads the durable post-onboarding recovery stage. + * @param preferences Checked stage persistence shared with startup routing. + * @author Dmitriy Moroz + */ +internal class GetBackupStartupStageUseCaseImpl(private val preferences: BackupPreferencesGateway) : + GetBackupStartupStageUseCase { + + override operator fun invoke(): BackupStartupStage = preferences.readStartupStage() +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/GetPendingBackupExportUseCaseImpl.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/GetPendingBackupExportUseCaseImpl.kt new file mode 100644 index 000000000..067375fbb --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/GetPendingBackupExportUseCaseImpl.kt @@ -0,0 +1,23 @@ +package com.shifthackz.aisdv1.feature.backup.usecase + +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import com.shifthackz.aisdv1.domain.gateway.backup.BackupExportStateStore +import com.shifthackz.aisdv1.domain.usecase.backup.GetPendingBackupExportUseCase +import kotlinx.coroutines.withContext + +/** + * Routes durable pending or completed export outcomes back to the dedicated backup screen. + * @param records Checked nonsecret export association. + * @param dispatchers Keeps preference recovery on IO. + * @author Dmitriy Moroz + */ +internal class GetPendingBackupExportUseCaseImpl( + private val records: BackupExportStateStore, + private val dispatchers: DispatchersProvider +) : GetPendingBackupExportUseCase { + + override suspend fun invoke(): Boolean = withContext(dispatchers.io) { + records.recoverPendingWrite() + records.read() != null + } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/InspectBackupUseCaseImpl.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/InspectBackupUseCaseImpl.kt new file mode 100644 index 000000000..00e8d6169 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/InspectBackupUseCaseImpl.kt @@ -0,0 +1,25 @@ +package com.shifthackz.aisdv1.feature.backup.usecase + +import com.shifthackz.aisdv1.domain.entity.backup.BackupInspection +import com.shifthackz.aisdv1.domain.entity.backup.BackupProgress +import com.shifthackz.aisdv1.domain.usecase.backup.InspectBackupUseCase +import com.shifthackz.aisdv1.feature.backup.archive.BackupArchiveStore +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import kotlinx.coroutines.withContext + +/** + * Runs the strict inspect archive operation on the IO dispatcher. + * @param archives Injected archive framing and staging owner. + * @param dispatchers Runs file and database work off the UI thread. + * @author Dmitriy Moroz + */ +internal class InspectBackupUseCaseImpl( + private val archives: BackupArchiveStore, + private val dispatchers: DispatchersProvider +) : InspectBackupUseCase { + + override suspend operator fun invoke( + document: String, + onProgress: (BackupProgress) -> Unit + ): BackupInspection = withContext(dispatchers.io) { archives.inspect(document, onProgress) } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/LoadBackupInventoryUseCaseImpl.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/LoadBackupInventoryUseCaseImpl.kt new file mode 100644 index 000000000..7698d05f0 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/LoadBackupInventoryUseCaseImpl.kt @@ -0,0 +1,22 @@ +package com.shifthackz.aisdv1.feature.backup.usecase + +import com.shifthackz.aisdv1.domain.entity.backup.BackupInspection +import com.shifthackz.aisdv1.domain.usecase.backup.LoadBackupInventoryUseCase +import com.shifthackz.aisdv1.feature.backup.archive.BackupArchiveStore +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import kotlinx.coroutines.withContext + +/** + * Runs the strict inventory archive operation on the IO dispatcher. + * @param archives Injected archive framing and staging owner. + * @param dispatchers Runs file and database work off the UI thread. + * @author Dmitriy Moroz + */ +internal class LoadBackupInventoryUseCaseImpl( + private val archives: BackupArchiveStore, + private val dispatchers: DispatchersProvider +) : LoadBackupInventoryUseCase { + + override suspend operator fun invoke(): BackupInspection = + withContext(dispatchers.io) { archives.inventory() } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/LoadPendingBackupUseCaseImpl.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/LoadPendingBackupUseCaseImpl.kt new file mode 100644 index 000000000..4652b5736 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/LoadPendingBackupUseCaseImpl.kt @@ -0,0 +1,87 @@ +package com.shifthackz.aisdv1.feature.backup.usecase + +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import com.shifthackz.aisdv1.domain.entity.backup.BackupRecovery +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.gateway.backup.BackupChangesGateway +import kotlinx.coroutines.NonCancellable +import com.shifthackz.aisdv1.domain.entity.backup.BackupRestoreRequest +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationStore +import com.shifthackz.aisdv1.domain.gateway.backup.BackupPreferencesGateway +import com.shifthackz.aisdv1.domain.gateway.ProviderSelectionGuard +import com.shifthackz.aisdv1.domain.preference.ConfigurationStore +import com.shifthackz.aisdv1.domain.usecase.backup.LoadPendingBackupUseCase +import com.shifthackz.aisdv1.feature.backup.archive.BackupArchiveStore +import com.shifthackz.aisdv1.feature.backup.archive.BackupStagingCleaner +import com.shifthackz.aisdv1.feature.backup.restore.BackupSessionCodec +import com.shifthackz.aisdv1.storage.gateway.BackupStorage +import kotlinx.coroutines.withContext + +/** + * Recovers checked credential association before exposing the staged unfinished operation. + * @param preferences Recovers an already-started checked typed settings batch before startup or abandonment. + * @param database Restore intent ledger. + * @param archives Revalidates retained private archive bytes. + * @param sessions Decodes nonsecret category/provider selection. + * @param configuration Retries an exact failed checked preference write. + * @param authorization Recovers protected credential association before normal app publication. + * @param guard Serializes recovery with provider transitions. + * @param dispatchers Runs disk and protected-store work on IO. + * @param staging Cleans previous-process orphan files once, retaining every pending restore archive. + * @param changes Refreshes retained preference readers after protected association recovery. + * @author Dmitriy Moroz + */ +internal class LoadPendingBackupUseCaseImpl( + private val database: BackupStorage, + private val preferences: BackupPreferencesGateway, + private val archives: BackupArchiveStore, + private val sessions: BackupSessionCodec, + private val configuration: ConfigurationStore, + private val authorization: AuthorizationStore, + private val guard: ProviderSelectionGuard, + private val dispatchers: DispatchersProvider, + private val staging: BackupStagingCleaner, + private val changes: BackupChangesGateway, +) : LoadPendingBackupUseCase { + + override suspend fun invoke(): BackupRecovery? = withContext(dispatchers.io) { + staging.prepare() + val pending = + database.restoreSessionDao().pending().firstOrNull() ?: return@withContext null + val selection = sessions.decode(pending.selection) + guard.withSelection { + val recovered = + selection.categories.filter { it == BackupCategory.PROVIDERS || it == BackupCategory.SETTINGS } + .toMutableSet() + if (configuration.retryPendingConfiguration()) recovered += BackupCategory.PROVIDERS + recovered += preferences.recoverPendingWrite() + authorization.getAuthorizationCredentials() + withContext(NonCancellable) { changes.notifyChanged(recovered) } + } + val completed = database.restoreSessionDao().completed(pending.id).toSet() + val hasCommittedSelection = selection.categories.all { it.key in completed } + if (pending.requiresConfiguration && (pending.isComplete || hasCommittedSelection || preferences.readStartupStage() == BackupStartupStage.CONFIGURATION)) { + withContext(NonCancellable) { + if (preferences.readStartupStage() in setOf( + BackupStartupStage.INVITATION, + BackupStartupStage.RESTORE + ) + ) preferences.writeStartupStage(BackupStartupStage.CONFIGURATION) + database.restoreSessionDao().finish(pending.id) + database.restoreSessionDao().acknowledgeConfiguration(pending.id) + archives.discard(pending.archiveHandle) + } + return@withContext null + } + val archive = archives.staged(pending.archiveHandle) + BackupRecovery( + BackupRestoreRequest( + pending.archiveHandle, + selection, + pending.id, + shouldProceedToConfiguration = pending.requiresConfiguration + ), archives.summary(archive) + ) + } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/ObserveBackupExportUseCaseImpl.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/ObserveBackupExportUseCaseImpl.kt new file mode 100644 index 000000000..fada94e6d --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/ObserveBackupExportUseCaseImpl.kt @@ -0,0 +1,17 @@ +package com.shifthackz.aisdv1.feature.backup.usecase + +import com.shifthackz.aisdv1.domain.usecase.backup.ObserveBackupExportUseCase +import com.shifthackz.aisdv1.feature.backup.export.BackupExportCoordinator +import kotlinx.coroutines.flow.StateFlow +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportOperation + +/** + * Shares export progress and completion with each recreated screen without transferring job ownership. + * @param coordinator Owns durable export association independently from screen lifetimes. + * @author Dmitriy Moroz + */ +internal class ObserveBackupExportUseCaseImpl(private val coordinator: BackupExportCoordinator) : + ObserveBackupExportUseCase { + + override fun invoke(): StateFlow = coordinator.observe() +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/RestoreBackupUseCaseImpl.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/RestoreBackupUseCaseImpl.kt new file mode 100644 index 000000000..7cf70161b --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/RestoreBackupUseCaseImpl.kt @@ -0,0 +1,247 @@ +package com.shifthackz.aisdv1.feature.backup.usecase + +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.entity.backup.BackupProgress +import com.shifthackz.aisdv1.domain.entity.backup.BackupRestoreRequest +import com.shifthackz.aisdv1.domain.entity.backup.BackupRestoreResult +import com.shifthackz.aisdv1.domain.entity.backup.BackupRestoreNotice +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationCredentials +import com.shifthackz.aisdv1.domain.feature.auth.AuthorizationStore +import com.shifthackz.aisdv1.domain.feature.work.BackgroundWorkObserver +import com.shifthackz.aisdv1.domain.gateway.GenerationRestoreGate +import com.shifthackz.aisdv1.domain.gateway.backup.BackupChangesGateway +import com.shifthackz.aisdv1.domain.gateway.ProviderSelectionGuard +import com.shifthackz.aisdv1.domain.gateway.backup.BackupPreferencesGateway +import com.shifthackz.aisdv1.domain.preference.ConfigurationStore +import com.shifthackz.aisdv1.domain.usecase.backup.RestoreBackupUseCase +import com.shifthackz.aisdv1.feature.backup.archive.BackupArchiveStore +import com.shifthackz.aisdv1.feature.backup.restore.BackupProviderPlanner +import com.shifthackz.aisdv1.feature.backup.restore.BackupRestoreGuard +import com.shifthackz.aisdv1.feature.backup.restore.BackupRestoreWriter +import com.shifthackz.aisdv1.feature.backup.restore.BackupSessionCodec +import com.shifthackz.aisdv1.storage.gateway.BackupStorage +import com.shifthackz.aisdv1.storage.db.persistent.entity.RestoreSessionEntity +import com.shifthackz.aisdv1.storage.db.persistent.entity.RestoreSectionEntity +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.withContext + +/** + * Applies explicitly selected categories with guarded provider consent and durable category-level retries. + * @param archives Immutable staged archive reader. + * @param preferences Strict selective preference writer. + * @param configuration Existing checked configuration quarantine owner. + * @param authorization Protected Basic Auth association owner. + * @param selectionGuard Serializes conflict comparison and credential/configuration publication. + * @param restoreGuard Serializes whole restore sessions. + * @param planner Computes independent-provider conflicts without changing selection. + * @param writer Atomic additive Room imports. + * @param sessions Nonsecret selection encoder. + * @param database Durable intent and committed-category ledger. + * @param work Rejects replacement while generation work is active. + * @param changes Refreshes retained settings, locale and storage readers after durable commits. + * @param generationGate Rejects restore during generation and defers new generation until restoration finishes. + * @param dispatchers Runs durable work on IO. + * @author Dmitriy Moroz + */ +internal class RestoreBackupUseCaseImpl( + private val archives: BackupArchiveStore, + private val preferences: BackupPreferencesGateway, + private val configuration: ConfigurationStore, + private val authorization: AuthorizationStore, + private val selectionGuard: ProviderSelectionGuard, + private val restoreGuard: BackupRestoreGuard, + private val planner: BackupProviderPlanner, + private val writer: BackupRestoreWriter, + private val sessions: BackupSessionCodec, + private val database: BackupStorage, + private val work: BackgroundWorkObserver, + private val changes: BackupChangesGateway, + private val generationGate: GenerationRestoreGate, + private val dispatchers: DispatchersProvider, +) : RestoreBackupUseCase { + + override suspend fun invoke( + request: BackupRestoreRequest, + onProgress: (BackupProgress) -> Unit + ): BackupRestoreResult = withContext(dispatchers.io) { + restoreGuard.exclusive { + generationGate.restoring { + require(request.sessionId.matches(Regex("[0-9a-fA-F-]{36}"))) { "Invalid restore session" } + require(request.selection.categories.isNotEmpty()) { "Select restore data" } + val archive = archives.staged(request.handle) + val summary = archives.summary(archive) + require(request.selection.categories.all { category -> summary.entries.any { it.category == category && it.isAvailable } }) { "Unavailable backup section" } + require(summary.providers.containsAll(request.selection.providers)) { "Unavailable backup provider" } + val incoming = archives.preferences(archive) + val ledger = database.restoreSessionDao() + val selectionJson = sessions.encode(request.selection) + val recoveredPreferences = mutableSetOf() + val operationResult = runCatching { + val existing = ledger.get(request.sessionId) + check(existing == null || existing.archiveHandle == request.handle && existing.selection == selectionJson) { "Restore session belongs to another request" } + check( + ledger.pending() + .none { it.id != request.sessionId }) { "Finish or cancel the pending restore first" } + var hasFailed = false + val conflict = selectionGuard.withSelection { + check(!work.hasActiveTasks()) { "Wait for generation to finish before restoring" } + val hasRecoveredConfiguration = configuration.retryPendingConfiguration() + val recovered = preferences.recoverPendingWrite() + val hasProviderSection = + BackupCategory.PROVIDERS in request.selection.categories && "providers" !in ledger.completed( + request.sessionId + ) + val credentials = + if (hasProviderSection) authorization.getAuthorizationCredentials() else AuthorizationCredentials.None + if (hasRecoveredConfiguration) recoveredPreferences += BackupCategory.PROVIDERS + recoveredPreferences += recovered + val plan = if (hasProviderSection) planner.plan( + preferences.read(), + incoming, + request.selection, + credentials + ) else null + if (plan != null && plan.conflicts.isNotEmpty() && plan.fingerprint != request.confirmedFingerprint) { + return@withSelection BackupRestoreResult.Conflict( + plan.conflicts, + plan.fingerprint + ) + } + if (existing == null) ledger.insert( + RestoreSessionEntity( + request.sessionId, + request.handle, + selectionJson, + requiresConfiguration = request.shouldProceedToConfiguration + ) + ) + if (plan != null) { + currentCoroutineContext().ensureActive() + try { + withContext(NonCancellable) { + if (plan.credentials != null) authorization.storeAuthorizationCredentials( + plan.credentials + ) { commitId -> + preferences.writeProviders(plan.providers, commitId) + } else preferences.writeProviders(plan.providers, null) + ledger.mark( + RestoreSectionEntity( + request.sessionId, + "providers", + plan.providers.size.toLong(), + plan.skippedCount.toLong(), + plan.retainedCredentialProviders.sorted() + .joinToString(",") + ) + ) + } + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + hasFailed = true + } + } + null + } + if (conflict != null) return@runCatching conflict + if (!hasFailed) { + for (category in listOf( + BackupCategory.SETTINGS, + BackupCategory.GALLERY, + BackupCategory.NETWORK + )) { + if (category !in request.selection.categories || category.key in ledger.completed( + request.sessionId + ) + ) continue + currentCoroutineContext().ensureActive() + onProgress( + BackupProgress( + category, + 0, + archive.manifest.sections.single { it.id == category.key }.itemCount + ) + ) + try { + when (category) { + BackupCategory.SETTINGS -> withContext(NonCancellable) { + preferences.writeSettings(incoming.settings) + ledger.mark( + RestoreSectionEntity( + request.sessionId, + "settings", + incoming.settings.size.toLong() + ) + ) + } + + BackupCategory.GALLERY -> writer.gallery( + request.sessionId, + archive, + onProgress + ) + + BackupCategory.NETWORK -> writer.network( + request.sessionId, + archive + ) + + BackupCategory.PROVIDERS -> Unit + } + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + hasFailed = true; break + } + } + } + val results = ledger.results(request.sessionId) + val completed = + BackupCategory.entries.filter { category -> results.any { it.category == category.key } } + .toSet() + BackupRestoreResult.Finished( + completed, + summary.skippedCount + results.sumOf { it.skippedCount }.toInt(), + hasFailed, + results.mapNotNull { result -> + BackupCategory.entries.firstOrNull { it.key == result.category } + ?.let { it to result.importedCount } + }.toMap(), + results.mapNotNull { result -> + result.retainedCredentialProviders.split(',').filter { it.isNotBlank() } + .toSet().takeIf { it.isNotEmpty() } + ?.let { BackupRestoreNotice.SharedCredentialsRetained(it) } + } + ) + } + val publicationResult = runCatching { + withContext(NonCancellable) { + val committed = ledger.results(request.sessionId) + val completedCategories = + BackupCategory.entries.filter { category -> committed.any { it.category == category.key } } + .toSet() + val changed = completedCategories + recoveredPreferences + if (changed.isNotEmpty()) changes.notifyChanged(changed) + if (completedCategories.containsAll(request.selection.categories)) ledger.finish( + request.sessionId + ) + } + } + val operationFailure = operationResult.exceptionOrNull() + val publicationFailure = publicationResult.exceptionOrNull() + if (operationFailure != null) { + if (publicationFailure != null && publicationFailure !== operationFailure) operationFailure.addSuppressed( + publicationFailure + ) + throw operationFailure + } + publicationResult.getOrThrow() + operationResult.getOrThrow() + } + } + } +} diff --git a/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/SetBackupStartupStageUseCaseImpl.kt b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/SetBackupStartupStageUseCaseImpl.kt new file mode 100644 index 000000000..aa1fddc90 --- /dev/null +++ b/feature/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/feature/backup/usecase/SetBackupStartupStageUseCaseImpl.kt @@ -0,0 +1,19 @@ +package com.shifthackz.aisdv1.feature.backup.usecase + +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage +import com.shifthackz.aisdv1.domain.gateway.backup.BackupPreferencesGateway +import com.shifthackz.aisdv1.domain.usecase.backup.SetBackupStartupStageUseCase + +/** + * Advances durable recovery progression so a stale screen cannot reopen completed provider setup. + * @param preferences Checked stage persistence shared with startup routing. + * @author Dmitriy Moroz + */ +internal class SetBackupStartupStageUseCaseImpl(private val preferences: BackupPreferencesGateway) : + SetBackupStartupStageUseCase { + + override operator fun invoke(stage: BackupStartupStage) { + if (stage.ordinal < preferences.readStartupStage().ordinal) return + preferences.writeStartupStage(stage) + } +} diff --git a/feature/backup/src/iosMain/kotlin/com/shifthackz/aisdv1/feature/backup/di/BackupPlatformModule.ios.kt b/feature/backup/src/iosMain/kotlin/com/shifthackz/aisdv1/feature/backup/di/BackupPlatformModule.ios.kt new file mode 100644 index 000000000..15e0ba9eb --- /dev/null +++ b/feature/backup/src/iosMain/kotlin/com/shifthackz/aisdv1/feature/backup/di/BackupPlatformModule.ios.kt @@ -0,0 +1,13 @@ +package com.shifthackz.aisdv1.feature.backup.di + +import com.shifthackz.aisdv1.feature.backup.io.BackupFileStore +import com.shifthackz.aisdv1.feature.backup.io.IosBackupFileStore +import org.koin.core.module.Module +import org.koin.dsl.module + +/** + * Binds native document transport while retaining the shared backup API. + * @author Dmitriy Moroz + */ +internal actual val backupPlatformModule: Module = + module { single { IosBackupFileStore() } } diff --git a/feature/backup/src/iosMain/kotlin/com/shifthackz/aisdv1/feature/backup/io/BackupFileStore.ios.kt b/feature/backup/src/iosMain/kotlin/com/shifthackz/aisdv1/feature/backup/io/BackupFileStore.ios.kt new file mode 100644 index 000000000..4b90b0538 --- /dev/null +++ b/feature/backup/src/iosMain/kotlin/com/shifthackz/aisdv1/feature/backup/io/BackupFileStore.ios.kt @@ -0,0 +1,54 @@ +package com.shifthackz.aisdv1.feature.backup.io + +import okio.FileSystem +import okio.Path +import okio.Path.Companion.toPath +import okio.buffer +import platform.Foundation.NSFileManager +import platform.Foundation.NSFileSystemFreeSize +import platform.Foundation.NSHomeDirectory +import platform.Foundation.NSNumber +import platform.Foundation.NSURL +import platform.Foundation.NSUUID +import kotlinx.cinterop.ExperimentalForeignApi + +/** + * Stages archives in Application Support; imported picker documents are copied by UIKit into the sandbox. + * @author Dmitriy Moroz + */ +@OptIn(ExperimentalForeignApi::class) +internal class IosBackupFileStore : BackupFileStore { + override val root: Path get() = (NSHomeDirectory() + "/Library/Application Support/backup").toPath() + + override fun documentReference(path: Path): String = + NSURL.fileURLWithPath(path.toString()).absoluteString!! + + override fun documentPath(reference: String): Path { + val url = checkNotNull(NSURL.URLWithString(reference)) + require(url.scheme == "file") { "Not a private backup document" } + return checkNotNull(url.path).toPath() + } + + override fun documentName(document: String): String = + NSURL.URLWithString(document)?.lastPathComponent ?: "SDAI.sdaibackup" + + override fun documentLocation(document: String): String = + documentPath(document).toString() + + override fun newId(): String = NSUUID().UUIDString + + override fun openDocument(document: String) = + FileSystem.SYSTEM.source(checkNotNull(NSURL.URLWithString(document)?.path).toPath()) + .buffer() + + override fun writeDocument(document: String) = + FileSystem.SYSTEM.sink(checkNotNull(NSURL.URLWithString(document)?.path).toPath()).buffer() + + override fun availableBytes(): Long = + checkNotNull( + NSFileManager.defaultManager.attributesOfFileSystemForPath( + NSHomeDirectory(), + null + )?.get(NSFileSystemFreeSize) as? NSNumber + ) { "Could not inspect private storage" }.longLongValue +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index c72309b5c..9522598ff 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -17,6 +17,7 @@ lifecycleViewModel = "2.10.0" navigation = "2.9.8" gson = "2.15.0" okhttp = "5.4.0" +okio = "3.17.0" ktor = "3.5.0" koin = "4.2.1" koinCompose = "4.2.1" @@ -46,6 +47,7 @@ dokka = "2.3.0" detekt = "2.0.0-alpha.3" [libraries] +okio = { group = "com.squareup.okio", name = "okio", version.ref = "okio" } android-tools-build-gradle = { group = "com.android.tools.build", name = "gradle", version.ref = "agp" } kotlin-gradle-plugin = { group = "org.jetbrains.kotlin", name = "kotlin-gradle-plugin", version.ref = "kotlin" } apache-stringutils = { group = "org.apache.commons", name = "commons-lang3", version.ref = "apacheStringUtils" } diff --git a/presentation/app/build.gradle.kts b/presentation/app/build.gradle.kts index 5619fae95..dbbc3f1ec 100644 --- a/presentation/app/build.gradle.kts +++ b/presentation/app/build.gradle.kts @@ -24,6 +24,7 @@ kotlin { sourceSets { commonMain.dependencies { implementation(project(":presentation:benchmark")) + implementation(project(":presentation:backup")) implementation(project(":presentation:components")) implementation(project(":presentation:configuration")) implementation(project(":presentation:debug")) @@ -48,6 +49,7 @@ kotlin { implementation(project(":demo")) implementation(project(":network")) implementation(project(":feature:auth")) + implementation(project(":feature:backup")) implementation(project(":feature:benchmark")) implementation(project(":feature:work")) api(project(":feature:bonsai")) @@ -75,6 +77,8 @@ kotlin { implementation(libs.koin.android) } + androidUnitTest.dependencies { implementation(libs.test.junit) } + iosMain.dependencies { implementation(project(":feature:sdxl")) } diff --git a/presentation/app/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/app/BackupRouterSaverTest.kt b/presentation/app/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/app/BackupRouterSaverTest.kt new file mode 100644 index 000000000..0fa7cd91a --- /dev/null +++ b/presentation/app/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/app/BackupRouterSaverTest.kt @@ -0,0 +1,49 @@ +package com.shifthackz.aisdv1.presentation.app + +import androidx.compose.runtime.saveable.SaverScope +import com.shifthackz.aisdv1.core.navigation.AppRoute +import com.shifthackz.aisdv1.core.navigation.LaunchSource +import com.shifthackz.aisdv1.core.navigation.RootAppRouter +import org.junit.Assert.assertEquals +import org.junit.Test + +class BackupRouterSaverTest { + private val scope = object : SaverScope { + override fun canBeSaved(value: Any): Boolean = true + } + + private fun saved(router: RootAppRouter): String = + with(backupRouterSaver) { scope.save(router)!! } + + @Test + fun `given settings native backup picker, host route is saved and restored, expected backup callback destination and settings back route retained`() { + // Given + val router = RootAppRouter(AppRoute.Settings).also { it.navigateToBackup() } + // When + val restored = backupRouterSaver.restore(saved(router))!! + // Then + assertEquals(AppRoute.Backup(LaunchSource.SETTINGS), restored.route.value) + restored.navigateBack() + assertEquals(AppRoute.Settings, restored.route.value) + } + + @Test + fun `given initial restore route, host route is saved and restored, expected first launch mode retained`() { + // Given + val router = RootAppRouter(AppRoute.Backup(LaunchSource.SPLASH)) + // When + val restored = backupRouterSaver.restore(saved(router))!! + // Then + assertEquals(AppRoute.Backup(LaunchSource.SPLASH), restored.route.value) + } + + @Test + fun `given route with unrelated transient arguments, host route is saved, expected existing splash startup validation`() { + // Given + val router = RootAppRouter(AppRoute.TextToImage) + // When + val restored = backupRouterSaver.restore(saved(router))!! + // Then + assertEquals(AppRoute.Splash, restored.route.value) + } +} diff --git a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdApp.kt b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdApp.kt index b409df0fa..cb9acf8ac 100644 --- a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdApp.kt +++ b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdApp.kt @@ -19,6 +19,7 @@ import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier @@ -55,7 +56,7 @@ fun AiSdApp( val preferenceManager = remember(koin) { koin.get() } - val router = remember { RootAppRouter() } + val router = rememberSaveable(saver = backupRouterSaver) { RootAppRouter() } val route by router.route.collectAsState() val isDrawerOpen by router.drawerOpen.collectAsState() val canNavigateBack by router.canNavigateBack.collectAsState() diff --git a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdAppRoutes.kt b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdAppRoutes.kt index f87d8486b..67bda23aa 100644 --- a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdAppRoutes.kt +++ b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdAppRoutes.kt @@ -1,6 +1,13 @@ package com.shifthackz.aisdv1.presentation.app import com.shifthackz.aisdv1.presentation.home.AppScaffold +import com.shifthackz.aisdv1.core.navigation.LaunchSource +import com.shifthackz.aisdv1.presentation.backup.BackupScreen +import com.shifthackz.aisdv1.presentation.backup.BackupScreenMode +import com.shifthackz.aisdv1.presentation.backup.BackupViewModel +import com.shifthackz.aisdv1.presentation.backup.BackupIntent +import com.shifthackz.aisdv1.presentation.backup.BackupEffect +import com.shifthackz.aisdv1.presentation.backup.platform.rememberBackupDocumentLauncher import androidx.compose.runtime.getValue import androidx.compose.foundation.layout.Box @@ -226,6 +233,50 @@ internal fun OverlayRouteContent( AppRoute.Settings, -> Unit + AppRoute.BackupWelcome, is AppRoute.Backup -> { + val mode = when (route) { + AppRoute.BackupWelcome -> BackupScreenMode.WELCOME + is AppRoute.Backup -> if (route.source == LaunchSource.SPLASH) BackupScreenMode.FIRST_LAUNCH else BackupScreenMode.SETTINGS + } + val viewModel = remember(koin, router, mode) { + koin.get { + parametersOf( + mode, + router + ) + } + } + val launcher = rememberBackupDocumentLauncher( + onPicked = { viewModel.processIntent(BackupIntent.DocumentSelected(it)) }, + onExported = { destination, hasExported, handle -> + viewModel.processIntent( + BackupIntent.ExportFinished( + destination, + hasExported, + handle + ) + ) + }, + ) + DisposableEffect(viewModel) { onDispose { viewModel.onRouteDisposed() } } + RootBackHandler(enabled = true) { + if (mode != BackupScreenMode.WELCOME) viewModel.processIntent(BackupIntent.NavigateBack) + } + MviComponent(viewModel = viewModel, processEffect = { effect -> + when (effect) { + BackupEffect.OpenDocument -> launcher.open() + is BackupEffect.ExportDocument -> launcher.export(effect.backup) + } + }) { state, processIntent -> + BackupScreen( + mode, + state, + processIntent, + Modifier.fillMaxSize() + ) + } + } + AppRoute.StorageUsage -> { StorageUsageScreen( modifier = Modifier.fillMaxSize(), diff --git a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/BackupRouterSaver.kt b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/BackupRouterSaver.kt new file mode 100644 index 000000000..7198c8646 --- /dev/null +++ b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/BackupRouterSaver.kt @@ -0,0 +1,29 @@ +package com.shifthackz.aisdv1.presentation.app + +import androidx.compose.runtime.saveable.Saver +import com.shifthackz.aisdv1.core.navigation.AppRoute +import com.shifthackz.aisdv1.core.navigation.LaunchSource +import com.shifthackz.aisdv1.core.navigation.RootAppRouter + +/** + * Retains only nonsecret backup launch context so native document results reconnect after host recreation. + * Other routes retain the existing cold-start behavior and are rebuilt through startup validation. + * @author Dmitriy Moroz + */ +internal val backupRouterSaver = Saver( + save = { router -> + when (val route = router.route.value) { + is AppRoute.Backup -> if (route.source == LaunchSource.SPLASH) "initial" else "settings" + AppRoute.BackupWelcome -> "welcome" + else -> "splash" + } + }, + restore = { context -> + when (context) { + "initial" -> RootAppRouter(AppRoute.Backup(LaunchSource.SPLASH)) + "settings" -> RootAppRouter(AppRoute.Settings).also { it.navigateToBackup() } + "welcome" -> RootAppRouter(AppRoute.BackupWelcome) + else -> RootAppRouter() + } + } +) diff --git a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/di/AppCoreModule.kt b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/di/AppCoreModule.kt index 5a3e40e1c..8f114637b 100644 --- a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/di/AppCoreModule.kt +++ b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/di/AppCoreModule.kt @@ -43,6 +43,8 @@ import com.shifthackz.aisdv1.core.navigation.router.StorageUsageRouter import com.shifthackz.aisdv1.core.navigation.router.TextToImageRouter import com.shifthackz.aisdv1.core.navigation.router.WebUiRouter import com.shifthackz.aisdv1.core.mvi.diagnostics.uiDiagnosticsModule +import com.shifthackz.aisdv1.core.navigation.router.BackupRouter +import com.shifthackz.aisdv1.core.navigation.router.NoOpBackupRouter import org.koin.dsl.module /** @@ -52,6 +54,7 @@ import org.koin.dsl.module * @author Dmitriy Moroz */ val appCoreModule = module { + single { NoOpBackupRouter } includes(uiDiagnosticsModule(isEnabled = false)) single { DefaultLinksProvider } single { createPlatformBuildInfoProvider() } diff --git a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/di/KoinBootstrap.kt b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/di/KoinBootstrap.kt index 89e3f62af..3f95084cc 100644 --- a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/di/KoinBootstrap.kt +++ b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/di/KoinBootstrap.kt @@ -8,6 +8,7 @@ import com.shifthackz.aisdv1.demo.di.demoModule import com.shifthackz.aisdv1.domain.di.coreDomainModule import com.shifthackz.aisdv1.domain.di.benchmarkUseCaseModule import com.shifthackz.aisdv1.feature.auth.di.authModule +import com.shifthackz.aisdv1.feature.backup.di.backupModule import com.shifthackz.aisdv1.feature.benchmark.di.benchmarkModule import com.shifthackz.aisdv1.feature.bonsai.di.bonsaiModule import com.shifthackz.aisdv1.feature.coreml.di.coreMlModule @@ -26,9 +27,22 @@ import com.shifthackz.aisdv1.domain.preference.PreferenceManager * @author Dmitriy Moroz */ internal val commonApplicationModules = listOf( - coreNetworkModule, networkModule, validatorsModule, coreDomainModule, benchmarkUseCaseModule, - coreDataModule, *dataModule, demoModule, authModule, benchmarkModule, bonsaiModule, - coreMlModule, mnnHostRuntimeModule, backgroundWorkModule, corePresentationModule, + coreNetworkModule, + networkModule, + validatorsModule, + coreDomainModule, + benchmarkUseCaseModule, + coreDataModule, + *dataModule, + demoModule, + authModule, + backupModule, + benchmarkModule, + bonsaiModule, + coreMlModule, + mnnHostRuntimeModule, + backgroundWorkModule, + corePresentationModule, ) /** 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 fa243edaa..e57d94574 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 @@ -22,6 +22,7 @@ import com.shifthackz.aisdv1.presentation.generation.di.generationCoreModule import com.shifthackz.aisdv1.presentation.generation.di.generationViewModelModule import com.shifthackz.aisdv1.presentation.debug.di.debugCoreModule import com.shifthackz.aisdv1.presentation.debug.di.debugViewModelModule +import com.shifthackz.aisdv1.presentation.backup.di.backupViewModelModule import org.koin.dsl.module /** @@ -31,6 +32,7 @@ import org.koin.dsl.module */ val corePresentationModule = module { includes( + backupViewModelModule, benchmarkCoreModule, benchmarkViewModelModule, statisticsViewModelModule, diff --git a/presentation/backup/build.gradle.kts b/presentation/backup/build.gradle.kts new file mode 100644 index 000000000..a34ef374e --- /dev/null +++ b/presentation/backup/build.gradle.kts @@ -0,0 +1,57 @@ +plugins { + alias(libs.plugins.generic.kmp.compose) +} + +compose.resources { + packageOfResClass = "com.shifthackz.aisdv1.presentation.backup.generated.resources" +} + +android { + namespace = "com.shifthackz.aisdv1.presentation.backup" + testOptions.unitTests { + all { test -> + test.jvmArgs( + "--add-opens", "java.base/java.lang=ALL-UNNAMED", + "--add-opens", "java.base/java.lang.reflect=ALL-UNNAMED" + ) + } + isReturnDefaultValues = true + } +} + +kotlin { + sourceSets { + commonMain.dependencies { + implementation(project(":core:common")) + implementation(project(":core:localization")) + implementation(project(":core:ui")) + implementation(project(":domain")) + implementation(project(":presentation:components")) + implementation(compose.runtime) + implementation(compose.components.resources) + implementation(compose.ui) + implementation(compose.foundation) + implementation(compose.animation) + implementation(compose.material3) + implementation(compose.materialIconsExtended) + implementation(libs.androidx.lifecycle.compose) + implementation(libs.kotlinx.coroutines.core) + implementation(libs.koin.core) + } + + androidMain.dependencies { implementation(libs.androidx.compose.activity) } + androidUnitTest.dependencies { + implementation(libs.test.junit) + implementation(libs.test.mockk) + implementation(libs.test.coroutines) + } + } +} + +// Reports describe compiler stability/skipping decisions; they do not measure frame performance. +composeCompiler { + if (providers.gradleProperty("sdaiComposeReports").orNull == "true") { + metricsDestination.set(layout.buildDirectory.dir("compose-metrics")) + reportsDestination.set(layout.buildDirectory.dir("compose-reports")) + } +} diff --git a/presentation/backup/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/backup/platform/BackupDateFormatter.android.kt b/presentation/backup/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/backup/platform/BackupDateFormatter.android.kt new file mode 100644 index 000000000..ad9946d50 --- /dev/null +++ b/presentation/backup/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/backup/platform/BackupDateFormatter.android.kt @@ -0,0 +1,12 @@ +package com.shifthackz.aisdv1.presentation.backup.platform + +import java.text.DateFormat +import java.util.Date + +/** + * Formats a UTC timestamp using the current platform locale and date/time conventions. + * @param epochMillis Archive creation time in milliseconds since the Unix epoch. + * @author Dmitriy Moroz + */ +internal actual fun formatBackupCreatedAt(epochMillis: Long): String = + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(Date(epochMillis)) diff --git a/presentation/backup/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/backup/platform/BackupDocumentLauncher.android.kt b/presentation/backup/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/backup/platform/BackupDocumentLauncher.android.kt new file mode 100644 index 000000000..55fb4a942 --- /dev/null +++ b/presentation/backup/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/backup/platform/BackupDocumentLauncher.android.kt @@ -0,0 +1,50 @@ +package com.shifthackz.aisdv1.presentation.backup.platform + +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import com.shifthackz.aisdv1.domain.entity.backup.BackupExport + +/** + * Uses Android Storage Access Framework without broad storage permissions or retained external ownership. + * @param onPicked Receives a read-granted document URI or neutral cancellation. + * @param onExported Receives a destination URI; file writing remains a domain operation. + * @author Dmitriy Moroz + */ +@Composable +actual fun rememberBackupDocumentLauncher( + onPicked: (String?) -> Unit, + onExported: (String?, Boolean, String) -> Unit +): BackupDocumentLauncher { + val picked = rememberUpdatedState(onPicked) + val exported = rememberUpdatedState(onExported) + var exportHandle by rememberSaveable { mutableStateOf("") } + val open = + rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { picked.value(it?.toString()) } + val save = + rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/octet-stream")) { + exported.value( + it?.toString(), + false, + exportHandle + ) + } + return remember(open, save) { + object : BackupDocumentLauncher { + override fun open() { + open.launch(arrayOf("application/octet-stream", "*/*")) + } + + override fun export(backup: BackupExport) { + exportHandle = backup.handle + save.launch(backup.filename) + } + } + } +} diff --git a/presentation/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupPagerInteractionTest.kt b/presentation/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupPagerInteractionTest.kt new file mode 100644 index 000000000..03aae0bc3 --- /dev/null +++ b/presentation/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupPagerInteractionTest.kt @@ -0,0 +1,89 @@ +package com.shifthackz.aisdv1.presentation.backup + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class BackupPagerInteractionTest { + @Test + fun `given create page, vertical scroll has no horizontal displacement, expected action remains available`() { + // Given + val selectedPage = 0 + // When + val canInteract = canInteractWithBackupPage(selectedPage, 0, 0f) + // Then + assertTrue(canInteract) + } + + @Test + fun `given create page, incidental swipe stays below forty percent, expected action remains available`() { + // Given + val offsets = listOf(0.001f, 0.1f, 0.3999f) + // When + val availability = offsets.map { canInteractWithBackupPage(0, 0, it) } + // Then + assertTrue(availability.all { it }) + } + + @Test + fun `given create page, swipe reaches forty percent, expected action pauses`() { + // Given + val offset = 0.4f + // When + val canInteract = canInteractWithBackupPage(0, 0, offset) + // Then + assertFalse(canInteract) + } + + @Test + fun `given create page still selected, nearest page flips during swipe, expected original action stays paused`() { + // Given + val newNearestPage = 1 + // When + val canInteract = canInteractWithBackupPage(0, newNearestPage, -0.49f) + // Then + assertFalse(canInteract) + } + + @Test + fun `given restore page, reverse swipe stays below forty percent, expected action remains available`() { + // Given + val offsets = listOf(-0.001f, -0.1f, -0.3999f) + // When + val availability = offsets.map { canInteractWithBackupPage(1, 1, it) } + // Then + assertTrue(availability.all { it }) + } + + @Test + fun `given restore page, reverse swipe reaches forty percent, expected action pauses`() { + // Given + val offset = -0.4f + // When + val canInteract = canInteractWithBackupPage(1, 1, offset) + // Then + assertFalse(canInteract) + } + + @Test + fun `given restore page still selected, nearest page flips on reverse swipe, expected original action stays paused`() { + // Given + val newNearestPage = 0 + // When + val canInteract = canInteractWithBackupPage(1, newNearestPage, 0.49f) + // Then + assertFalse(canInteract) + } + + @Test + fun `given restore tab chosen, animation approaches selected page, expected action returns inside forty percent`() { + // Given + val selectedPage = 1 + // When + val isPaused = !canInteractWithBackupPage(selectedPage, 0, 0f) + val canInteract = canInteractWithBackupPage(selectedPage, 1, -0.3f) + // Then + assertTrue(isPaused) + assertTrue(canInteract) + } +} diff --git a/presentation/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupViewModelTest.kt b/presentation/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupViewModelTest.kt new file mode 100644 index 000000000..b55ddedcf --- /dev/null +++ b/presentation/backup/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupViewModelTest.kt @@ -0,0 +1,684 @@ +package com.shifthackz.aisdv1.presentation.backup + +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import com.shifthackz.aisdv1.core.navigation.router.BackupRouter +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.entity.backup.BackupEntry +import com.shifthackz.aisdv1.domain.entity.backup.BackupExport +import com.shifthackz.aisdv1.domain.entity.backup.BackupInspection +import com.shifthackz.aisdv1.domain.entity.backup.BackupRestoreResult +import com.shifthackz.aisdv1.domain.entity.backup.BackupRestoreRequest +import com.shifthackz.aisdv1.domain.entity.backup.BackupProgress +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage +import com.shifthackz.aisdv1.domain.usecase.backup.CreateBackupUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.InspectBackupUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.RestoreBackupUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.ObserveBackupExportUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.CompleteBackupExportUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.CancelBackupExportUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.DismissBackupExportUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.GetBackupStartupStageUseCase +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportOperation +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportStatus +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportCompletion +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.CompletableDeferred +import com.shifthackz.aisdv1.domain.usecase.backup.DiscardBackupUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.LoadBackupInventoryUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.LoadPendingBackupUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.SetBackupStartupStageUseCase +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.setMain +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class BackupViewModelTest { + private val router = mockk(relaxed = true) + private val inventory = mockk() + private val create = mockk() + private val inspect = mockk() + private val restore = mockk() + private val exportState = MutableStateFlow(BackupExportOperation()) + private val observeExport = + mockk { every { this@mockk.invoke() } returns exportState } + private val completeExport = mockk(relaxed = true) + private val cancelExport = mockk(relaxed = true) + private val dismissExport = mockk(relaxed = true) + private val getStage = + mockk { every { this@mockk.invoke() } returns BackupStartupStage.RESTORE } + private val discard = mockk(relaxed = true) + private val pending = mockk() + private val startup = mockk(relaxed = true) + private val summary = BackupInspection( + "11111111-1111-1111-1111-111111111111", + 100, + "1", + "IOS", + listOf(BackupEntry(BackupCategory.GALLERY, 2), BackupEntry(BackupCategory.SETTINGS, 1)), + emptySet() + ) + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + private fun TestScope.viewModel( + mode: BackupScreenMode = BackupScreenMode.SETTINGS, + shouldUseImmediateDispatcher: Boolean = false, + ): BackupViewModel { + val dispatcher = + if (shouldUseImmediateDispatcher) UnconfinedTestDispatcher(testScheduler) else StandardTestDispatcher( + testScheduler + ) + Dispatchers.setMain(dispatcher) + coEvery { pending() } returns null + coEvery { inventory() } returns summary + val dispatchers = + mockk { every { io } returns dispatcher; every { immediate } returns dispatcher } + return BackupViewModel( + mode, + router, + mockk(relaxed = true), + dispatchers, + inventory, + create, + inspect, + restore, + observeExport, + completeExport, + cancelExport, + dismissExport, + getStage, + discard, + pending, + startup + ) + } + + @Test + fun `given backup tabs, selection changes before switching twice, expected create selection retained`() = + runTest { + // Given + val vm = viewModel() + advanceUntilIdle() + // When + vm.processIntent(BackupIntent.ToggleCategory(BackupCategory.GALLERY)) + vm.processIntent(BackupIntent.SelectTab(true)) + vm.processIntent(BackupIntent.SelectTab(false)) + // Then + assertEquals(setOf(BackupCategory.SETTINGS), vm.state.value.create.selection.categories) + assertFalse(vm.state.value.isRestoreTab) + } + + @Test + fun `given restore file picker, user cancels document selection, expected neutral state without inspection`() = + runTest { + // Given + val vm = viewModel() + advanceUntilIdle() + vm.processIntent(BackupIntent.SelectTab(true)) + vm.processIntent(BackupIntent.ChooseFile) + advanceUntilIdle() + // When + vm.processIntent(BackupIntent.DocumentSelected(null)) + advanceUntilIdle() + // Then + assertFalse(vm.state.value.isPicking) + assertFalse(vm.state.value.hasError) + assertNull(vm.state.value.restore.inspection) + coVerify(exactly = 0) { inspect(any(), any()) } + } + + @Test + fun `given first launch invitation, user continues, expected configuration stage and route`() = + runTest { + // Given + val vm = viewModel(BackupScreenMode.WELCOME) + // When + vm.processIntent(BackupIntent.Continue) + advanceUntilIdle() + // Then + verify { startup(BackupStartupStage.CONFIGURATION); router.navigateToInitialConfiguration() } + verify(exactly = 0) { router.navigateBack() } + } + + @Test + fun `given first launch restore screen, user cancels decision, expected configuration without returning onboarding`() = + runTest { + // Given + val vm = viewModel(BackupScreenMode.FIRST_LAUNCH) + advanceUntilIdle() + // When + vm.processIntent(BackupIntent.NavigateBack) + advanceUntilIdle() + // Then + verify { startup(BackupStartupStage.CONFIGURATION); router.navigateToInitialConfiguration() } + verify(exactly = 0) { router.navigateBack() } + } + + @Test + fun `given staged export, coordinator reports write failure, expected error without saved success`() = + runTest { + // Given + val vm = viewModel() + coEvery { create(any(), any()) } returns BackupExport( + "file:///private/archive", + "backup.sdaibackup", + "export" + ) + + advanceUntilIdle() + vm.processIntent(BackupIntent.Submit) + advanceUntilIdle() + // When + vm.processIntent(BackupIntent.ExportFinished("content://destination", false, "export")) + advanceUntilIdle() + exportState.value = BackupExportOperation(BackupExportStatus.FAILED) + advanceUntilIdle() + // Then + assertTrue(vm.state.value.hasError) + assertFalse(vm.state.value.hasExported) + verify { + completeExport( + BackupExportCompletion.DestinationSelected( + "content://destination", + "export" + ) + ) + } + coVerify(exactly = 0) { discard(any()) } + } + + @Test + fun `given restore conflict dialog, user cancels replacement, expected editable selection and no success`() = + runTest { + // Given + val vm = viewModel() + coEvery { inspect(any(), any()) } returns summary + coEvery { restore(any(), any()) } returns BackupRestoreResult.Conflict( + setOf("custom"), + "fingerprint" + ) + advanceUntilIdle() + vm.processIntent(BackupIntent.SelectTab(true)) + vm.processIntent(BackupIntent.DocumentSelected("content://backup")) + advanceUntilIdle() + vm.processIntent(BackupIntent.Submit) + advanceUntilIdle() + // When + vm.processIntent(BackupIntent.DismissConflict) + vm.processIntent(BackupIntent.ToggleCategory(BackupCategory.GALLERY)) + // Then + assertNull(vm.state.value.conflict) + assertEquals( + setOf(BackupCategory.SETTINGS), + vm.state.value.restore.selection.categories + ) + assertNull(vm.state.value.result) + } + + @Test + fun `given first launch restore, user acknowledges successful result, expected restored setup flow`() = + runTest { + // Given + val vm = viewModel(BackupScreenMode.FIRST_LAUNCH) + coEvery { inspect(any(), any()) } returns summary + coEvery { restore(any(), any()) } returns BackupRestoreResult.Finished( + setOf( + BackupCategory.GALLERY, + BackupCategory.SETTINGS + ), 0, false + ) + advanceUntilIdle() + vm.processIntent(BackupIntent.DocumentSelected("content://backup")) + advanceUntilIdle() + vm.processIntent(BackupIntent.Submit) + advanceUntilIdle() + assertTrue(vm.state.value.isFeedbackVisible) + verify(exactly = 0) { router.navigateToInitialConfiguration() } + // When + vm.processIntent(BackupIntent.DismissFeedback) + advanceUntilIdle() + // Then + verify { startup(BackupStartupStage.CONFIGURATION); router.navigateToInitialConfiguration() } + coVerify { discard(summary.handle) } + verify(exactly = 0) { router.navigateBack() } + } + + @Test + fun `given retained failed export, screen initializes on immediate dispatcher, expected failure feedback retained`() = + runTest { + // Given + exportState.value = BackupExportOperation( + BackupExportStatus.FAILED, + BackupExport("source", "name", "handle") + ) + + // When + val vm = viewModel(shouldUseImmediateDispatcher = true) + advanceUntilIdle() + + // Then + assertTrue(vm.state.value.hasError) + assertTrue(vm.state.value.isFeedbackVisible) + assertFalse(vm.state.value.isBusy) + vm.onRouteDisposed() + } + + @Test + fun `given retained canceled export, screen initializes on immediate dispatcher, expected cancellation feedback retained`() = + runTest { + // Given + exportState.value = BackupExportOperation( + BackupExportStatus.CANCELED, + BackupExport("source", "name", "handle") + ) + + // When + val vm = viewModel(shouldUseImmediateDispatcher = true) + advanceUntilIdle() + + // Then + assertTrue(vm.state.value.hasCanceled) + assertTrue(vm.state.value.isFeedbackVisible) + assertFalse(vm.state.value.isBusy) + vm.onRouteDisposed() + } + + @Test + fun `given failed backup inspection, user acknowledges error, expected file selection remains available`() = + runTest { + // Given + val vm = viewModel() + coEvery { inspect(any(), any()) } throws IllegalArgumentException("Invalid archive") + advanceUntilIdle() + vm.processIntent(BackupIntent.DocumentSelected("content://invalid")) + advanceUntilIdle() + assertTrue(vm.state.value.isFeedbackVisible) + assertTrue(vm.state.value.hasError) + + // When + vm.processIntent(BackupIntent.DismissFeedback) + advanceUntilIdle() + + // Then + assertFalse(vm.state.value.isFeedbackVisible) + assertFalse(vm.state.value.isBusy) + assertNull(vm.state.value.restore.inspection) + verify(exactly = 0) { router.navigateBack(); router.navigateToInitialConfiguration() } + vm.onRouteDisposed() + } + + @Test + fun `given partial restore result, user acknowledges failure, expected journal selection retained for retry`() = + runTest { + // Given + val vm = viewModel() + coEvery { inspect(any(), any()) } returns summary + val result = BackupRestoreResult.Finished(setOf(BackupCategory.GALLERY), 0, true) + coEvery { restore(any(), any()) } returns result + advanceUntilIdle() + vm.processIntent(BackupIntent.SelectTab(true)) + vm.processIntent(BackupIntent.DocumentSelected("content://backup")) + advanceUntilIdle() + vm.processIntent(BackupIntent.Submit) + advanceUntilIdle() + + // When + vm.processIntent(BackupIntent.DismissFeedback) + advanceUntilIdle() + + // Then + assertFalse(vm.state.value.isFeedbackVisible) + assertEquals(result, vm.state.value.result) + assertTrue(vm.state.value.hasPendingSession) + assertTrue(vm.state.value.isRestoreSelectionLocked) + coVerify(exactly = 0) { discard(any()) } + vm.onRouteDisposed() + } + + @Test + fun `given inspected backup with custom selection, next picker is canceled, expected original file and choices retained`() = + runTest { + // Given + val vm = viewModel() + coEvery { inspect(any(), any()) } returns summary + advanceUntilIdle() + vm.processIntent(BackupIntent.SelectTab(true)) + vm.processIntent(BackupIntent.DocumentSelected("content://original")) + advanceUntilIdle() + vm.processIntent(BackupIntent.ToggleCategory(BackupCategory.GALLERY)) + // When + vm.processIntent(BackupIntent.ChooseFile) + advanceUntilIdle() + vm.processIntent(BackupIntent.DocumentSelected(null)) + advanceUntilIdle() + // Then + assertEquals(summary, vm.state.value.restore.inspection) + assertEquals( + setOf(BackupCategory.SETTINGS), + vm.state.value.restore.selection.categories + ) + coVerify(exactly = 0) { discard(any()) } + } + + @Test + fun `given recreated backup route, native callback arrives before initialization completes, expected result queued without dropping destination`() = + runTest { + // Given + val vm = viewModel() + val initialization = CompletableDeferred() + every { completeExport(any()) } answers { + exportState.value = BackupExportOperation(BackupExportStatus.PROCESSING) + } + coEvery { pending() } coAnswers { initialization.await(); null } + // When + vm.processIntent( + BackupIntent.ExportFinished( + "content://destination", + false, + "durable-export" + ) + ) + advanceUntilIdle() + // Then + verify(exactly = 1) { + completeExport( + BackupExportCompletion.DestinationSelected( + "content://destination", + "durable-export" + ) + ) + } + assertTrue(vm.state.value.isExporting) + initialization.complete(Unit) + advanceUntilIdle() + vm.onRouteDisposed() + } + + @Test + fun `given reconstructed first launch route, recovery acknowledged configuration, expected direct setup navigation`() = + runTest { + // Given + every { getStage() } returns BackupStartupStage.CONFIGURATION + // When + val vm = viewModel(BackupScreenMode.FIRST_LAUNCH) + advanceUntilIdle() + // Then + verify(exactly = 1) { router.navigateToInitialConfiguration() } + coVerify(exactly = 0) { inventory(); restore(any(), any()) } + vm.onRouteDisposed() + } + + @Test + fun `given recreated export route, durable copy is running, expected editing disabled and source retained on disposal`() = + runTest { + // Given + exportState.value = BackupExportOperation( + BackupExportStatus.COPYING, + BackupExport("source", "name", "handle") + ) + val vm = viewModel() + advanceUntilIdle() + val original = vm.state.value.create.selection + // When + vm.processIntent(BackupIntent.ToggleCategory(BackupCategory.GALLERY)) + vm.onRouteDisposed() + // Then + assertEquals(original, vm.state.value.create.selection) + assertTrue(vm.state.value.isExporting) + verify(exactly = 0) { cancelExport() } + coVerify(exactly = 0) { dismissExport(); discard(any()) } + } + + @Test + fun `given recreated import picker, document arrives during initialization, expected queued inspection and visible Restore tab`() = + runTest { + // Given + val vm = viewModel() + val initialized = CompletableDeferred() + coEvery { pending() } coAnswers { initialized.await(); null } + coEvery { inspect("content://restored-result", any()) } returns summary + runCurrent() + // When + vm.processIntent(BackupIntent.DocumentSelected("content://restored-result")) + runCurrent() + // Then + coVerify(exactly = 0) { inspect(any(), any()) } + assertTrue(vm.state.value.isPicking) + initialized.complete(Unit) + advanceUntilIdle() + coVerify(exactly = 1) { inspect("content://restored-result", any()) } + assertTrue(vm.state.value.isRestoreTab) + assertEquals(summary, vm.state.value.restore.inspection) + assertFalse(vm.state.value.isPicking) + vm.onRouteDisposed() + } + + @Test + fun `given reconstructed first launch route, setup has already completed before handoff acknowledgment, expected home without empty restore screen`() = + runTest { + // Given + every { getStage() } returns BackupStartupStage.COMPLETE + // When + val vm = viewModel(BackupScreenMode.FIRST_LAUNCH) + advanceUntilIdle() + // Then + verify(exactly = 1) { router.navigateToHomeScreen() } + verify(exactly = 0) { startup(any()); router.navigateToInitialConfiguration() } + vm.onRouteDisposed() + } + + @Test + fun `given provider child choices, last child is unchecked then another selected, expected parent category follows child selection`() = + runTest { + // Given + val vm = viewModel() + coEvery { inventory() } returns summary.copy( + entries = listOf( + BackupEntry( + BackupCategory.PROVIDERS, + 2 + ) + ), providers = setOf("custom", "swarm_ui") + ) + advanceUntilIdle() + // When + vm.processIntent(BackupIntent.ToggleProvider("custom")) + vm.processIntent(BackupIntent.ToggleProvider("swarm_ui")) + val empty = vm.state.value.create.selection + vm.processIntent(BackupIntent.ToggleProvider("swarm_ui")) + // Then + assertTrue(empty.categories.isEmpty()) + assertTrue(empty.providers.isEmpty()) + assertEquals( + setOf(BackupCategory.PROVIDERS), + vm.state.value.create.selection.categories + ) + assertEquals(setOf("swarm_ui"), vm.state.value.create.selection.providers) + vm.onRouteDisposed() + } + + @Test + fun `given expanded create providers, user collapses then switches tabs, expected independent expansion and retained selection`() = + runTest { + // Given + val vm = viewModel() + advanceUntilIdle() + val original = vm.state.value.create.selection + // When + vm.processIntent(BackupIntent.ToggleProvidersExpanded) + val isCreateExpanded = vm.state.value.create.areProvidersExpanded + vm.processIntent(BackupIntent.SelectTab(true)) + vm.processIntent(BackupIntent.ToggleProvidersExpanded) + vm.processIntent(BackupIntent.SelectTab(false)) + // Then + assertEquals(isCreateExpanded, vm.state.value.create.areProvidersExpanded) + assertEquals(original, vm.state.value.create.selection) + vm.onRouteDisposed() + } + + @Test + fun `given provider replacement conflict, user confirms, expected same session and exact consent fingerprint`() = + runTest { + // Given + val vm = viewModel() + coEvery { inspect(any(), any()) } returns summary + val requests = mutableListOf() + coEvery { restore(any(), any()) } answers { + requests += firstArg() + if (requests.size == 1) BackupRestoreResult.Conflict(setOf("custom"), "revision") + else BackupRestoreResult.Finished(setOf(BackupCategory.GALLERY), 0, false) + } + advanceUntilIdle() + vm.processIntent(BackupIntent.DocumentSelected("source")) + advanceUntilIdle() + vm.processIntent(BackupIntent.Submit) + advanceUntilIdle() + // When + vm.processIntent(BackupIntent.ConfirmProviderReplacement) + advanceUntilIdle() + // Then + assertEquals(2, requests.size) + assertEquals(requests.first().sessionId, requests.last().sessionId) + assertEquals("revision", requests.last().confirmedFingerprint) + assertNull(vm.state.value.conflict) + assertTrue(vm.state.value.isFeedbackVisible) + vm.onRouteDisposed() + } + + @Test + fun `given failed partial restore, user edits then retries, expected original locked selection and session reused`() = + runTest { + // Given + val vm = viewModel() + coEvery { inspect(any(), any()) } returns summary + val requests = mutableListOf() + coEvery { restore(any(), any()) } answers { + requests += firstArg() + BackupRestoreResult.Finished(setOf(BackupCategory.GALLERY), 0, true) + } + advanceUntilIdle() + vm.processIntent(BackupIntent.DocumentSelected("source")) + advanceUntilIdle() + vm.processIntent(BackupIntent.Submit) + advanceUntilIdle() + // When + vm.processIntent(BackupIntent.DismissFeedback) + vm.processIntent(BackupIntent.ToggleCategory(BackupCategory.GALLERY)) + vm.processIntent(BackupIntent.Submit) + advanceUntilIdle() + // Then + assertEquals(2, requests.size) + assertEquals(requests.first(), requests.last()) + assertTrue(vm.state.value.hasPendingSession) + vm.onRouteDisposed() + } + + @Test + fun `given backup creation failure, user submits selected data, expected failure dialog state without picker`() = + runTest { + // Given + val vm = viewModel() + coEvery { create(any(), any()) } throws IllegalStateException("full disk") + advanceUntilIdle() + // When + vm.processIntent(BackupIntent.Submit) + advanceUntilIdle() + // Then + assertTrue(vm.state.value.hasError) + assertTrue(vm.state.value.isFeedbackVisible) + assertFalse(vm.state.value.isPicking) + assertFalse(vm.state.value.isBusy) + assertFalse(vm.state.value.hasExported) + vm.onRouteDisposed() + } + + @Test + fun `given selected valid archive, replacement inspection fails, expected original file and selection retained`() = + runTest { + // Given + val vm = viewModel() + coEvery { inspect("original", any()) } returns summary + coEvery { inspect("invalid", any()) } throws IllegalArgumentException("bad archive") + advanceUntilIdle() + vm.processIntent(BackupIntent.DocumentSelected("original")) + advanceUntilIdle() + vm.processIntent(BackupIntent.ToggleCategory(BackupCategory.GALLERY)) + val original = vm.state.value.restore + // When + vm.processIntent(BackupIntent.DocumentSelected("invalid")) + advanceUntilIdle() + // Then + assertEquals(original, vm.state.value.restore) + assertTrue(vm.state.value.hasError) + coVerify(exactly = 0) { discard(any()) } + vm.onRouteDisposed() + } + + @Test + fun `given running restore, progress is reported then user cancels, expected canceled feedback and cleared busy state`() = + runTest { + // Given + val vm = viewModel() + val running = CompletableDeferred() + coEvery { inspect(any(), any()) } returns summary + coEvery { restore(any(), any()) } coAnswers { + secondArg<(BackupProgress) -> Unit>()(BackupProgress(BackupCategory.GALLERY, 1, 2)) + running.await() + BackupRestoreResult.Finished(emptySet(), 0, false) + } + advanceUntilIdle() + vm.processIntent(BackupIntent.DocumentSelected("source")) + advanceUntilIdle() + vm.processIntent(BackupIntent.Submit) + runCurrent() + assertTrue(vm.state.value.isBusy) + assertEquals(1L, vm.state.value.progress?.completed) + // When + vm.processIntent(BackupIntent.CancelWork) + advanceUntilIdle() + // Then + assertTrue(vm.state.value.hasCanceled) + assertTrue(vm.state.value.isFeedbackVisible) + assertFalse(vm.state.value.isBusy) + assertNull(vm.state.value.progress) + verify { cancelExport() } + vm.onRouteDisposed() + } + + @Test + fun `given first launch invitation, durable stage write fails, expected feedback and no navigation`() = + runTest { + // Given + val vm = viewModel(BackupScreenMode.WELCOME) + every { startup(any()) } throws IllegalStateException("storage unavailable") + // When + vm.processIntent(BackupIntent.BeginInitialRestore) + advanceUntilIdle() + // Then + assertTrue(vm.state.value.hasError) + assertTrue(vm.state.value.isFeedbackVisible) + verify(exactly = 0) { router.navigateToInitialRestore() } + vm.onRouteDisposed() + } +} diff --git a/presentation/backup/src/commonMain/composeResources/drawable/backup_welcome.png b/presentation/backup/src/commonMain/composeResources/drawable/backup_welcome.png new file mode 100644 index 000000000..d10c0c17b Binary files /dev/null and b/presentation/backup/src/commonMain/composeResources/drawable/backup_welcome.png differ diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupEffect.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupEffect.kt new file mode 100644 index 000000000..16f7a811e --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupEffect.kt @@ -0,0 +1,20 @@ +package com.shifthackz.aisdv1.presentation.backup + +import com.shifthackz.aisdv1.core.mvi.MviEffect +import com.shifthackz.aisdv1.domain.entity.backup.BackupExport + +/** + * Lifecycle-aware requests for native document pickers. + * @author Dmitriy Moroz + */ +sealed interface BackupEffect : MviEffect { + /** Opens the system document picker without discarding the previous file. @author Dmitriy Moroz */ + data object OpenDocument : BackupEffect + + /** + * Presents native export after a complete binary archive has been staged. + * @param backup Private document reference and suggested filename. + * @author Dmitriy Moroz + */ + data class ExportDocument(val backup: BackupExport) : BackupEffect +} diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupIntent.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupIntent.kt new file mode 100644 index 000000000..66d546695 --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupIntent.kt @@ -0,0 +1,111 @@ +package com.shifthackz.aisdv1.presentation.backup + +import com.shifthackz.aisdv1.core.mvi.MviIntent +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory + +/** + * Explicit backup actions and native document results; no action contains decoded archive data. + * @author Dmitriy Moroz + */ +sealed interface BackupIntent : MviIntent { + /** + * Returns to Settings or mandatory first-launch configuration after resolving staged ownership. + * @author Dmitriy Moroz + */ + data object NavigateBack : BackupIntent + + /** + * Consumes the first-launch invitation and proceeds through provider configuration. + * @author Dmitriy Moroz + */ + data object Continue : BackupIntent + + /** + * Opens restore-only content while persisting first-launch recovery progression. + * @author Dmitriy Moroz + */ + data object BeginInitialRestore : BackupIntent + + /** + * Changes visible tab while retaining each page selection. + * @param isRestore Whether the Restore tab should be selected. + * @author Dmitriy Moroz + */ + data class SelectTab(val isRestore: Boolean) : BackupIntent + + /** + * Changes one available category selection. + * @param category Stable category represented by the checklist row. + * @author Dmitriy Moroz + */ + data class ToggleCategory(val category: BackupCategory) : BackupIntent + + /** + * Changes one supported provider child selection. + * @param key Stable provider wire identifier. + * @author Dmitriy Moroz + */ + data class ToggleProvider(val key: String) : BackupIntent + + /** + * Expands or collapses provider choices without changing selection. + * @author Dmitriy Moroz + */ + data object ToggleProvidersExpanded : BackupIntent + + /** + * Opens a native picker while retaining the previous inspection until a new selection succeeds. + * @author Dmitriy Moroz + */ + data object ChooseFile : BackupIntent + + /** + * Starts export or submits the selected restore plan with its current retry identity. + * @author Dmitriy Moroz + */ + data object Submit : BackupIntent + + /** + * Confirms only the current displayed conflict fingerprint; changed destination values require renewed consent. + * @author Dmitriy Moroz + */ + data object ConfirmProviderReplacement : BackupIntent + + /** + * Cancels replacement before any category mutation and returns to editable selection. + * @author Dmitriy Moroz + */ + data object DismissConflict : BackupIntent + + /** + * Acknowledges feedback without clearing retry state; successful first-launch restore proceeds to setup. + * @author Dmitriy Moroz + */ + data object DismissFeedback : BackupIntent + + /** + * Cancels active bounded work; already committed categories remain journal-owned. + * @author Dmitriy Moroz + */ + data object CancelWork : BackupIntent + + /** + * Delivers a native import result; null is neutral picker cancellation. + * @param document Opaque native source reference or null. + * @author Dmitriy Moroz + */ + data class DocumentSelected(val document: String?) : BackupIntent + + /** + * Delivers a destination or completed UIKit export; neither means cancellation. + * @param destination Android write-granted output reference, or null on iOS/cancel. + * @param hasExported Whether UIKit confirmed completed native export. + * @param handle Nonsecret staged identity saved by the launcher across host recreation. + * @author Dmitriy Moroz + */ + data class ExportFinished( + val destination: String?, + val hasExported: Boolean, + val handle: String + ) : BackupIntent +} diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupPageContent.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupPageContent.kt new file mode 100644 index 000000000..2969fe0cb --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupPageContent.kt @@ -0,0 +1,42 @@ +package com.shifthackz.aisdv1.presentation.backup + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.shifthackz.aisdv1.presentation.backup.create.CreateBackupScreen +import com.shifthackz.aisdv1.presentation.backup.restore.RestoreBackupScreen +import com.shifthackz.aisdv1.presentation.components.widget.scrollbar.verticalScrollbar + +/** + * Keeps each pager page's vertical scroll independent while reusing dedicated create/restore content. + * @param isRestore Whether this page selects and restores an existing backup. + * @param page Independent inventory and checkbox selection for the displayed operation. + * @param isEnabled Whether native document and selection actions can currently run. + * @param canEditSelection Whether an owned staged operation still permits editing its selection. + * @param processIntent Caller-owned selection and file actions. + * @param modifier Placement within the pager or first-launch content area. + * @author Dmitriy Moroz + */ +@Composable +internal fun BackupPageContent( + isRestore: Boolean, + page: BackupPageState, + isEnabled: Boolean, + canEditSelection: Boolean, + processIntent: (BackupIntent) -> Unit, + modifier: Modifier = Modifier, +) { + val scrollState = rememberScrollState() + Column( + modifier.fillMaxSize().verticalScrollbar(scrollState).verticalScroll(scrollState) + .padding(16.dp) + ) { + if (isRestore) RestoreBackupScreen(page, isEnabled, canEditSelection, processIntent) + else CreateBackupScreen(page, isEnabled && canEditSelection, processIntent) + } +} diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupPageState.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupPageState.kt new file mode 100644 index 000000000..08cda1068 --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupPageState.kt @@ -0,0 +1,17 @@ +package com.shifthackz.aisdv1.presentation.backup + +import com.shifthackz.aisdv1.domain.entity.backup.BackupInspection +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection + +/** + * Independent tab inventory and selection; switching tabs retains both pages. + * @param inspection Available data or validated archive summary. + * @param selection Explicit category and provider choices. + * @param areProvidersExpanded Whether nested provider choices are visible. + * @author Dmitriy Moroz + */ +data class BackupPageState( + val inspection: BackupInspection? = null, + val selection: BackupSelection = BackupSelection(), + val areProvidersExpanded: Boolean = true, +) diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupPagerInteraction.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupPagerInteraction.kt new file mode 100644 index 000000000..c8a25a430 --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupPagerInteraction.kt @@ -0,0 +1,17 @@ +package com.shifthackz.aisdv1.presentation.backup + +import kotlin.math.abs + +/** + * Keeps the selected page's actions stable during incidental horizontal movement in a vertical scroll. + * Actions pause once a swipe has moved at least forty percent of one page away from that selection. + * @param selectedPage Page owning the active MVI selection and bottom action. + * @param currentPage Pager's nearest page; this changes halfway through a swipe. + * @param currentPageOffsetFraction Signed displacement from the nearest page in page-width units. + * @author Dmitriy Moroz + */ +internal fun canInteractWithBackupPage( + selectedPage: Int, + currentPage: Int, + currentPageOffsetFraction: Float, +): Boolean = abs(currentPage - selectedPage + currentPageOffsetFraction) < 0.4f diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupScreen.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupScreen.kt new file mode 100644 index 000000000..203445de0 --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupScreen.kt @@ -0,0 +1,167 @@ +package com.shifthackz.aisdv1.presentation.backup + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.pager.HorizontalPager +import androidx.compose.foundation.pager.rememberPagerState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.outlined.ArrowBack +import androidx.compose.material3.CenterAlignedTopAppBar +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Tab +import androidx.compose.material3.SecondaryTabRow +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Modifier +import com.shifthackz.aisdv1.core.localization.Localization +import com.shifthackz.aisdv1.presentation.backup.dialog.BackupDialogs +import com.shifthackz.aisdv1.presentation.backup.welcome.RestoreWelcomeScreen +import com.shifthackz.aisdv1.presentation.components.theme.global.persistentTopAppBarWindowInsets +import com.shifthackz.aisdv1.presentation.components.widget.action.PrimaryActionButton +import com.shifthackz.aisdv1.presentation.components.widget.action.ScreenActionBar +import kotlinx.coroutines.flow.drop + +/** + * Hosts reusable backup content with configuration-aligned chrome and operation dialogs. + * @param mode Settings tabs or first-launch recovery context. + * @param state Nonsecret inventory, selection and operation feedback. + * @param processIntent Caller-owned MVI event sink. + * @param modifier Root screen placement. + * @author Dmitriy Moroz + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun BackupScreen( + mode: BackupScreenMode, + state: BackupState, + processIntent: (BackupIntent) -> Unit, + modifier: Modifier = Modifier, +) { + val isEnabled = !state.isBusy && !state.isPicking && !state.isExporting + if (mode == BackupScreenMode.WELCOME) { + RestoreWelcomeScreen( + isEnabled = isEnabled, + onRestore = { processIntent(BackupIntent.BeginInitialRestore) }, + onContinue = { processIntent(BackupIntent.Continue) }, + modifier = modifier, + ) + } else { + val page = if (state.isRestoreTab) state.restore else state.create + val pager = rememberPagerState(initialPage = if (state.isRestoreTab) 1 else 0) { 2 } + val isRestoreSelected by rememberUpdatedState(state.isRestoreTab) + val selectedPage = if (state.isRestoreTab) 1 else 0 + val canInteractWithPage = mode != BackupScreenMode.SETTINGS || canInteractWithBackupPage( + selectedPage, pager.currentPage, pager.currentPageOffsetFraction + ) + LaunchedEffect(state.isRestoreTab, isEnabled) { + if (mode == BackupScreenMode.SETTINGS) { + pager.animateScrollToPage(selectedPage) + } + } + LaunchedEffect(pager) { + if (mode == BackupScreenMode.SETTINGS) { + snapshotFlow { pager.settledPage }.drop(1).collect { settledPage -> + val shouldRestore = settledPage == 1 + if (shouldRestore != isRestoreSelected) processIntent( + BackupIntent.SelectTab( + shouldRestore + ) + ) + } + } + } + val isFinished = + if (state.isRestoreTab) state.result?.hasFailed == false else state.hasExported + Scaffold( + modifier = modifier, + topBar = { + CenterAlignedTopAppBar( + title = { + Text( + Localization.string("backup_title"), + style = MaterialTheme.typography.headlineMedium + ) + }, + navigationIcon = { + IconButton( + onClick = { processIntent(BackupIntent.NavigateBack) }, + enabled = isEnabled + ) { + Icon( + Icons.AutoMirrored.Outlined.ArrowBack, + Localization.string("action_back") + ) + } + }, + windowInsets = persistentTopAppBarWindowInsets(), + ) + }, + bottomBar = { + ScreenActionBar { + PrimaryActionButton( + onClick = { processIntent(if (isFinished) BackupIntent.NavigateBack else BackupIntent.Submit) }, + isEnabled = isEnabled && canInteractWithPage && (isFinished || page.selection.categories.isNotEmpty()), + ) { + Text(Localization.string(if (isFinished) "backup_done" else if (state.isRestoreTab) "backup_restore" else "backup_create")) + } + } + }, + ) { padding -> + Column(Modifier.padding(padding).fillMaxSize()) { + if (mode == BackupScreenMode.SETTINGS) { + SecondaryTabRow( + selectedTabIndex = selectedPage, + contentColor = MaterialTheme.colorScheme.primary, + ) { + Tab( + selected = !state.isRestoreTab, + onClick = { processIntent(BackupIntent.SelectTab(false)) }, + enabled = isEnabled, + text = { Text(Localization.string("backup_create_tab")) }, + ) + Tab( + selected = state.isRestoreTab, + onClick = { processIntent(BackupIntent.SelectTab(true)) }, + enabled = isEnabled, + text = { Text(Localization.string("backup_restore_tab")) }, + ) + } + HorizontalPager( + state = pager, + modifier = Modifier.weight(1f).fillMaxWidth(), + userScrollEnabled = isEnabled, + key = { it }, + ) { pageIndex -> + val isRestorePage = pageIndex == 1 + BackupPageContent( + isRestore = isRestorePage, + page = if (isRestorePage) state.restore else state.create, + isEnabled = isEnabled && canInteractWithPage && isRestorePage == state.isRestoreTab, + canEditSelection = if (isRestorePage) !state.isRestoreSelectionLocked else !state.hasPendingExport, + processIntent = processIntent, + ) + } + } else { + BackupPageContent( + isRestore = true, + page = state.restore, + isEnabled = isEnabled, + canEditSelection = !state.isRestoreSelectionLocked, + processIntent = processIntent, + ) + } + } + } + } + BackupDialogs(state, processIntent) +} diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupScreenMode.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupScreenMode.kt new file mode 100644 index 000000000..6efb415f5 --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupScreenMode.kt @@ -0,0 +1,7 @@ +package com.shifthackz.aisdv1.presentation.backup + +/** + * Controls chrome and completion behavior while reusing the same create and restore content. + * @author Dmitriy Moroz + */ +enum class BackupScreenMode { SETTINGS, FIRST_LAUNCH, WELCOME } diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupState.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupState.kt new file mode 100644 index 000000000..385caacb0 --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupState.kt @@ -0,0 +1,44 @@ +package com.shifthackz.aisdv1.presentation.backup + +import com.shifthackz.aisdv1.core.mvi.MviState +import com.shifthackz.aisdv1.domain.entity.backup.BackupProgress +import com.shifthackz.aisdv1.domain.entity.backup.BackupRestoreResult + +/** + * Nonsecret backup UI state. Archive bytes and provider credential values never enter this model. + * @param create Create inventory and choices. + * @param restore Restore summary and choices. + * @param isRestoreTab Current tab, or true in first-launch restore-only mode. + * @param isBusy Whether a serialized file or commit job owns the screen. + * @param isExporting Whether graph-owned destination copying is in progress. + * @param hasPendingExport Whether a durable export intent owns the staged source. + * @param isPicking Whether a native document picker is open. + * @param progress Current bounded work stage. + * @param conflict Named provider conflicts and opaque consent fingerprint. + * @param result Durable completion report, including partial failure. + * @param isFeedbackVisible Whether the current completion, cancellation or failure still needs acknowledgement. + * @param hasError Whether the last operation failed before a completion report. + * @param hasCanceled Whether the user canceled active work. + * @param hasExported Whether native document export actually completed. + * @param hasPendingSession Whether unfinished restore intent owns the staged archive. + * @param isRestoreSelectionLocked Whether displayed choices are bound to a submitted or completed restore operation. + * @author Dmitriy Moroz + */ +data class BackupState( + val create: BackupPageState = BackupPageState(), + val restore: BackupPageState = BackupPageState(), + val isRestoreTab: Boolean = false, + val isBusy: Boolean = false, + val isExporting: Boolean = false, + val hasPendingExport: Boolean = false, + val isPicking: Boolean = false, + val progress: BackupProgress? = null, + val conflict: BackupRestoreResult.Conflict? = null, + val result: BackupRestoreResult.Finished? = null, + val isFeedbackVisible: Boolean = false, + val hasError: Boolean = false, + val hasCanceled: Boolean = false, + val hasExported: Boolean = false, + val hasPendingSession: Boolean = false, + val isRestoreSelectionLocked: Boolean = false, +) : MviState diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupViewModel.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupViewModel.kt new file mode 100644 index 000000000..415d68372 --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/BackupViewModel.kt @@ -0,0 +1,405 @@ +package com.shifthackz.aisdv1.presentation.backup + +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import com.shifthackz.aisdv1.core.mvi.BaseMviViewModel +import com.shifthackz.aisdv1.core.mvi.diagnostics.UiDiagnostics +import com.shifthackz.aisdv1.core.mvi.diagnostics.asDiagnosticScreen +import com.shifthackz.aisdv1.core.navigation.NavigationDestination +import com.shifthackz.aisdv1.core.navigation.router.BackupRouter +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.entity.backup.BackupExport +import com.shifthackz.aisdv1.domain.entity.backup.BackupInspection +import com.shifthackz.aisdv1.domain.entity.backup.BackupProgress +import com.shifthackz.aisdv1.domain.entity.backup.BackupRestoreRequest +import com.shifthackz.aisdv1.domain.entity.backup.BackupRestoreResult +import com.shifthackz.aisdv1.domain.entity.backup.BackupSelection +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage +import com.shifthackz.aisdv1.domain.usecase.backup.CreateBackupUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.InspectBackupUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.RestoreBackupUseCase +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportCompletion +import com.shifthackz.aisdv1.domain.entity.backup.BackupExportStatus +import com.shifthackz.aisdv1.domain.usecase.backup.ObserveBackupExportUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.CompleteBackupExportUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.CancelBackupExportUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.DismissBackupExportUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.GetBackupStartupStageUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.DiscardBackupUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.LoadBackupInventoryUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.LoadPendingBackupUseCase +import com.shifthackz.aisdv1.domain.usecase.backup.SetBackupStartupStageUseCase +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Job +import kotlinx.coroutines.withContext +import kotlin.random.Random + +/** + * Owns independent tab selections, native picker outcomes and resumable restore intent. + * @param mode Settings tabs or first-launch recovery context. + * @param router Caller-owned navigation contract. + * @param diagnostics Bounded nonsecret MVI diagnostics. + * @param dispatchers IO work and immediate UI publication dispatchers. + * @param inventory Loads current selectable app data. + * @param createBackup Creates a complete staged binary archive. + * @param inspectBackup Stages and validates a native document. + * @param restoreBackup Merges selected categories with durable retry identity. + * @param observeExport Observes graph-owned export work across host recreation. + * @param completeExport Queues native outcomes independently of screen initialization. + * @param cancelExport Interrupts destination copying while retaining its owned source. + * @param dismissExport Acknowledges export completion or abandons a staged export. + * @param getStartupStage Reads acknowledged first-launch progression after pending recovery. + * @param discardBackup Releases staging after resolving checked writes. + * @param loadPending Loads nonsecret process-recovery intent. + * @param setStartupStage Persists first-launch progression before navigation. + * @author Dmitriy Moroz + */ +class BackupViewModel( + val mode: BackupScreenMode, + private val router: BackupRouter, + diagnostics: UiDiagnostics, + private val dispatchers: DispatchersProvider, + private val inventory: LoadBackupInventoryUseCase, + private val createBackup: CreateBackupUseCase, + private val inspectBackup: InspectBackupUseCase, + private val restoreBackup: RestoreBackupUseCase, + private val observeExport: ObserveBackupExportUseCase, + private val completeExport: CompleteBackupExportUseCase, + private val cancelExport: CancelBackupExportUseCase, + private val dismissExport: DismissBackupExportUseCase, + private val getStartupStage: GetBackupStartupStageUseCase, + private val discardBackup: DiscardBackupUseCase, + private val loadPending: LoadPendingBackupUseCase, + private val setStartupStage: SetBackupStartupStageUseCase, +) : BaseMviViewModel( + diagnostics, NavigationDestination.BACKUP.asDiagnosticScreen(), + BackupState(isRestoreTab = mode == BackupScreenMode.FIRST_LAUNCH), dispatchers.immediate, +) { + private var operation: Job? = null + private var documentResult: Job? = null + private var documentResultId = 0L + private var pendingExport: BackupExport? = null + private var restoreRequest: BackupRestoreRequest? = null + + private val exportObserver = launch(dispatchers.immediate) { + observeExport().collect { export -> + pendingExport = export.backup + updateState { + it.copy( + isExporting = export.status == BackupExportStatus.COPYING || export.status == BackupExportStatus.PROCESSING, + hasPendingExport = export.backup != null, + hasExported = export.status == BackupExportStatus.COMPLETE, + hasCanceled = it.hasCanceled || export.status == BackupExportStatus.CANCELED, + hasError = it.hasError || export.status == BackupExportStatus.FAILED, + isFeedbackVisible = it.isFeedbackVisible || export.status in setOf( + BackupExportStatus.COMPLETE, + BackupExportStatus.FAILED, + BackupExportStatus.CANCELED, + ), + ) + } + } + } + + init { + if (mode != BackupScreenMode.WELCOME) runOperation(shouldClearFeedback = false) { + val recovery = loadPending() + if (recovery != null) { + restoreRequest = recovery.request + updateState { + it.copy( + isRestoreTab = true, + hasPendingSession = true, + isRestoreSelectionLocked = true, + restore = BackupPageState(recovery.inspection, recovery.request.selection) + ) + } + } + if (recovery == null && mode == BackupScreenMode.FIRST_LAUNCH) { + when (getStartupStage()) { + BackupStartupStage.CONFIGURATION -> { + withContext(dispatchers.immediate) { router.navigateToInitialConfiguration() } + return@runOperation + } + + BackupStartupStage.COMPLETE -> { + withContext(dispatchers.immediate) { router.navigateToHomeScreen() } + return@runOperation + } + + BackupStartupStage.INVITATION, BackupStartupStage.RESTORE -> Unit + } + } + val values = inventory() + updateState { it.copy(create = BackupPageState(values, allSelected(values))) } + } + } + + /** + * Applies UI choices or native document outcomes while rejecting overlapping jobs. + * @param intent User action or native document picker result. + * @author Dmitriy Moroz + */ + override fun processIntent(intent: BackupIntent) { + when (intent) { + BackupIntent.CancelWork -> { + documentResult?.cancel(); operation?.cancel(); cancelExport() + } + + BackupIntent.NavigateBack -> if (canInteract()) leave() + BackupIntent.Continue -> transition(BackupStartupStage.CONFIGURATION) { router.navigateToInitialConfiguration() } + BackupIntent.BeginInitialRestore -> transition(BackupStartupStage.RESTORE) { router.navigateToInitialRestore() } + is BackupIntent.SelectTab -> if (canInteract()) updateState { + it.copy( + isRestoreTab = intent.isRestore, + result = null, + hasError = false, + hasCanceled = false, + isFeedbackVisible = false, + ) + } + + is BackupIntent.ToggleCategory -> if (canEdit()) editPage { page -> + val selected = page.selection.categories + val categories = + if (intent.category in selected) selected - intent.category else selected + intent.category + val providers = if (intent.category == BackupCategory.PROVIDERS) { + if (intent.category in categories) page.inspection?.providers.orEmpty() else emptySet() + } else page.selection.providers + page.copy(selection = BackupSelection(categories, providers)) + } + + is BackupIntent.ToggleProvider -> if (canEdit()) editPage { page -> + val providers = + page.selection.providers.let { if (intent.key in it) it - intent.key else it + intent.key } + val categories = + if (providers.isEmpty()) page.selection.categories - BackupCategory.PROVIDERS else page.selection.categories + BackupCategory.PROVIDERS + page.copy(selection = BackupSelection(categories, providers)) + } + + BackupIntent.ToggleProvidersExpanded -> if (canInteract()) editPage { + it.copy( + areProvidersExpanded = !it.areProvidersExpanded + ) + } + + BackupIntent.ChooseFile -> if (canInteract()) runOperation { + updateState { it.copy(isPicking = true) } + emitEffect(BackupEffect.OpenDocument) + } + + is BackupIntent.DocumentSelected -> selectDocument(intent.document) + + BackupIntent.Submit -> if (canInteract()) submit(null) + BackupIntent.ConfirmProviderReplacement -> currentState.conflict?.let { submit(it.fingerprint) } + BackupIntent.DismissConflict -> { + if (!currentState.hasPendingSession) restoreRequest = null + updateState { + it.copy( + conflict = null, + isRestoreSelectionLocked = restoreRequest != null + ) + } + } + + BackupIntent.DismissFeedback -> if (canInteract()) { + if (mode == BackupScreenMode.FIRST_LAUNCH && currentState.result?.hasFailed == false) { + leave() + } else updateState { it.copy(isFeedbackVisible = false) } + } + + is BackupIntent.ExportFinished -> completeExport(intent) + } + } + + private fun selectDocument(document: String?) { + if (document == null) { + updateState { it.copy(isPicking = false) } + return + } + documentResult?.cancel() + val resultId = ++documentResultId + val preceding = operation + updateState { it.copy(isPicking = true) } + documentResult = launch(dispatchers.io) { + try { + preceding?.join() + withContext(dispatchers.immediate) { + updateState { it.copy(isPicking = false, isRestoreTab = true) } + runOperation { + val inspected = inspectBackup(document, ::progress) + try { + clearRestore() + } catch (failure: Throwable) { + discardBackup(inspected.handle) + throw failure + } + updateState { + it.copy( + restore = BackupPageState(inspected, allSelected(inspected)), + hasPendingSession = false, + isRestoreSelectionLocked = false, + result = null, + ) + } + } + } + } finally { + if (resultId == documentResultId) updateState { it.copy(isPicking = false) } + } + } + } + + private fun submit(fingerprint: String?) { + val snapshot = currentState + if (!snapshot.isRestoreTab) { + if (snapshot.create.selection.categories.isEmpty()) return + runOperation { + val backup = pendingExport ?: createBackup(snapshot.create.selection, ::progress) + pendingExport = backup + updateState { it.copy(isPicking = true) } + emitEffect(BackupEffect.ExportDocument(backup)) + } + } else { + val inspection = snapshot.restore.inspection ?: return + if (snapshot.restore.selection.categories.isEmpty()) return + val request = (restoreRequest ?: BackupRestoreRequest( + inspection.handle, + snapshot.restore.selection, + newSessionId(), + shouldProceedToConfiguration = mode == BackupScreenMode.FIRST_LAUNCH + )).copy(confirmedFingerprint = fingerprint) + restoreRequest = request + updateState { it.copy(conflict = null, isRestoreSelectionLocked = true) } + runOperation { + when (val result = restoreBackup(request, ::progress)) { + is BackupRestoreResult.Conflict -> updateState { it.copy(conflict = result) } + is BackupRestoreResult.Finished -> { + updateState { + it.copy( + result = result, + hasPendingSession = result.hasFailed, + isFeedbackVisible = true, + ) + } + } + } + } + } + } + + private fun completeExport(result: BackupIntent.ExportFinished) { + updateState { it.copy(isPicking = false, isExporting = true) } + // This callback may precede asynchronous initialization on a recreated host. + completeExport( + when { + result.destination != null -> BackupExportCompletion.DestinationSelected( + result.destination, + result.handle + ) + + result.hasExported -> BackupExportCompletion.NativeCompleted(result.handle) + else -> BackupExportCompletion.Canceled(result.handle) + } + ) + } + + private fun leave() = runOperation { + if (mode == BackupScreenMode.FIRST_LAUNCH) setStartupStage(BackupStartupStage.CONFIGURATION) + clearRestore() + dismissExport() + pendingExport = null + if (mode == BackupScreenMode.FIRST_LAUNCH) { + withContext(dispatchers.immediate) { router.navigateToInitialConfiguration() } + } else withContext(dispatchers.immediate) { router.navigateBack() } + } + + private suspend fun clearRestore() { + currentState.restore.inspection?.let { discardBackup(it.handle) } + restoreRequest = null + updateState { + it.copy( + restore = BackupPageState(), + hasPendingSession = false, + isRestoreSelectionLocked = false + ) + } + } + + private fun transition(stage: BackupStartupStage, navigate: () -> Unit) { + if (!canInteract()) return + runOperation { + setStartupStage(stage) + withContext(dispatchers.immediate) { navigate() } + } + } + + /** + * Serializes bounded work and publishes cancellable loading plus acknowledged failure feedback. + * @param shouldClearFeedback Whether a new user operation replaces the prior feedback; startup keeps durable export completion. + * @param block Work run on IO with state publication through the MVI owner. + * @author Dmitriy Moroz + */ + private fun runOperation(shouldClearFeedback: Boolean = true, block: suspend () -> Unit) { + if (operation?.isActive == true) return + updateState { + it.copy( + isBusy = true, + hasError = if (shouldClearFeedback) false else it.hasError, + hasCanceled = if (shouldClearFeedback) false else it.hasCanceled, + isFeedbackVisible = if (shouldClearFeedback) false else it.isFeedbackVisible, + progress = null + ) + } + operation = launch(dispatchers.io) { + try { + block() + } catch (cancelled: CancellationException) { + updateState { it.copy(hasCanceled = true, isFeedbackVisible = true) } + throw cancelled + } catch (_: Exception) { + updateState { it.copy(hasError = true, isFeedbackVisible = true) } + } finally { + updateState { it.copy(isBusy = false, progress = null) } + } + } + } + + private fun progress(value: BackupProgress) = updateState { it.copy(progress = value) } + private fun canInteract() = + !currentState.isBusy && !currentState.isPicking && !currentState.isExporting + + private fun canEdit() = + canInteract() && (if (currentState.isRestoreTab) !currentState.isRestoreSelectionLocked else !currentState.hasPendingExport) + + private fun editPage(transform: (BackupPageState) -> BackupPageState) = updateState { + if (it.isRestoreTab) it.copy(restore = transform(it.restore)) else it.copy( + create = transform( + it.create + ) + ) + } + + private fun allSelected(summary: BackupInspection) = + BackupSelection( + summary.entries.filter { it.isAvailable }.map { it.category }.toSet(), + summary.providers + ) + + private fun newSessionId(): String = + List(16) { Random.nextInt(256).toString(16).padStart(2, '0') }.joinToString("").let { + it.take(8) + "-" + it.substring(8, 12) + "-" + it.substring( + 12, + 16 + ) + "-" + it.substring(16, 20) + "-" + it.substring(20) + } + + /** + * Stops owned work on route disposal. Interrupted restore staging remains journal-owned for recovery. + * @author Dmitriy Moroz + */ + fun onRouteDisposed() { + documentResult?.cancel() + operation?.cancel() + exportObserver.cancel() + } +} diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/component/BackupArchiveCard.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/component/BackupArchiveCard.kt new file mode 100644 index 000000000..8da307dbb --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/component/BackupArchiveCard.kt @@ -0,0 +1,66 @@ +package com.shifthackz.aisdv1.presentation.backup.component + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Description +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedCard +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.domain.entity.backup.BackupInspection +import com.shifthackz.aisdv1.presentation.backup.platform.formatBackupCreatedAt + +/** + * Groups the selected archive identity, available source location and creation details before restore choices. + * @param archive Validated summary with no provider credentials or decoded image data. + * @param modifier Card placement within the scrolling restore content. + * @author Dmitriy Moroz + */ +@Composable +internal fun BackupArchiveCard(archive: BackupInspection, modifier: Modifier = Modifier) { + OutlinedCard(modifier.fillMaxWidth()) { + Row(Modifier.padding(16.dp), horizontalArrangement = Arrangement.spacedBy(16.dp)) { + Icon( + Icons.Outlined.Description, + contentDescription = null, + modifier = Modifier.size(24.dp) + ) + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text(archive.filename, style = MaterialTheme.typography.titleMedium) + if (archive.sourceLocation.isNotEmpty()) { + Text( + archive.sourceLocation, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Text( + Localization.string( + "backup_archive_details", + archive.appVersion, + archive.sourcePlatform + ), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Text( + Localization.string( + "backup_created_at", + formatBackupCreatedAt(archive.createdAt) + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } +} diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/component/BackupSelectionList.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/component/BackupSelectionList.kt new file mode 100644 index 000000000..df0da8cdb --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/component/BackupSelectionList.kt @@ -0,0 +1,178 @@ +package com.shifthackz.aisdv1.presentation.backup.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.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +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.selection.triStateToggleable +import androidx.compose.foundation.selection.toggleable +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ExpandLess +import androidx.compose.material.icons.filled.ExpandMore +import androidx.compose.material3.Card +import androidx.compose.material3.Checkbox +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TriStateCheckbox +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.state.ToggleableState +import androidx.compose.ui.unit.dp +import com.shifthackz.aisdv1.domain.entity.ServerSource +import com.shifthackz.aisdv1.presentation.components.model.shortDisplayName +import com.shifthackz.aisdv1.core.localization.Localization +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.presentation.backup.BackupPageState +import com.shifthackz.aisdv1.presentation.backup.BackupIntent + +/** + * Shared category and nested-provider selection for create and restore. Selection is always caller-owned. + * @param state Current page inventory and choices; contains no credential values. + * @param isEnabled Whether selection can change during this operation. + * @param processIntent Receives selection and disclosure actions. + * @param modifier Layout applied to the root list container. + * @author Dmitriy Moroz + */ +@Composable +internal fun BackupSelectionList( + state: BackupPageState, + isEnabled: Boolean, + processIntent: (BackupIntent) -> Unit, + modifier: Modifier = Modifier +) { + Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) { + state.inspection?.entries?.forEach { entry -> + val category = entry.category + val isSelected = category in state.selection.categories + val hasSomeProviders = + category == BackupCategory.PROVIDERS && state.selection.providers.isNotEmpty() + val hasAllProviders = state.selection.providers.containsAll(state.inspection.providers) + Card(Modifier.fillMaxWidth()) { + Row( + Modifier.fillMaxWidth().then( + if (category == BackupCategory.PROVIDERS) Modifier.triStateToggleable( + state = when { + hasSomeProviders && !hasAllProviders -> ToggleableState.Indeterminate + isSelected -> ToggleableState.On + else -> ToggleableState.Off + }, + enabled = isEnabled && entry.isAvailable, + role = Role.Checkbox, + onClick = { processIntent(BackupIntent.ToggleCategory(category)) }, + ) else Modifier.toggleable( + value = isSelected, + enabled = isEnabled && entry.isAvailable, + role = Role.Checkbox, + onValueChange = { processIntent(BackupIntent.ToggleCategory(category)) }, + ) + ).padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + if (category == BackupCategory.PROVIDERS) { + TriStateCheckbox( + state = when { + hasSomeProviders && !hasAllProviders -> ToggleableState.Indeterminate + isSelected -> ToggleableState.On + else -> ToggleableState.Off + }, onClick = null, enabled = isEnabled && entry.isAvailable + ) + } else Checkbox( + checked = isSelected, + onCheckedChange = null, + enabled = isEnabled && entry.isAvailable + ) + Spacer(Modifier.size(12.dp)) + Column(Modifier.weight(1f)) { + Text( + Localization.string("backup_category_" + category.key), + style = MaterialTheme.typography.titleMedium + ) + Text( + if (entry.isAvailable) Localization.string( + "backup_items", + entry.itemCount + ) else Localization.string("backup_unavailable"), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + if (category == BackupCategory.PROVIDERS && state.inspection.providers.isNotEmpty()) IconButton( + onClick = { processIntent(BackupIntent.ToggleProvidersExpanded) }, + enabled = isEnabled + ) { + Icon( + if (state.areProvidersExpanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore, + Localization.string("backup_provider_choices") + ) + } + } + if (category == BackupCategory.PROVIDERS) { + AnimatedVisibility( + visible = state.areProvidersExpanded, + enter = expandVertically() + fadeIn(), + exit = shrinkVertically() + fadeOut(), + ) { + Column { + state.inspection.providers.sorted().forEach { provider -> + Row( + Modifier.fillMaxWidth().heightIn(min = 48.dp).toggleable( + value = provider in state.selection.providers, + enabled = isEnabled && entry.isAvailable, + role = Role.Checkbox, + onValueChange = { + processIntent( + BackupIntent.ToggleProvider( + provider + ) + ) + }, + ).padding( + start = 44.dp, + end = 16.dp, + top = 8.dp, + bottom = 8.dp + ), + verticalAlignment = Alignment.CenterVertically + ) { + Checkbox( + checked = provider in state.selection.providers, + onCheckedChange = null, + enabled = isEnabled && entry.isAvailable + ) + Spacer(Modifier.size(12.dp)) + Text( + providerName(provider), + style = MaterialTheme.typography.bodyLarge + ) + } + } + } + } + } + } + } + } +} + +/** + * Resolves a known stable provider ID through the existing localized short display-name mapping. + * Unknown IDs retain their literal identifier so inspection can still describe unsupported data. + * + * @param key Stable provider wire identifier from backup metadata. + * @author Dmitriy Moroz + */ +internal fun providerName(key: String): String = + ServerSource.entries.firstOrNull { it.key == key }?.shortDisplayName() ?: key diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/create/CreateBackupScreen.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/create/CreateBackupScreen.kt new file mode 100644 index 000000000..d06613bac --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/create/CreateBackupScreen.kt @@ -0,0 +1,43 @@ +package com.shifthackz.aisdv1.presentation.backup.create + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.material3.MaterialTheme +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.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.presentation.backup.BackupPageState +import com.shifthackz.aisdv1.presentation.backup.BackupIntent +import com.shifthackz.aisdv1.presentation.backup.component.BackupSelectionList + +/** + * Dedicated reusable create content with a visible portable-credential disclosure. + * @param state Create inventory and independent selection. + * @param isEnabled Whether the checklist can be edited. + * @param processIntent Selection and navigation actions. + * @param modifier Root content placement. + * @author Dmitriy Moroz + */ +@Composable +internal fun CreateBackupScreen( + state: BackupPageState, + isEnabled: Boolean, + processIntent: (BackupIntent) -> Unit, + modifier: Modifier = Modifier +) { + Column(modifier, verticalArrangement = Arrangement.spacedBy(16.dp)) { + Text( + Localization.string("backup_create_description"), + style = MaterialTheme.typography.bodyLarge + ) + BackupSelectionList(state, isEnabled, processIntent) + if (BackupCategory.PROVIDERS in state.selection.categories) Text( + Localization.string("backup_secrets_warning"), + color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.bodyMedium + ) + } +} diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/di/BackupViewModelModule.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/di/BackupViewModelModule.kt new file mode 100644 index 000000000..9128d6251 --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/di/BackupViewModelModule.kt @@ -0,0 +1,36 @@ +package com.shifthackz.aisdv1.presentation.backup.di + +import com.shifthackz.aisdv1.core.navigation.router.BackupRouter +import com.shifthackz.aisdv1.presentation.backup.BackupScreenMode +import com.shifthackz.aisdv1.presentation.backup.BackupViewModel +import com.shifthackz.aisdv1.domain.gateway.backup.BackupChangesGateway +import com.shifthackz.aisdv1.presentation.backup.service.BackupChangesGatewayImpl +import org.koin.dsl.module + +/** + * Creates caller-owned backup state holders with shared domain operations. + * @author Dmitriy Moroz + */ +val backupViewModelModule = module { + single { BackupChangesGatewayImpl(get(), get()) } + factory { (mode: BackupScreenMode, router: BackupRouter) -> + BackupViewModel( + mode, + router, + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get(), + get() + ) + } +} diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/dialog/BackupDialogs.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/dialog/BackupDialogs.kt new file mode 100644 index 000000000..42626833e --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/dialog/BackupDialogs.kt @@ -0,0 +1,83 @@ +package com.shifthackz.aisdv1.presentation.backup.dialog + +import androidx.compose.runtime.Composable +import com.shifthackz.aisdv1.core.localization.Localization +import com.shifthackz.aisdv1.core.model.asUiText +import com.shifthackz.aisdv1.presentation.backup.BackupIntent +import com.shifthackz.aisdv1.presentation.backup.BackupState +import com.shifthackz.aisdv1.presentation.backup.component.providerName +import com.shifthackz.aisdv1.presentation.components.widget.dialog.DecisionInteractiveDialogContent +import com.shifthackz.aisdv1.presentation.components.widget.dialog.ErrorDialog +import com.shifthackz.aisdv1.presentation.components.widget.dialog.InfoDialog +import com.shifthackz.aisdv1.presentation.components.widget.dialog.ProgressDialog +import com.shifthackz.aisdv1.presentation.components.widget.dialog.ProgressDialogCancelButton + +/** + * Presents exclusive progress, provider-consent and acknowledged result feedback using shared app dialogs. + * @param state Nonsecret operation state; completed restore data stays available after acknowledgement. + * @param processIntent Cancellation, conflict consent and acknowledgement event sink. + * @author Dmitriy Moroz + */ +@Composable +internal fun BackupDialogs(state: BackupState, processIntent: (BackupIntent) -> Unit) { + val dismiss = { processIntent(BackupIntent.DismissFeedback) } + when { + state.isBusy || state.isExporting -> { + val status = state.progress?.let { progress -> + val category = + progress.category?.let { Localization.string("backup_category_" + it.key) } + val count = + if (progress.total > 0) "${progress.completed} / ${progress.total}" else progress.completed.toString() + listOfNotNull(category, count).joinToString(" · ") + } ?: Localization.string("backup_working") + ProgressDialog( + title = Localization.string("backup_title").asUiText(), + subTitle = status.asUiText(), + canDismiss = false, + ) { + ProgressDialogCancelButton(onClick = { processIntent(BackupIntent.CancelWork) }) + } + } + + state.conflict != null -> DecisionInteractiveDialogContent( + title = Localization.string("backup_conflict_title"), + text = Localization.string( + "backup_conflict_description", + state.conflict.providers.joinToString(", ", transform = ::providerName) + ), + confirmActionText = Localization.string("backup_replace_providers"), + dismissActionText = Localization.string("backup_cancel"), + onConfirmAction = { processIntent(BackupIntent.ConfirmProviderReplacement) }, + onDismissRequest = { processIntent(BackupIntent.DismissConflict) }, + ) + + state.isFeedbackVisible -> when { + state.hasCanceled -> InfoDialog( + Localization.string("backup_title").asUiText(), + Localization.string("backup_canceled").asUiText(), + dismiss, + ) + + state.hasError -> ErrorDialog(Localization.string("backup_error").asUiText(), dismiss) + state.result != null -> { + val result = state.result + if (result.hasFailed) { + ErrorDialog(backupResultText(result).asUiText(), dismiss) + } else { + InfoDialog( + Localization.string("backup_restored").asUiText(), + backupResultText(result).asUiText(), + dismiss + ) + } + } + + state.hasExported -> InfoDialog( + Localization.string("backup_title").asUiText(), + Localization.string("backup_exported").asUiText(), + dismiss, + ) + + } + } +} diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/dialog/BackupResultText.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/dialog/BackupResultText.kt new file mode 100644 index 000000000..f0fbf4d0b --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/dialog/BackupResultText.kt @@ -0,0 +1,29 @@ +package com.shifthackz.aisdv1.presentation.backup.dialog + +import com.shifthackz.aisdv1.core.localization.Localization +import com.shifthackz.aisdv1.domain.entity.backup.BackupRestoreNotice +import com.shifthackz.aisdv1.domain.entity.backup.BackupRestoreResult +import com.shifthackz.aisdv1.presentation.backup.component.providerName + +/** + * Formats the committed category counts and skipped-data notices for the shared result dialog. + * @param result Durable outcome of the submitted restore session. + * @author Dmitriy Moroz + */ +internal fun backupResultText(result: BackupRestoreResult.Finished): String = buildList { + if (result.hasFailed) add(Localization.string("backup_partial")) + result.importedCounts.forEach { (category, count) -> + add(Localization.string("backup_category_" + category.key) + ": " + count) + } + result.notices.forEach { notice -> + when (notice) { + is BackupRestoreNotice.SharedCredentialsRetained -> add( + Localization.string( + "backup_shared_credentials_retained", + notice.providers.joinToString(", ", transform = ::providerName), + ) + ) + } + } + if (result.skippedCount > 0) add(Localization.string("backup_skipped", result.skippedCount)) +}.joinToString("\n\n") diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/platform/BackupDateFormatter.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/platform/BackupDateFormatter.kt new file mode 100644 index 000000000..974b95919 --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/platform/BackupDateFormatter.kt @@ -0,0 +1,8 @@ +package com.shifthackz.aisdv1.presentation.backup.platform + +/** + * Formats a UTC timestamp using the current platform locale and date/time conventions. + * @param epochMillis Archive creation time in milliseconds since the Unix epoch. + * @author Dmitriy Moroz + */ +internal expect fun formatBackupCreatedAt(epochMillis: Long): String diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/platform/BackupDocumentLauncher.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/platform/BackupDocumentLauncher.kt new file mode 100644 index 000000000..c18a6baa4 --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/platform/BackupDocumentLauncher.kt @@ -0,0 +1,35 @@ +package com.shifthackz.aisdv1.presentation.backup.platform + +import androidx.compose.runtime.Composable +import com.shifthackz.aisdv1.domain.entity.backup.BackupExport + +/** + * Native document presentation owned by the Compose route lifecycle. + * @author Dmitriy Moroz + */ +interface BackupDocumentLauncher { + /** + * Opens a single backup file using the system document picker. + * @author Dmitriy Moroz + */ + fun open() + + /** + * Presents native export for a complete staged document. + * @param backup Private staged document and suggested public filename. + * @author Dmitriy Moroz + */ + fun export(backup: BackupExport) +} + +/** + * Remembers native activity-result launchers or a retained UIKit document delegate. + * @param onPicked Opaque selected document, or null after neutral cancellation. + * @param onExported Android destination reference or iOS completion flag; cancellation reports neither. + * @author Dmitriy Moroz + */ +@Composable +expect fun rememberBackupDocumentLauncher( + onPicked: (String?) -> Unit, + onExported: (String?, Boolean, String) -> Unit +): BackupDocumentLauncher diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/restore/RestoreBackupScreen.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/restore/RestoreBackupScreen.kt new file mode 100644 index 000000000..b1ec613af --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/restore/RestoreBackupScreen.kt @@ -0,0 +1,71 @@ +package com.shifthackz.aisdv1.presentation.backup.restore + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.shifthackz.aisdv1.core.localization.Localization +import com.shifthackz.aisdv1.presentation.backup.BackupPageState +import com.shifthackz.aisdv1.presentation.backup.BackupIntent +import com.shifthackz.aisdv1.presentation.backup.component.BackupArchiveCard +import com.shifthackz.aisdv1.presentation.backup.component.BackupSelectionList + +/** + * Dedicated restore content shared by settings tabs and first-launch recovery. + * @param state Inspected file summary and category choices. + * @param isEnabled Whether a new file can be selected. + * @param canEditSelection Whether choices are still editable before a journal-bound restore. + * @param processIntent Native picker and selection requests. + * @param modifier Root content placement. + * @author Dmitriy Moroz + */ +@Composable +internal fun RestoreBackupScreen( + state: BackupPageState, + isEnabled: Boolean, + canEditSelection: Boolean, + processIntent: (BackupIntent) -> Unit, + modifier: Modifier = Modifier +) { + Column(modifier) { + Text( + Localization.string("backup_restore_description"), + style = MaterialTheme.typography.bodyLarge + ) + Spacer(Modifier.height(16.dp)) + Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { + OutlinedButton( + onClick = { processIntent(BackupIntent.ChooseFile) }, + enabled = isEnabled, + modifier = Modifier.heightIn(min = 48.dp), + ) { Text(Localization.string("backup_choose_file")) } + } + state.inspection?.let { archive -> + Spacer(Modifier.height(16.dp)) + BackupArchiveCard(archive) + if (archive.skippedCount > 0) Text( + Localization.string( + "backup_skipped", + archive.skippedCount + ), color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(Modifier.height(16.dp)) + BackupSelectionList(state, isEnabled && canEditSelection, processIntent) + Spacer(Modifier.height(16.dp)) + Text( + Localization.string("backup_secrets_warning"), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } +} diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/service/BackupChangesGatewayImpl.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/service/BackupChangesGatewayImpl.kt new file mode 100644 index 000000000..e4558037c --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/service/BackupChangesGatewayImpl.kt @@ -0,0 +1,24 @@ +package com.shifthackz.aisdv1.presentation.backup.service + +import com.shifthackz.aisdv1.core.localization.Localization +import com.shifthackz.aisdv1.domain.entity.backup.BackupCategory +import com.shifthackz.aisdv1.domain.gateway.backup.BackupChangesGateway +import com.shifthackz.aisdv1.domain.preference.PreferenceManager +import com.shifthackz.aisdv1.presentation.components.service.storage.StorageUsageObserver + +/** + * Keeps retained UI snapshots consistent with committed portable data without feature-to-presentation dependencies. + * @param preferences Current checked settings and their shared invalidation flow. + * @param storage Shared storage usage revision observed by Settings and storage screens. + * @author Dmitriy Moroz + */ +internal class BackupChangesGatewayImpl( + private val preferences: PreferenceManager, + private val storage: StorageUsageObserver +) : BackupChangesGateway { + override suspend fun notifyChanged(categories: Set) { + if (BackupCategory.SETTINGS in categories) Localization.setLanguageCode(preferences.languageCode.takeIf { it.isNotBlank() }) + if (categories.isNotEmpty()) preferences.refresh() + if (BackupCategory.GALLERY in categories) storage.notifyChanged() + } +} diff --git a/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/welcome/RestoreWelcomeScreen.kt b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/welcome/RestoreWelcomeScreen.kt new file mode 100644 index 000000000..d6c66f01e --- /dev/null +++ b/presentation/backup/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/backup/welcome/RestoreWelcomeScreen.kt @@ -0,0 +1,98 @@ +package com.shifthackz.aisdv1.presentation.backup.welcome + +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.aspectRatio +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.widthIn +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import com.shifthackz.aisdv1.core.localization.Localization +import com.shifthackz.aisdv1.presentation.backup.generated.resources.Res +import com.shifthackz.aisdv1.presentation.backup.generated.resources.backup_welcome +import com.shifthackz.aisdv1.presentation.components.theme.global.persistentTopAppBarWindowInsets +import com.shifthackz.aisdv1.presentation.components.widget.action.PrimaryActionButton +import com.shifthackz.aisdv1.presentation.components.widget.action.ScreenActionBar +import com.shifthackz.aisdv1.presentation.components.widget.action.SecondaryActionButton +import org.jetbrains.compose.resources.painterResource + +/** + * Invites first-launch recovery with branded artwork and the same pinned action geometry as setup. + * @param isEnabled Whether a durable navigation transition can start. + * @param onRestore Opens restore-only recovery. + * @param onContinue Continues through mandatory provider setup. + * @param modifier Root full-screen layout. + * @author Dmitriy Moroz + */ +@Composable +internal fun RestoreWelcomeScreen( + isEnabled: Boolean, + onRestore: () -> Unit, + onContinue: () -> Unit, + modifier: Modifier = Modifier, +) { + Scaffold( + modifier = modifier, + containerColor = MaterialTheme.colorScheme.surface, + topBar = { + Spacer( + Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surface) + .windowInsetsPadding(persistentTopAppBarWindowInsets()) + ) + }, + bottomBar = { + ScreenActionBar(containerColor = MaterialTheme.colorScheme.surface) { + SecondaryActionButton(onClick = onContinue, isEnabled = isEnabled) { + Text(Localization.string("backup_continue")) + } + PrimaryActionButton(onClick = onRestore, isEnabled = isEnabled) { + Text(Localization.string("backup_restore_from_file")) + } + } + }, + ) { padding -> + Column( + modifier = Modifier.padding(padding).fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(horizontal = 16.dp, vertical = 24.dp), + verticalArrangement = Arrangement.Center, + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Image( + painter = painterResource(Res.drawable.backup_welcome), + contentDescription = null, + modifier = Modifier.widthIn(max = 320.dp).fillMaxWidth().aspectRatio(1.25f), + ) + Spacer(Modifier.height(24.dp)) + Text( + Localization.string("backup_welcome_title"), + modifier = Modifier.widthIn(max = 480.dp), + style = MaterialTheme.typography.headlineMedium, + textAlign = TextAlign.Center, + ) + Spacer(Modifier.height(16.dp)) + Text( + Localization.string("backup_welcome_description"), + modifier = Modifier.widthIn(max = 480.dp), + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + } + } +} diff --git a/presentation/backup/src/iosMain/kotlin/com/shifthackz/aisdv1/presentation/backup/platform/BackupDateFormatter.ios.kt b/presentation/backup/src/iosMain/kotlin/com/shifthackz/aisdv1/presentation/backup/platform/BackupDateFormatter.ios.kt new file mode 100644 index 000000000..7fdc8a361 --- /dev/null +++ b/presentation/backup/src/iosMain/kotlin/com/shifthackz/aisdv1/presentation/backup/platform/BackupDateFormatter.ios.kt @@ -0,0 +1,16 @@ +package com.shifthackz.aisdv1.presentation.backup.platform + +import platform.Foundation.NSDate +import platform.Foundation.NSDateFormatter +import platform.Foundation.NSDateFormatterMediumStyle +import platform.Foundation.NSDateFormatterShortStyle + +/** + * Formats a UTC timestamp using the current platform locale and date/time conventions. + * @param epochMillis Archive creation time in milliseconds since the Unix epoch. + * @author Dmitriy Moroz + */ +internal actual fun formatBackupCreatedAt(epochMillis: Long): String = NSDateFormatter().apply { + dateStyle = NSDateFormatterMediumStyle + timeStyle = NSDateFormatterShortStyle +}.stringFromDate(NSDate(timeIntervalSinceReferenceDate = epochMillis / 1000.0 - 978307200.0)) diff --git a/presentation/backup/src/iosMain/kotlin/com/shifthackz/aisdv1/presentation/backup/platform/BackupDocumentLauncher.ios.kt b/presentation/backup/src/iosMain/kotlin/com/shifthackz/aisdv1/presentation/backup/platform/BackupDocumentLauncher.ios.kt new file mode 100644 index 000000000..78698f0fb --- /dev/null +++ b/presentation/backup/src/iosMain/kotlin/com/shifthackz/aisdv1/presentation/backup/platform/BackupDocumentLauncher.ios.kt @@ -0,0 +1,130 @@ +package com.shifthackz.aisdv1.presentation.backup.platform + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import com.shifthackz.aisdv1.domain.entity.backup.BackupExport +import platform.Foundation.NSURL +import platform.UIKit.UIApplication +import platform.UIKit.UIDocumentPickerDelegateProtocol +import platform.UIKit.UIDocumentPickerViewController +import platform.UIKit.UIViewController +import platform.UIKit.UIWindow +import platform.UniformTypeIdentifiers.UTTypeData +import platform.darwin.NSObject + +/** + * Retains UIKit delegate callbacks for import/export and treats picker cancellation as neutral. + * @param onPicked Receives a sandbox-copy URL; no persistent security-scoped grant is retained. + * @param onExported Receives true only after UIKit confirms completed export. + * @author Dmitriy Moroz + */ +@Composable +actual fun rememberBackupDocumentLauncher( + onPicked: (String?) -> Unit, + onExported: (String?, Boolean, String) -> Unit +): BackupDocumentLauncher { + val picked = rememberUpdatedState(onPicked) + val exported = rememberUpdatedState(onExported) + val launcher = + remember { + IosBackupDocumentLauncher( + { picked.value(it) }, + { hasExported, handle -> exported.value(null, hasExported, handle) }) + } + DisposableEffect(launcher) { onDispose { launcher.release() } } + return launcher +} + +/** + * Owns the native modal and delegate until its result is delivered. + * @param onPicked Import result callback receiving only a sandbox-copy document reference. + * @param onExported Export success callback, false for cancellation. + * @author Dmitriy Moroz + */ +private class IosBackupDocumentLauncher( + private val onPicked: (String?) -> Unit, + private val onExported: (Boolean, String) -> Unit, +) : BackupDocumentLauncher { + private val delegate = BackupDocumentDelegate(::onDocumentsPicked, ::onPickerCanceled) + private var picker: UIDocumentPickerViewController? = null + private var exportHandle: String = "" + private var isExporting = false + + override fun open() { + isExporting = false + present( + UIDocumentPickerViewController( + forOpeningContentTypes = listOf(UTTypeData), + asCopy = true + ) + ) + } + + override fun export(backup: BackupExport) { + exportHandle = backup.handle + isExporting = true + val url = NSURL.URLWithString(backup.document) + if (url == null) { + onExported(false, exportHandle); return + } + present(UIDocumentPickerViewController(forExportingURLs = listOf(url), asCopy = true)) + } + + private fun present(controller: UIDocumentPickerViewController) { + val application = UIApplication.sharedApplication + val root = application.keyWindow?.rootViewController + ?: application.windows.filterIsInstance() + .firstOrNull { it.isKeyWindow() }?.rootViewController + val presenter = root?.topmost() + if (presenter == null) { + if (isExporting) onExported(false, exportHandle) else onPicked(null); return + } + picker = controller + controller.delegate = delegate + controller.allowsMultipleSelection = false + presenter.presentViewController(controller, true, null) + } + + private fun onDocumentsPicked(didPickDocumentsAtURLs: List<*>) { + if (isExporting) onExported(true, exportHandle) + else onPicked((didPickDocumentsAtURLs.firstOrNull() as? NSURL)?.absoluteString) + picker?.delegate = null + picker = null + } + + private fun onPickerCanceled() { + if (isExporting) onExported(false, exportHandle) else onPicked(null) + picker?.delegate = null + picker = null + } + + fun release() { + picker?.delegate = null + picker?.dismissViewControllerAnimated(false, null) + picker = null + } + + private fun UIViewController.topmost(): UIViewController = + presentedViewController?.topmost() ?: this +} + +/** + * Bridges Objective-C picker events without mixing Objective-C and Kotlin interface inheritance. + * @param onPicked Selected sandbox document URLs or completed export destinations. + * @param onCanceled Neutral picker cancellation. + * @author Dmitriy Moroz + */ +private class BackupDocumentDelegate( + private val onPicked: (List<*>) -> Unit, + private val onCanceled: () -> Unit, +) : NSObject(), UIDocumentPickerDelegateProtocol { + override fun documentPicker( + controller: UIDocumentPickerViewController, + didPickDocumentsAtURLs: List<*> + ) = onPicked(didPickDocumentsAtURLs) + + override fun documentPickerWasCancelled(controller: UIDocumentPickerViewController) = + onCanceled() +} diff --git a/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/action/PrimaryActionButton.kt b/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/action/PrimaryActionButton.kt new file mode 100644 index 000000000..cdb3bd084 --- /dev/null +++ b/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/action/PrimaryActionButton.kt @@ -0,0 +1,32 @@ +package com.shifthackz.aisdv1.presentation.components.widget.action + +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.material3.Button +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp + +/** + * 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 +fun PrimaryActionButton( + 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 + ) +} diff --git a/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/action/ScreenActionBar.kt b/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/action/ScreenActionBar.kt new file mode 100644 index 000000000..d8c8b6ba3 --- /dev/null +++ b/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/action/ScreenActionBar.kt @@ -0,0 +1,40 @@ +package com.shifthackz.aisdv1.presentation.components.widget.action + +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.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +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 containerColor Screen surface extended behind the actions and bottom safe area. + * @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 +fun ScreenActionBar( + modifier: Modifier = Modifier, + containerColor: Color = MaterialTheme.colorScheme.background, + verticalArrangement: Arrangement.Vertical = Arrangement.spacedBy(8.dp), + content: @Composable ColumnScope.() -> Unit, +) { + Column( + modifier = modifier.fillMaxWidth() + .background(containerColor) + .windowInsetsPadding(persistentBottomBarWindowInsets()) + .padding(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 16.dp), + verticalArrangement = verticalArrangement, + content = content, + ) +} diff --git a/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/action/SecondaryActionButton.kt b/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/action/SecondaryActionButton.kt new file mode 100644 index 000000000..1a1bcf514 --- /dev/null +++ b/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/action/SecondaryActionButton.kt @@ -0,0 +1,32 @@ +package com.shifthackz.aisdv1.presentation.components.widget.action + +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.material3.OutlinedButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp + +/** + * 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 +fun SecondaryActionButton( + 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/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupCustomSelectionTest.kt b/presentation/configuration/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupCustomSelectionTest.kt index 7bcf903ba..a58ce7b54 100644 --- a/presentation/configuration/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupCustomSelectionTest.kt +++ b/presentation/configuration/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/ServerSetupCustomSelectionTest.kt @@ -2,6 +2,7 @@ package com.shifthackz.aisdv1.presentation.configuration.setup import com.shifthackz.aisdv1.domain.entity.LocalAiModel import com.shifthackz.aisdv1.domain.entity.ServerSource +import com.shifthackz.aisdv1.presentation.configuration.setup.component.mainButtonEnabled import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith @@ -55,6 +56,74 @@ class ServerSetupCustomSelectionTest( assertEquals(true, refreshed.catalogModels(custom.type).single().selected) } + @Test + fun `given custom model enabled, user selects undownloaded catalog model, expected setup disabled`() { + // Given + val catalog = custom.copy(id = "catalog-model", selected = false, downloaded = false) + val initial = ServerSetupState(mode = source, step = ServerSetupState.Step.CONFIGURE) + .withCatalogResult(custom.type, listOf(custom, catalog), LocalCatalogStatus.READY) + .withAllowCustomModel(true) + + // When + val selected = initial.withSelectedLocalModel( + initial.catalogModels(custom.type).first { it.id == catalog.id }) + + // Then + assertEquals(true, selected.localCustomModel) + assertEquals( + true, + selected.catalogModels(custom.type).first { it.id == catalog.id }.selected + ) + assertEquals(false, selected.mainButtonEnabled) + } + + @Test + fun `given custom model enabled, user selects downloaded catalog model, expected setup enabled`() { + // Given + val catalog = custom.copy(id = "catalog-model", selected = false, downloaded = true) + val initial = ServerSetupState(mode = source, step = ServerSetupState.Step.CONFIGURE) + .withCatalogResult(custom.type, listOf(custom, catalog), LocalCatalogStatus.READY) + .withAllowCustomModel(true) + + // When + val selected = initial.withSelectedLocalModel( + initial.catalogModels(custom.type).first { it.id == catalog.id }) + + // Then + assertEquals(true, selected.mainButtonEnabled) + } + + @Test + fun `given custom model enabled, user selects custom entry, expected setup enabled without catalog download`() { + // Given + val initial = ServerSetupState(mode = source, step = ServerSetupState.Step.CONFIGURE) + .withCatalogResult( + custom.type, + listOf(custom.copy(downloaded = false)), + LocalCatalogStatus.READY + ) + + // When + val selected = initial.withAllowCustomModel(true) + + // Then + assertEquals(true, selected.mainButtonEnabled) + } + + @Test + fun `given custom model disabled, no model is selected, expected setup disabled`() { + // Given + val initial = ServerSetupState(mode = source, step = ServerSetupState.Step.CONFIGURE) + .withCatalogResult(custom.type, listOf(custom), LocalCatalogStatus.READY) + .withAllowCustomModel(true) + + // When + val selected = initial.withAllowCustomModel(false) + + // Then + assertEquals(false, selected.mainButtonEnabled) + } + companion object { /** * Selects provider forms that expose the shared standard custom-model switch. 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 6685a238e..a0ddc2277 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 @@ -1,5 +1,6 @@ package com.shifthackz.aisdv1.presentation.configuration.setup.component +import com.shifthackz.aisdv1.presentation.components.widget.action.SecondaryActionButton import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.expandVertically import androidx.compose.animation.fadeIn @@ -48,7 +49,7 @@ internal fun LocalModelDownloadAction( exit = shrinkVertically() + fadeOut(), ) { Column { - SetupSecondaryAction( + SecondaryActionButton( isEnabled = action.isEnabled, onClick = { processIntent(if (isCurrentBatch) ServerSetupIntent.CancelModelDownloads else ServerSetupIntent.DownloadAllModels) }, ) { 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 2cf095fa0..ead384cd0 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,5 +1,8 @@ package com.shifthackz.aisdv1.presentation.configuration.setup.component +import com.shifthackz.aisdv1.presentation.components.widget.action.SecondaryActionButton +import com.shifthackz.aisdv1.presentation.components.widget.action.PrimaryActionButton +import com.shifthackz.aisdv1.presentation.components.widget.action.ScreenActionBar import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable @@ -29,7 +32,7 @@ internal fun OpenAiOAuthActionBar( processIntent: (ServerSetupIntent) -> Unit, modifier: Modifier = Modifier, ) { - SetupActionBar(modifier = modifier) { + ScreenActionBar(modifier = modifier) { when (state.openAiOAuthPhase) { OpenAiOAuthSetupPhase.SIGNED_OUT -> OAuthPrimaryAction( label = Localization.string("open_ai_oauth_login"), @@ -91,7 +94,7 @@ private fun OAuthPrimaryAction( isEnabled: Boolean = true, onClick: () -> Unit, ) { - SetupPrimaryAction( + PrimaryActionButton( modifier = modifier, isEnabled = isEnabled, onClick = onClick, @@ -115,7 +118,7 @@ private fun OAuthSecondaryAction( onClick: () -> Unit, modifier: Modifier = Modifier, ) { - SetupSecondaryAction( + SecondaryActionButton( modifier = modifier, onClick = onClick, ) { 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 b977a077a..b14faf4b7 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 @@ -330,6 +330,11 @@ internal fun ServerSetupState.ValidationError.message( ServerSetupState.ValidationError.InvalidUrl -> Localization.string("error_invalid_url") } +/** + * Enables setup only for the selected usable model; allowing custom paths does not bypass catalog downloads. + * Authorization recovery and provider-specific account requirements remain authoritative. + * @author Dmitriy Moroz + */ internal val ServerSetupState.mainButtonEnabled: Boolean get() = when { isAuthorizationStorageBusy -> false @@ -340,15 +345,12 @@ internal val ServerSetupState.mainButtonEnabled: Boolean ServerSetupState.Step.SOURCE -> true ServerSetupState.Step.CONFIGURE -> when (mode) { ServerSource.OPEN_AI_OAUTH -> openAiOAuthAccount != null && !openAiOAuthBusy - ServerSource.LOCAL_MNN -> isLocalMnnCustomModel || localMnnModels.any { it.selected && it.downloaded } - ServerSource.LOCAL_MICROSOFT_ONNX -> localOnnxCustomModel || - localOnnxModels.any { it.selected && it.downloaded } - - ServerSource.LOCAL_GOOGLE_MEDIA_PIPE -> localMediaPipeCustomModel || - localMediaPipeModels.any { it.selected && it.downloaded } - - ServerSource.LOCAL_STABLE_DIFFUSION_CPP -> localSdxlCustomModel || - localSdxlModels.any { it.selected && it.downloaded } + ServerSource.LOCAL_MNN, + ServerSource.LOCAL_MICROSOFT_ONNX, + ServerSource.LOCAL_GOOGLE_MEDIA_PIPE, + ServerSource.LOCAL_STABLE_DIFFUSION_CPP -> localModels.any { model -> + model.selected && if (model.isCustom) localCustomModel else model.downloaded + } ServerSource.LOCAL_APPLE_CORE_ML -> localCoreMlModels.any { model -> model.selected && @@ -367,6 +369,10 @@ internal val ServerSetupState.mainButtonEnabled: Boolean } } +/** + * Identifies the platform-neutral custom entry, whose source files are selected separately from catalog downloads. + * @author Dmitriy Moroz + */ internal val ServerSetupState.LocalModel.isCustom: Boolean get() = id == LocalAiModel.CustomOnnx.id || id == LocalAiModel.CustomMediaPipe.id || 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 deleted file mode 100644 index 52f6cf9a3..000000000 --- a/presentation/configuration/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/configuration/setup/component/SetupActionBar.kt +++ /dev/null @@ -1,87 +0,0 @@ -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 1bd67e3b4..3e8c11b1e 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,6 +2,8 @@ package com.shifthackz.aisdv1.presentation.configuration.setup.content +import com.shifthackz.aisdv1.presentation.components.widget.action.PrimaryActionButton +import com.shifthackz.aisdv1.presentation.components.widget.action.ScreenActionBar import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -25,8 +27,6 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.RectangleShape 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 @@ -108,11 +108,11 @@ fun ServerSetupContent( processIntent = processIntent ) } else { - SetupActionBar(verticalArrangement = Arrangement.Top) { + ScreenActionBar(verticalArrangement = Arrangement.Top) { if (state.step == ServerSetupState.Step.CONFIGURE && state.mode.localCatalogType != null) { LocalModelDownloadAction(state, processIntent) } - SetupPrimaryAction( + PrimaryActionButton( isEnabled = !state.loadingConfiguration && state.mainButtonEnabled, onClick = { processIntent(ServerSetupIntent.MainButtonClick) }, ) { diff --git a/presentation/onboarding/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/onboarding/OnBoardingViewModelSplashSourceTest.kt b/presentation/onboarding/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/onboarding/OnBoardingViewModelSplashSourceTest.kt index 6a36467e4..7fea14de8 100644 --- a/presentation/onboarding/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/onboarding/OnBoardingViewModelSplashSourceTest.kt +++ b/presentation/onboarding/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/onboarding/OnBoardingViewModelSplashSourceTest.kt @@ -2,104 +2,81 @@ package com.shifthackz.aisdv1.presentation.onboarding import com.shifthackz.aisdv1.core.common.appbuild.BuildInfoProvider import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider -import com.shifthackz.aisdv1.domain.entity.DarkThemeToken -import com.shifthackz.aisdv1.domain.preference.PreferenceManager -import com.shifthackz.aisdv1.domain.usecase.splash.SplashNavigationUseCase import com.shifthackz.aisdv1.core.navigation.LaunchSource import com.shifthackz.aisdv1.core.navigation.router.OnBoardingRouter -import io.mockk.coEvery +import com.shifthackz.aisdv1.domain.entity.DarkThemeToken +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage +import com.shifthackz.aisdv1.domain.preference.PreferenceManager +import com.shifthackz.aisdv1.domain.usecase.backup.SetBackupStartupStageUseCase import io.mockk.every import io.mockk.mockk import io.mockk.verify -import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.StandardTestDispatcher -import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runTest -import org.junit.Before -import org.junit.Ignore +import kotlinx.coroutines.test.setMain +import org.junit.After import org.junit.Test -@Ignore("ToDo: Investigate why sometimes tests fail on remote worker due to race-conditions.") @OptIn(ExperimentalCoroutinesApi::class) class OnBoardingViewModelSplashSourceTest { + private val router = mockk(relaxed = true) + private val preferences = mockk(relaxed = true) { + every { designDarkThemeToken } returns DarkThemeToken.FRAPPE.toString() + } + private val stage = mockk(relaxed = true) - private val stubRouter = mockk(relaxed = true) - private val stubSplashNavigationUseCase = mockk() - private val stubPreferenceManager = mockk() - private val stubBuildInfoProvider = mockk() - - @Before - fun initialize() { - every { - stubPreferenceManager::designDarkThemeToken.get() - } returns DarkThemeToken.FRAPPE.toString() - - every { - stubPreferenceManager::onBoardingComplete.set(any()) - } returns Unit - - every { - stubBuildInfoProvider.toString() - } returns "" + @After + fun tearDown() { + Dispatchers.resetMain() } @Test - fun `given on boarding view model splash source, received Navigate intent from splash, expected navigation processed`() = + fun `given first launch onboarding, user completes onboarding, expected durable invitation and no old loader navigation`() = runTest { // Given - - coEvery { - stubSplashNavigationUseCase() - } returns SplashNavigationUseCase.Action.LAUNCH_HOME + val dispatcher = StandardTestDispatcher(testScheduler) + Dispatchers.setMain(dispatcher) + val viewModel = OnBoardingViewModel( + mockk(relaxed = true), + LaunchSource.SPLASH, + mockk { every { io } returns dispatcher; every { immediate } returns dispatcher }, + router, + preferences, + BuildInfoProvider.stub, + stage + ) // When - val viewModel = createViewModel(LaunchSource.SPLASH) - viewModel.processIntent(OnBoardingIntent.Navigate) advanceUntilIdle() - // Then - verify { - stubRouter.navigateToPostOnBoardingConfigLoader() - } - + verify { stage(BackupStartupStage.INVITATION); router.navigateToBackupWelcome() } + verify(exactly = 0) { router.navigateBack() } } @Test - fun `given on boarding view model splash source, received Navigate intent from settings, expected navigateBack processed`() = + fun `given settings onboarding, user completes walkthrough, expected return without first launch invitation`() = runTest { // Given - - val viewModel = createViewModel(LaunchSource.SETTINGS) - + val dispatcher = StandardTestDispatcher(testScheduler) + Dispatchers.setMain(dispatcher) + val viewModel = OnBoardingViewModel( + mockk(relaxed = true), + LaunchSource.SETTINGS, + mockk { every { io } returns dispatcher; every { immediate } returns dispatcher }, + router, + preferences, + BuildInfoProvider.stub, + stage + ) // When viewModel.processIntent(OnBoardingIntent.Navigate) - + advanceUntilIdle() // Then - verify { - stubRouter.navigateBack() - } - + verify { router.navigateBack() } + verify(exactly = 0) { stage(any()) } } - - private fun TestScope.createViewModel( - source: LaunchSource, - ): OnBoardingViewModel { - val dispatcher = StandardTestDispatcher(testScheduler) - val dispatchersProvider = object : DispatchersProvider { - override val io: CoroutineDispatcher = dispatcher - override val ui: CoroutineDispatcher = dispatcher - override val immediate: CoroutineDispatcher = dispatcher - } - return OnBoardingViewModel( - diagnostics = mockk(relaxed = true), - launchSource = source, - dispatchersProvider = dispatchersProvider, - router = stubRouter, - splashNavigationUseCase = stubSplashNavigationUseCase, - preferenceManager = stubPreferenceManager, - buildInfoProvider = stubBuildInfoProvider, - ) - } } diff --git a/presentation/onboarding/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/onboarding/OnBoardingViewModel.kt b/presentation/onboarding/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/onboarding/OnBoardingViewModel.kt index faf6e2540..c6f9d0e3e 100644 --- a/presentation/onboarding/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/onboarding/OnBoardingViewModel.kt +++ b/presentation/onboarding/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/onboarding/OnBoardingViewModel.kt @@ -7,25 +7,25 @@ import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider import com.shifthackz.aisdv1.core.mvi.diagnostics.UiDiagnostics import com.shifthackz.aisdv1.core.mvi.BaseMviViewModel import com.shifthackz.aisdv1.core.mvi.EmptyEffect +import com.shifthackz.aisdv1.domain.entity.backup.BackupStartupStage +import com.shifthackz.aisdv1.domain.usecase.backup.SetBackupStartupStageUseCase import com.shifthackz.aisdv1.domain.entity.DarkThemeToken import com.shifthackz.aisdv1.domain.preference.PreferenceManager -import com.shifthackz.aisdv1.domain.usecase.splash.SplashNavigationUseCase import com.shifthackz.aisdv1.core.navigation.LaunchSource import com.shifthackz.aisdv1.core.navigation.router.OnBoardingRouter -import com.shifthackz.aisdv1.presentation.onboarding.navigation.postOnBoardingNavigation import kotlinx.coroutines.withContext /** - * Initializes onboarding previews from saved appearance and advances to the correct post-onboarding route. + * Initializes onboarding previews and replaces first-launch completion with the restore invitation. * Completion is persisted before navigation; a settings launch returns to the caller, while first launch - * rechecks configuration off the UI dispatcher. + * persists recovery progression off the UI dispatcher before navigating. * * @param diagnostics Optional bounded observer for MVI state transitions. * @param launchSource Distinguishes first-launch completion from revisiting onboarding through settings. * @param dispatchersProvider Runs configuration checks on IO and publishes navigation on the UI dispatcher. * @param router Receives setup, loader or back navigation after completion. - * @param splashNavigationUseCase Reassesses saved configuration after first-launch onboarding. - * @param preferenceManager Supplies preview appearance and stores the completed-onboarding flag. + * @param setBackupStartupStage Persists the fresh-install restore invitation before onboarding is consumed. + * @param preferenceManager Supplies saved preview appearance; the checked startup transition owns onboarding completion. * @param buildInfoProvider Supplies the version displayed in the appearance preview. * * @author Dmitriy Moroz @@ -35,9 +35,9 @@ class OnBoardingViewModel( val launchSource: LaunchSource, private val dispatchersProvider: DispatchersProvider, private val router: OnBoardingRouter, - private val splashNavigationUseCase: SplashNavigationUseCase, private val preferenceManager: PreferenceManager, private val buildInfoProvider: BuildInfoProvider, + private val setBackupStartupStage: SetBackupStartupStageUseCase, ) : BaseMviViewModel( diagnostics = diagnostics, diagnosticScreen = NavigationDestination.ON_BOARDING.asDiagnosticScreen(), @@ -62,16 +62,10 @@ class OnBoardingViewModel( } private fun navigate() { - preferenceManager.onBoardingComplete = true when (launchSource) { LaunchSource.SPLASH -> launch(dispatchersProvider.io) { - runCatching { splashNavigationUseCase() } - .onSuccess { action -> - withContext(dispatchersProvider.immediate) { - router.postOnBoardingNavigation(action) - } - } - .onFailure { } + setBackupStartupStage(BackupStartupStage.INVITATION) + withContext(dispatchersProvider.immediate) { router.navigateToBackupWelcome() } } LaunchSource.SETTINGS -> router.navigateBack() diff --git a/presentation/onboarding/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/onboarding/di/OnboardingViewModelModule.kt b/presentation/onboarding/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/onboarding/di/OnboardingViewModelModule.kt index f539ace76..88e8ec089 100644 --- a/presentation/onboarding/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/onboarding/di/OnboardingViewModelModule.kt +++ b/presentation/onboarding/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/onboarding/di/OnboardingViewModelModule.kt @@ -17,7 +17,7 @@ val onboardingViewModelModule = module { launchSource = launchSource, dispatchersProvider = get(), router = router, - splashNavigationUseCase = get(), + setBackupStartupStage = get(), preferenceManager = get(), buildInfoProvider = get(), ) diff --git a/presentation/onboarding/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/onboarding/navigation/OnBoardingNavigation.kt b/presentation/onboarding/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/onboarding/navigation/OnBoardingNavigation.kt deleted file mode 100644 index 17717243e..000000000 --- a/presentation/onboarding/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/onboarding/navigation/OnBoardingNavigation.kt +++ /dev/null @@ -1,20 +0,0 @@ -package com.shifthackz.aisdv1.presentation.onboarding.navigation - -import com.shifthackz.aisdv1.domain.usecase.splash.SplashNavigationUseCase -import com.shifthackz.aisdv1.core.navigation.router.OnBoardingRouter - -/** - * Maps the completed onboarding decision to setup or configuration loading. - * - * @param action Domain launch decision produced after the relevant configuration checks. - * - * @author Dmitriy Moroz - */ -fun OnBoardingRouter.postOnBoardingNavigation( - action: SplashNavigationUseCase.Action, -) = when (action) { - SplashNavigationUseCase.Action.LAUNCH_ONBOARDING, - SplashNavigationUseCase.Action.LAUNCH_SERVER_SETUP -> navigateToServerSetupAfterOnBoarding() - - SplashNavigationUseCase.Action.LAUNCH_HOME -> navigateToPostOnBoardingConfigLoader() -} diff --git a/presentation/settings/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModelTest.kt b/presentation/settings/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModelTest.kt index 6a37641a3..5fbc5e8ee 100644 --- a/presentation/settings/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModelTest.kt +++ b/presentation/settings/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModelTest.kt @@ -409,6 +409,8 @@ private object TestBuildInfoProvider : BuildInfoProvider { } private class TestSettingsRouter : SettingsRouter { + override fun navigateToBackup() = Unit + var serverSetupSource: LaunchSource? = null var storageUsageOpened = false var networkUsageOpened = false diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsContentTypes.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsContentTypes.kt index 133428fcc..ff8204cc8 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsContentTypes.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsContentTypes.kt @@ -38,6 +38,7 @@ internal fun SettingsListItem.contentType(): SettingsContentType = when (this) { SettingsListItem.VERSION -> SettingsContentType.FOOTER SettingsListItem.CONFIGURATION, + SettingsListItem.BACKUP, SettingsListItem.BENCHMARK, SettingsListItem.CREDITS, SettingsListItem.CONNECTION_TIMEOUT, diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsIntent.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsIntent.kt index cdeef8813..15e2391fd 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsIntent.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsIntent.kt @@ -20,6 +20,9 @@ sealed interface SettingsIntent : MviIntent { */ data object NavigateConfiguration : SettingsIntent + /** Opens portable selective backup and restore. @author Dmitriy Moroz */ + data object NavigateBackup : SettingsIntent + /** * Opens the generation waiting-limit picker. * @@ -174,6 +177,7 @@ sealed interface SettingsIntent : MviIntent { data class DarkTheme(override val flag: Boolean) : UpdateFlag } + data class NewColorToken(val token: ColorToken) : SettingsIntent data class NewDarkThemeToken(val token: DarkThemeToken) : SettingsIntent diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItem.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItem.kt index b25f725a7..55c59dd1d 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItem.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItem.kt @@ -9,6 +9,7 @@ package com.shifthackz.aisdv1.presentation.settings internal enum class SettingsListItem { SERVER_HEADER, CONFIGURATION, + BACKUP, BENCHMARK, CREDITS, CONNECTION_TIMEOUT, diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItems.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItems.kt index 43c7d15e8..4526c62da 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItems.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItems.kt @@ -23,6 +23,7 @@ internal fun settingsListItems( if (!state.onBoardingDemo) { add(SettingsListItem.SERVER_HEADER) add(SettingsListItem.CONFIGURATION) + add(SettingsListItem.BACKUP) add(SettingsListItem.BENCHMARK) if (state.showStabilityAiCredits) add(SettingsListItem.CREDITS) if (state.showNetworkTimeoutSettings) { diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModel.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModel.kt index 61d3f4887..051732b38 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModel.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModel.kt @@ -214,6 +214,8 @@ class SettingsViewModel( it.copy(screenModal = SettingsModal.None) } + SettingsIntent.NavigateBackup -> router.navigateToBackup() + SettingsIntent.NavigateConfiguration -> router.navigateToServerSetup( LaunchSource.SETTINGS, ) diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/content/SettingsContent.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/content/SettingsContent.kt index 3bc8a17eb..50369bb77 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/content/SettingsContent.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/content/SettingsContent.kt @@ -66,6 +66,7 @@ internal fun ContentSettingsState( when (row) { SettingsListItem.SERVER_HEADER, SettingsListItem.CONFIGURATION, + SettingsListItem.BACKUP, SettingsListItem.BENCHMARK, SettingsListItem.CREDITS, SettingsListItem.CONNECTION_TIMEOUT, diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/section/SettingsServerSection.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/section/SettingsServerSection.kt index 73d3a302e..ec0978958 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/section/SettingsServerSection.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/section/SettingsServerSection.kt @@ -1,5 +1,6 @@ package com.shifthackz.aisdv1.presentation.settings.section +import androidx.compose.material.icons.filled.Backup import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AccountTree import androidx.compose.material.icons.filled.AutoFixNormal @@ -80,6 +81,16 @@ internal fun SettingsServerSection( ) } + SettingsListItem.BACKUP -> { + SettingsItem( + modifier = itemModifier, + loading = isLoading, + startIcon = Icons.Default.Backup, + text = text("backup_title"), + onClick = { processIntent(SettingsIntent.NavigateBackup) }, + ) + } + SettingsListItem.BENCHMARK -> { SettingsItem( modifier = itemModifier, diff --git a/presentation/splash/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/splash/navigation/SplashNavigation.kt b/presentation/splash/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/splash/navigation/SplashNavigation.kt index d9a90f6a5..f12b87b91 100644 --- a/presentation/splash/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/splash/navigation/SplashNavigation.kt +++ b/presentation/splash/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/splash/navigation/SplashNavigation.kt @@ -14,6 +14,9 @@ fun SplashRouter.postSplashNavigation( action: SplashNavigationUseCase.Action, ) { when (action) { + SplashNavigationUseCase.Action.LAUNCH_BACKUP_WELCOME -> navigateToBackupWelcome() + SplashNavigationUseCase.Action.LAUNCH_INITIAL_RESTORE -> navigateToInitialRestore() + SplashNavigationUseCase.Action.LAUNCH_BACKUP_RESTORE -> navigateToBackupRestore() SplashNavigationUseCase.Action.LAUNCH_ONBOARDING -> navigateToOnBoardingFromSplash() SplashNavigationUseCase.Action.LAUNCH_SERVER_SETUP -> navigateToServerSetupFromSplash() SplashNavigationUseCase.Action.LAUNCH_HOME -> navigateToPostSplashConfigLoader() diff --git a/settings.gradle.kts b/settings.gradle.kts index 3030d06a6..1e85c78b5 100755 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -35,6 +35,7 @@ val modules = listOf( ":demo", ":domain", ":feature:auth", + ":feature:backup", ":feature:openai-oauth", ":feature:benchmark", ":feature:bonsai", @@ -47,6 +48,7 @@ val modules = listOf( ":network", ":presentation:app", ":presentation:benchmark", + ":presentation:backup", ":presentation:components", ":presentation:configuration", ":presentation:debug", diff --git a/storage/schemas/com.shifthackz.aisdv1.storage.db.persistent.PersistentDatabase/14.json b/storage/schemas/com.shifthackz.aisdv1.storage.db.persistent.PersistentDatabase/14.json new file mode 100644 index 000000000..16ff7a3f1 --- /dev/null +++ b/storage/schemas/com.shifthackz.aisdv1.storage.db.persistent.PersistentDatabase/14.json @@ -0,0 +1,551 @@ +{ + "formatVersion": 1, + "database": { + "version": 14, + "identityHash": "3631519f530e6340c0c1728a9cfeedd4", + "entities": [ + { + "tableName": "generation_results", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `image_base_64` TEXT NOT NULL, `original_image_base_64` TEXT NOT NULL, `created_at` INTEGER NOT NULL, `generation_type` TEXT NOT NULL, `prompt` TEXT NOT NULL, `negative_prompt` TEXT NOT NULL, `width` INTEGER NOT NULL, `height` INTEGER NOT NULL, `sampling_steps` INTEGER NOT NULL, `cfg_scale` REAL NOT NULL, `restore_faces` INTEGER NOT NULL, `sampler` TEXT NOT NULL, `seed` TEXT NOT NULL, `sub_seed` TEXT NOT NULL DEFAULT '', `sub_seed_strength` REAL NOT NULL DEFAULT 0.0, `denoising_strength` REAL NOT NULL DEFAULT 0.0, `hidden` INTEGER NOT NULL DEFAULT 0, `liked` INTEGER NOT NULL DEFAULT 0, `model_name` TEXT NOT NULL DEFAULT '', `image_revision` TEXT NOT NULL DEFAULT '')", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "imageBase64", + "columnName": "image_base_64", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "originalImageBase64", + "columnName": "original_image_base_64", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "created_at", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "generationType", + "columnName": "generation_type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "prompt", + "columnName": "prompt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "negativePrompt", + "columnName": "negative_prompt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "width", + "columnName": "width", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "height", + "columnName": "height", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "samplingSteps", + "columnName": "sampling_steps", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "cfgScale", + "columnName": "cfg_scale", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "restoreFaces", + "columnName": "restore_faces", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "sampler", + "columnName": "sampler", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "seed", + "columnName": "seed", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subSeed", + "columnName": "sub_seed", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "subSeedStrength", + "columnName": "sub_seed_strength", + "affinity": "REAL", + "notNull": true, + "defaultValue": "0.0" + }, + { + "fieldPath": "denoisingStrength", + "columnName": "denoising_strength", + "affinity": "REAL", + "notNull": true, + "defaultValue": "0.0" + }, + { + "fieldPath": "hidden", + "columnName": "hidden", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "liked", + "columnName": "liked", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "modelName", + "columnName": "model_name", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "imageRevision", + "columnName": "image_revision", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": ["id"] + }, + "indices": [ + { + "name": "index_generation_results_created_at", + "unique": false, + "columnNames": ["created_at"], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_generation_results_created_at` ON `${TABLE_NAME}` (`created_at`)" + } + ] + }, + { + "tableName": "local_models", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `type` TEXT NOT NULL DEFAULT 'onnx', `name` TEXT NOT NULL, `size` TEXT NOT NULL, `sources` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'onnx'" + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "size", + "columnName": "size", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sources", + "columnName": "sources", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": ["id"] + } + }, + { + "tableName": "hugging_face_models", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `alias` TEXT NOT NULL, `source` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "alias", + "columnName": "alias", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "source", + "columnName": "source", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": ["id"] + } + }, + { + "tableName": "supporters", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT NOT NULL, `date` INTEGER NOT NULL, `message` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "date", + "columnName": "date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "message", + "columnName": "message", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": ["id"] + } + }, + { + "tableName": "benchmark_result", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `created_at` INTEGER NOT NULL, `platform` TEXT NOT NULL, `manufacturer` TEXT NOT NULL, `model` TEXT NOT NULL, `os_version` TEXT NOT NULL, `cpu_name` TEXT NOT NULL, `cpu_cores` INTEGER NOT NULL, `gpu_name` TEXT NOT NULL, `total_ram_mb` INTEGER NOT NULL, `available_ram_mb` INTEGER NOT NULL, `total_vram_mb` INTEGER NOT NULL, `available_vram_mb` INTEGER NOT NULL, `accelerators` TEXT NOT NULL, `cpu_score` INTEGER NOT NULL, `memory_score` INTEGER NOT NULL, `accelerator_score` INTEGER NOT NULL, `total_score` INTEGER NOT NULL, `estimated_time_seconds` INTEGER NOT NULL, `recommended_width` INTEGER NOT NULL, `recommended_height` INTEGER NOT NULL, `recommended_steps` INTEGER NOT NULL, `recommended_cfg` REAL NOT NULL, `recommended_batch` INTEGER NOT NULL, `recommended_providers` TEXT NOT NULL, `recommended_background` INTEGER NOT NULL, `recommended_backend` TEXT NOT NULL, `notes` TEXT NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "created_at", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "platform", + "columnName": "platform", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "manufacturer", + "columnName": "manufacturer", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "model", + "columnName": "model", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "osVersion", + "columnName": "os_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "cpuName", + "columnName": "cpu_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "cpuCores", + "columnName": "cpu_cores", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "gpuName", + "columnName": "gpu_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "totalRamMb", + "columnName": "total_ram_mb", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "availableRamMb", + "columnName": "available_ram_mb", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "totalVramMb", + "columnName": "total_vram_mb", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "availableVramMb", + "columnName": "available_vram_mb", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "accelerators", + "columnName": "accelerators", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "cpuScore", + "columnName": "cpu_score", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "memoryScore", + "columnName": "memory_score", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "acceleratorScore", + "columnName": "accelerator_score", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "totalScore", + "columnName": "total_score", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "estimatedTimeSeconds", + "columnName": "estimated_time_seconds", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendedWidth", + "columnName": "recommended_width", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendedHeight", + "columnName": "recommended_height", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendedSteps", + "columnName": "recommended_steps", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendedCfg", + "columnName": "recommended_cfg", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "recommendedBatch", + "columnName": "recommended_batch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendedProviders", + "columnName": "recommended_providers", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "recommendedBackground", + "columnName": "recommended_background", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendedBackend", + "columnName": "recommended_backend", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "notes", + "columnName": "notes", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": ["id"] + }, + "indices": [ + { + "name": "index_benchmark_result_created_at", + "unique": false, + "columnNames": ["created_at"], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_benchmark_result_created_at` ON `${TABLE_NAME}` (`created_at`)" + } + ] + }, + { + "tableName": "network_usage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`category` TEXT NOT NULL, `bytes` INTEGER NOT NULL, PRIMARY KEY(`category`))", + "fields": [ + { + "fieldPath": "category", + "columnName": "category", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "bytes", + "columnName": "bytes", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": ["category"] + } + }, + { + "tableName": "restore_sessions", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `archiveHandle` TEXT NOT NULL, `selection` TEXT NOT NULL, `isComplete` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "archiveHandle", + "columnName": "archiveHandle", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "selection", + "columnName": "selection", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isComplete", + "columnName": "isComplete", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": ["id"] + } + }, + { + "tableName": "restore_sections", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `category` TEXT NOT NULL, `importedCount` INTEGER NOT NULL, `skippedCount` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `category`))", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "category", + "columnName": "category", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "importedCount", + "columnName": "importedCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "skippedCount", + "columnName": "skippedCount", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": ["sessionId", "category"] + } + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '3631519f530e6340c0c1728a9cfeedd4')" + ] + } +} diff --git a/storage/schemas/com.shifthackz.aisdv1.storage.db.persistent.PersistentDatabase/15.json b/storage/schemas/com.shifthackz.aisdv1.storage.db.persistent.PersistentDatabase/15.json new file mode 100644 index 000000000..3df1ebd68 --- /dev/null +++ b/storage/schemas/com.shifthackz.aisdv1.storage.db.persistent.PersistentDatabase/15.json @@ -0,0 +1,565 @@ +{ + "formatVersion": 1, + "database": { + "version": 15, + "identityHash": "a2342fba7f3aff7e4a2c55e30c1f2094", + "entities": [ + { + "tableName": "generation_results", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `image_base_64` TEXT NOT NULL, `original_image_base_64` TEXT NOT NULL, `created_at` INTEGER NOT NULL, `generation_type` TEXT NOT NULL, `prompt` TEXT NOT NULL, `negative_prompt` TEXT NOT NULL, `width` INTEGER NOT NULL, `height` INTEGER NOT NULL, `sampling_steps` INTEGER NOT NULL, `cfg_scale` REAL NOT NULL, `restore_faces` INTEGER NOT NULL, `sampler` TEXT NOT NULL, `seed` TEXT NOT NULL, `sub_seed` TEXT NOT NULL DEFAULT '', `sub_seed_strength` REAL NOT NULL DEFAULT 0.0, `denoising_strength` REAL NOT NULL DEFAULT 0.0, `hidden` INTEGER NOT NULL DEFAULT 0, `liked` INTEGER NOT NULL DEFAULT 0, `model_name` TEXT NOT NULL DEFAULT '', `image_revision` TEXT NOT NULL DEFAULT '')", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "imageBase64", + "columnName": "image_base_64", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "originalImageBase64", + "columnName": "original_image_base_64", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "created_at", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "generationType", + "columnName": "generation_type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "prompt", + "columnName": "prompt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "negativePrompt", + "columnName": "negative_prompt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "width", + "columnName": "width", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "height", + "columnName": "height", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "samplingSteps", + "columnName": "sampling_steps", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "cfgScale", + "columnName": "cfg_scale", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "restoreFaces", + "columnName": "restore_faces", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "sampler", + "columnName": "sampler", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "seed", + "columnName": "seed", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subSeed", + "columnName": "sub_seed", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "subSeedStrength", + "columnName": "sub_seed_strength", + "affinity": "REAL", + "notNull": true, + "defaultValue": "0.0" + }, + { + "fieldPath": "denoisingStrength", + "columnName": "denoising_strength", + "affinity": "REAL", + "notNull": true, + "defaultValue": "0.0" + }, + { + "fieldPath": "hidden", + "columnName": "hidden", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "liked", + "columnName": "liked", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "modelName", + "columnName": "model_name", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "imageRevision", + "columnName": "image_revision", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": ["id"] + }, + "indices": [ + { + "name": "index_generation_results_created_at", + "unique": false, + "columnNames": ["created_at"], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_generation_results_created_at` ON `${TABLE_NAME}` (`created_at`)" + } + ] + }, + { + "tableName": "local_models", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `type` TEXT NOT NULL DEFAULT 'onnx', `name` TEXT NOT NULL, `size` TEXT NOT NULL, `sources` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'onnx'" + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "size", + "columnName": "size", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sources", + "columnName": "sources", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": ["id"] + } + }, + { + "tableName": "hugging_face_models", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `alias` TEXT NOT NULL, `source` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "alias", + "columnName": "alias", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "source", + "columnName": "source", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": ["id"] + } + }, + { + "tableName": "supporters", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT NOT NULL, `date` INTEGER NOT NULL, `message` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "date", + "columnName": "date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "message", + "columnName": "message", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": ["id"] + } + }, + { + "tableName": "benchmark_result", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `created_at` INTEGER NOT NULL, `platform` TEXT NOT NULL, `manufacturer` TEXT NOT NULL, `model` TEXT NOT NULL, `os_version` TEXT NOT NULL, `cpu_name` TEXT NOT NULL, `cpu_cores` INTEGER NOT NULL, `gpu_name` TEXT NOT NULL, `total_ram_mb` INTEGER NOT NULL, `available_ram_mb` INTEGER NOT NULL, `total_vram_mb` INTEGER NOT NULL, `available_vram_mb` INTEGER NOT NULL, `accelerators` TEXT NOT NULL, `cpu_score` INTEGER NOT NULL, `memory_score` INTEGER NOT NULL, `accelerator_score` INTEGER NOT NULL, `total_score` INTEGER NOT NULL, `estimated_time_seconds` INTEGER NOT NULL, `recommended_width` INTEGER NOT NULL, `recommended_height` INTEGER NOT NULL, `recommended_steps` INTEGER NOT NULL, `recommended_cfg` REAL NOT NULL, `recommended_batch` INTEGER NOT NULL, `recommended_providers` TEXT NOT NULL, `recommended_background` INTEGER NOT NULL, `recommended_backend` TEXT NOT NULL, `notes` TEXT NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "created_at", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "platform", + "columnName": "platform", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "manufacturer", + "columnName": "manufacturer", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "model", + "columnName": "model", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "osVersion", + "columnName": "os_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "cpuName", + "columnName": "cpu_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "cpuCores", + "columnName": "cpu_cores", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "gpuName", + "columnName": "gpu_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "totalRamMb", + "columnName": "total_ram_mb", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "availableRamMb", + "columnName": "available_ram_mb", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "totalVramMb", + "columnName": "total_vram_mb", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "availableVramMb", + "columnName": "available_vram_mb", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "accelerators", + "columnName": "accelerators", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "cpuScore", + "columnName": "cpu_score", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "memoryScore", + "columnName": "memory_score", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "acceleratorScore", + "columnName": "accelerator_score", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "totalScore", + "columnName": "total_score", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "estimatedTimeSeconds", + "columnName": "estimated_time_seconds", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendedWidth", + "columnName": "recommended_width", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendedHeight", + "columnName": "recommended_height", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendedSteps", + "columnName": "recommended_steps", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendedCfg", + "columnName": "recommended_cfg", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "recommendedBatch", + "columnName": "recommended_batch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendedProviders", + "columnName": "recommended_providers", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "recommendedBackground", + "columnName": "recommended_background", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendedBackend", + "columnName": "recommended_backend", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "notes", + "columnName": "notes", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": ["id"] + }, + "indices": [ + { + "name": "index_benchmark_result_created_at", + "unique": false, + "columnNames": ["created_at"], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_benchmark_result_created_at` ON `${TABLE_NAME}` (`created_at`)" + } + ] + }, + { + "tableName": "network_usage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`category` TEXT NOT NULL, `bytes` INTEGER NOT NULL, PRIMARY KEY(`category`))", + "fields": [ + { + "fieldPath": "category", + "columnName": "category", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "bytes", + "columnName": "bytes", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": ["category"] + } + }, + { + "tableName": "restore_sessions", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `archiveHandle` TEXT NOT NULL, `selection` TEXT NOT NULL, `isComplete` INTEGER NOT NULL, `requiresConfiguration` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "archiveHandle", + "columnName": "archiveHandle", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "selection", + "columnName": "selection", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isComplete", + "columnName": "isComplete", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "requiresConfiguration", + "columnName": "requiresConfiguration", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": ["id"] + } + }, + { + "tableName": "restore_sections", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `category` TEXT NOT NULL, `importedCount` INTEGER NOT NULL, `skippedCount` INTEGER NOT NULL, `retainedCredentialProviders` TEXT NOT NULL DEFAULT '', PRIMARY KEY(`sessionId`, `category`))", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "category", + "columnName": "category", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "importedCount", + "columnName": "importedCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "skippedCount", + "columnName": "skippedCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "retainedCredentialProviders", + "columnName": "retainedCredentialProviders", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": ["sessionId", "category"] + } + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'a2342fba7f3aff7e4a2c55e30c1f2094')" + ] + } +} diff --git a/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/db/persistent/PersistentDatabase.kt b/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/db/persistent/PersistentDatabase.kt index 5eb5321c2..1137e620b 100644 --- a/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/db/persistent/PersistentDatabase.kt +++ b/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/db/persistent/PersistentDatabase.kt @@ -1,5 +1,8 @@ package com.shifthackz.aisdv1.storage.db.persistent +import com.shifthackz.aisdv1.storage.db.persistent.entity.RestoreSessionEntity +import com.shifthackz.aisdv1.storage.db.persistent.entity.RestoreSectionEntity +import com.shifthackz.aisdv1.storage.db.persistent.dao.RestoreSessionDao import androidx.room.AutoMigration import androidx.room.ConstructedBy import androidx.room.Database @@ -26,7 +29,7 @@ import com.shifthackz.aisdv1.storage.db.persistent.entity.SupporterEntity /** * Main Room database containing generated images, downloaded models, and app statistics. * - * Schema version 13 adds an opaque image revision so thumbnail caches invalidate on replacement. + * Schema version 15 retains first-launch restore handoffs and typed omission metadata across interruptions. * * @author Dmitriy Moroz */ @@ -40,8 +43,12 @@ import com.shifthackz.aisdv1.storage.db.persistent.entity.SupporterEntity SupporterEntity::class, BenchmarkResultEntity::class, NetworkUsageEntity::class, + RestoreSessionEntity::class, + RestoreSectionEntity::class, ], autoMigrations = [ + AutoMigration(from = 13, to = 14), + AutoMigration(from = 14, to = 15), /** * Added 3 fields to [GenerationResultEntity]: * - [GenerationResultContract.SUB_SEED] @@ -125,41 +132,41 @@ import com.shifthackz.aisdv1.storage.db.persistent.entity.SupporterEntity @ConstructedBy(PersistentDatabaseConstructor::class) internal abstract class PersistentDatabase : RoomDatabase() { /** - * Executes the `generationResultDao` step in the SDAI storage layer. + * Reads and mutates saved gallery images and their metadata. * - * @return Result produced by `generationResultDao`. + * @return The corresponding persistent table access owner. * @author Dmitriy Moroz */ abstract fun generationResultDao(): GenerationResultDao /** - * Executes the `localModelDao` step in the SDAI storage layer. + * Tracks downloaded local model records without changing user-managed sources. * - * @return Result produced by `localModelDao`. + * @return The corresponding persistent table access owner. * @author Dmitriy Moroz */ abstract fun localModelDao(): LocalModelDao /** - * Executes the `huggingFaceModelDao` step in the SDAI storage layer. + * Reads saved Hugging Face model catalog records. * - * @return Result produced by `huggingFaceModelDao`. + * @return The corresponding persistent table access owner. * @author Dmitriy Moroz */ abstract fun huggingFaceModelDao(): HuggingFaceModelDao /** - * Executes the `supporterDao` step in the SDAI storage layer. + * Reads cached supporter records. * - * @return Result produced by `supporterDao`. + * @return The corresponding persistent table access owner. * @author Dmitriy Moroz */ abstract fun supporterDao(): SupporterDao /** - * Executes the `benchmarkResultDao` step in the SDAI storage layer. + * Reads device-specific benchmark history. * - * @return Result produced by `benchmarkResultDao`. + * @return The corresponding persistent table access owner. * @author Dmitriy Moroz */ abstract fun benchmarkResultDao(): BenchmarkResultDao @@ -172,38 +179,44 @@ internal abstract class PersistentDatabase : RoomDatabase() { abstract fun networkUsageDao(): NetworkUsageDao /** - * Provides the `companion object` singleton used by the SDAI storage layer. + * Stable database filename and current migration target. * * @author Dmitriy Moroz */ + /** + * Returns durable restore intent and category-commit records. + * @author Dmitriy Moroz + */ + abstract fun restoreSessionDao(): RestoreSessionDao + companion object { /** - * Exposes the `DB_NAME` value used by the SDAI storage layer. + * Installed database filename; preserve it across schema upgrades. * * @author Dmitriy Moroz */ const val DB_NAME = "ai_sd_v1_storage_db" /** - * Exposes the `DB_VERSION` value used by the SDAI storage layer. + * Schema target including durable restore session and section ledgers. * * @author Dmitriy Moroz */ - const val DB_VERSION = 13 + const val DB_VERSION = 15 } } /** - * Provides the `PersistentDatabaseConstructor` singleton used by the SDAI storage layer. + * Constructs native Room implementations for each supported target. * * @author Dmitriy Moroz */ @Suppress("KotlinNoActualForExpect") internal expect object PersistentDatabaseConstructor : RoomDatabaseConstructor { /** - * Executes the `initialize` step in the SDAI storage layer. + * Creates the platform Room database implementation generated from this schema. * - * @return Result produced by `initialize`. + * @return Constructed persistent database owner. * @author Dmitriy Moroz */ override fun initialize(): PersistentDatabase diff --git a/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/db/persistent/dao/GenerationResultDao.kt b/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/db/persistent/dao/GenerationResultDao.kt index d031bd0aa..f239c21fc 100644 --- a/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/db/persistent/dao/GenerationResultDao.kt +++ b/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/db/persistent/dao/GenerationResultDao.kt @@ -11,39 +11,76 @@ import com.shifthackz.aisdv1.storage.db.persistent.entity.GenerationResultPrevie import kotlinx.coroutines.flow.Flow /** - * Defines the `GenerationResultDao` contract for the SDAI storage layer. + * Reads paged gallery metadata and persists complete image rows; backup imports must use fresh IDs. * * @author Dmitriy Moroz */ @Dao interface GenerationResultDao { + /** + * Advances through a stable backup snapshot by primary key without repeated OFFSET scans. + * @param afterId Exclusive ID cursor from the previous page, or zero for the first page. + * @param limit Maximum number of full image rows held at once. + * @author Dmitriy Moroz + */ + @Query("SELECT * FROM generation_results WHERE id > :afterId ORDER BY id LIMIT :limit") + suspend fun queryBackupPage(afterId: Long, limit: Int): List + + + /** + * Pages every saved image identity, including hidden history, without materializing image payloads. + * @param afterId Exclusive primary-key cursor, or zero for the first page. + * @param limit Maximum IDs read for duplicate checking at once. + * @author Dmitriy Moroz + */ + @Query("SELECT id FROM generation_results WHERE id > :afterId ORDER BY id LIMIT :limit") + suspend fun queryImageIdsAfter(afterId: Long, limit: Int): List + + /** + * Admits one output-only image string before materialization for a single-pass duplicate check. + * @param id Saved gallery or hidden-history identity. + * @param maxBytes Maximum stored UTF8 bytes allowed in the admitted text. + * @return Base64 text, or null for an oversized representation or missing row. + * @author Dmitriy Moroz + */ + @Query("SELECT image_base_64 FROM generation_results WHERE id = :id AND length(CAST(image_base_64 AS BLOB)) <= :maxBytes") + suspend fun queryImageTextForFingerprint(id: Long, maxBytes: Long): String? + + /** + * Reads a bounded Kotlin chunk from an oversized legacy representation. + * Used only when the single-read admission rejects the text; SQLite may materialize its value natively. + * @param id Saved gallery or hidden-history identity. + * @param offset One-based byte position in the stored UTF8 Base64 representation. + * @param maxBytes Maximum UTF8 bytes materialized in the result; BLOB slicing avoids repeated text-prefix scans. + * @return Image text bytes, an empty array at EOF, or null if the row no longer exists. + * @author Dmitriy Moroz + */ + @Query("SELECT substr(CAST(image_base_64 AS BLOB), :offset, :maxBytes) FROM generation_results WHERE id = :id") + suspend fun queryImageChunk(id: Long, offset: Long, maxBytes: Int): ByteArray? /** - * Executes the `query` step in the SDAI storage layer. + * Reads all gallery rows, including hidden generation history. * - * @return Result produced by `query`. * @author Dmitriy Moroz */ @Query("SELECT * FROM ${GenerationResultContract.TABLE} ORDER BY ${GenerationResultContract.CREATED_AT} DESC, ${GenerationResultContract.ID} DESC") suspend fun query(): List /** - * Executes the `queryPage` step in the SDAI storage layer. + * Reads one full-image page ordered by creation time and ID. * - * @param limit limit value consumed by the API. - * @param offset offset value consumed by the API. - * @return Result produced by `queryPage`. + * @param limit Maximum rows held in one page. + * @param offset Number of prior ordered rows to skip. * @author Dmitriy Moroz */ @Query("SELECT * FROM ${GenerationResultContract.TABLE} ORDER BY ${GenerationResultContract.CREATED_AT} DESC, ${GenerationResultContract.ID} DESC LIMIT :limit OFFSET :offset ") suspend fun queryPage(limit: Int, offset: Int): List /** - * Executes the `queryPagePreview` step in the SDAI storage layer. + * Reads one preview-only page without full image payloads. * - * @param limit limit value consumed by the API. - * @param offset offset value consumed by the API. - * @return Result produced by `queryPagePreview`. + * @param limit Maximum rows held in one page. + * @param offset Number of prior ordered rows to skip. * @author Dmitriy Moroz */ @Query( @@ -61,22 +98,20 @@ interface GenerationResultDao { suspend fun queryPagePreview(limit: Int, offset: Int): List /** - * Loads SDAI data through `observePage`. + * Observes a full-image gallery page after Room invalidations. * - * @param limit limit value consumed by the API. - * @param offset offset value consumed by the API. - * @return Result produced by `observePage`. + * @param limit Maximum rows held in one page. + * @param offset Number of prior ordered rows to skip. * @author Dmitriy Moroz */ @Query("SELECT * FROM ${GenerationResultContract.TABLE} ORDER BY ${GenerationResultContract.CREATED_AT} DESC, ${GenerationResultContract.ID} DESC LIMIT :limit OFFSET :offset ") fun observePage(limit: Int, offset: Int): Flow> /** - * Loads SDAI data through `observePagePreview`. + * Observes a preview-only page after Room invalidations. * - * @param limit limit value consumed by the API. - * @param offset offset value consumed by the API. - * @return Result produced by `observePagePreview`. + * @param limit Maximum rows held in one page. + * @param offset Number of prior ordered rows to skip. * @author Dmitriy Moroz */ @Query( @@ -94,93 +129,88 @@ interface GenerationResultDao { fun observePagePreview(limit: Int, offset: Int): Flow> /** - * Loads SDAI data through `observeCount`. + * Observes the current total number of persisted generation rows. * - * @return Result produced by `observeCount`. * @author Dmitriy Moroz */ @Query("SELECT COUNT(*) FROM ${GenerationResultContract.TABLE}") fun observeCount(): Flow /** - * Executes the `queryIds` step in the SDAI storage layer. + * Reads IDs of all saved generation rows. * - * @return Result produced by `queryIds`. * @author Dmitriy Moroz */ @Query("SELECT ${GenerationResultContract.ID} FROM ${GenerationResultContract.TABLE} ORDER BY ${GenerationResultContract.CREATED_AT} DESC, ${GenerationResultContract.ID} DESC") suspend fun queryIds(): List /** - * Executes the `queryById` step in the SDAI storage layer. + * Reads one complete saved image row by local identity. * - * @param id identifier of the target entity. - * @return Result produced by `queryById`. + * @param id Local persisted row identity. * @author Dmitriy Moroz */ @Query("SELECT * FROM ${GenerationResultContract.TABLE} WHERE ${GenerationResultContract.ID} = :id LIMIT 1") suspend fun queryById(id: Long): GenerationResultEntity /** - * Executes the `queryByIdList` step in the SDAI storage layer. + * Reads complete saved rows for explicit local identities. * - * @param idList id list value consumed by the API. - * @return Result produced by `queryByIdList`. + * @param idList Explicit local row identities to read or update. * @author Dmitriy Moroz */ @Query("SELECT * FROM ${GenerationResultContract.TABLE} WHERE ${GenerationResultContract.ID} IN (:idList)") suspend fun queryByIdList(idList: List): List /** - * Performs the SDAI side effect handled by `updateHiddenByIdList`. + * Changes history visibility without replacing image content. * - * @param idList id list value consumed by the API. - * @param hidden hidden value consumed by the API. + * @param idList Explicit local row identities to read or update. + * @param hidden Whether selected rows appear only in generation history. * @author Dmitriy Moroz */ @Query("UPDATE ${GenerationResultContract.TABLE} SET ${GenerationResultContract.HIDDEN} = :hidden WHERE ${GenerationResultContract.ID} IN (:idList)") suspend fun updateHiddenByIdList(idList: List, hidden: Boolean) /** - * Performs the SDAI side effect handled by `updateLikedByIdList`. + * Changes favorite flags without replacing image content. * - * @param idList id list value consumed by the API. - * @param liked liked value consumed by the API. + * @param idList Explicit local row identities to read or update. + * @param liked Whether selected rows are marked as favorites. * @author Dmitriy Moroz */ @Query("UPDATE ${GenerationResultContract.TABLE} SET ${GenerationResultContract.LIKED} = :liked WHERE ${GenerationResultContract.ID} IN (:idList)") suspend fun updateLikedByIdList(idList: List, liked: Boolean) /** - * Performs the SDAI side effect handled by `insert`. + * Inserts a complete gallery row; nonzero conflicting IDs replace existing rows. * - * @param item item value consumed by the API. - * @return Result produced by `insert`. + * @param item Full image row; use ID zero for additive backup import. * @author Dmitriy Moroz */ @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(item: GenerationResultEntity): Long /** - * Performs the SDAI side effect handled by `deleteById`. + * Removes one saved row by local identity. * - * @param id identifier of the target entity. + * @param id Local persisted row identity. * @author Dmitriy Moroz */ @Query("DELETE FROM ${GenerationResultContract.TABLE} WHERE ${GenerationResultContract.ID} = :id") suspend fun deleteById(id: Long) /** - * Performs the SDAI side effect handled by `deleteByIdList`. + * Removes only the explicitly selected saved rows. * - * @param idList id list value consumed by the API. + * @param idList Explicit local row identities to read or update. * @author Dmitriy Moroz */ @Query("DELETE FROM ${GenerationResultContract.TABLE} WHERE ${GenerationResultContract.ID} IN (:idList)") suspend fun deleteByIdList(idList: List) /** - * Performs the SDAI side effect handled by `deleteAll`. + * Removes every saved gallery and hidden history row. * * @author Dmitriy Moroz */ diff --git a/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/db/persistent/dao/RestoreSessionDao.kt b/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/db/persistent/dao/RestoreSessionDao.kt new file mode 100644 index 000000000..be0797291 --- /dev/null +++ b/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/db/persistent/dao/RestoreSessionDao.kt @@ -0,0 +1,78 @@ +package com.shifthackz.aisdv1.storage.db.persistent.dao + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query +import com.shifthackz.aisdv1.storage.db.persistent.entity.RestoreSessionEntity +import com.shifthackz.aisdv1.storage.db.persistent.entity.RestoreSectionEntity + +/** + * Persists restore intent and committed categories without serializing application secrets. + * @author Dmitriy Moroz + */ +@Dao +interface RestoreSessionDao { + /** + * Returns unfinished restore intents before normal application startup publication. + * @author Dmitriy Moroz + */ + @Query("SELECT * FROM restore_sessions WHERE isComplete = 0 OR requiresConfiguration = 1") + suspend fun pending(): List + + /** + * Loads exact operation intent, refusing to silently reuse IDs for different imports. + * @param id Restore session ID. + * @author Dmitriy Moroz + */ + @Query("SELECT * FROM restore_sessions WHERE id = :id") + suspend fun get(id: String): RestoreSessionEntity? + + /** + * Records one new restore intent. Reused session IDs are rejected. + * @param session Nonsecret archive and selection binding. + * @author Dmitriy Moroz + */ + @Insert(onConflict = OnConflictStrategy.ABORT) + suspend fun insert(session: RestoreSessionEntity) + + /** + * Reads categories already applied by this operation. + * @param sessionId Restore session ID. + * @author Dmitriy Moroz + */ + @Query("SELECT category FROM restore_sections WHERE sessionId = :sessionId") + suspend fun completed(sessionId: String): List + + /** + * Loads committed counts for accurate reports after process recovery. + * @param sessionId Restore session ID. + * @author Dmitriy Moroz + */ + @Query("SELECT * FROM restore_sections WHERE sessionId = :sessionId") + suspend fun results(sessionId: String): List + + /** + * Marks a category applied in the same transaction as its additive data. + * @param section Committed category and owning operation. + * @author Dmitriy Moroz + */ + @Insert(onConflict = OnConflictStrategy.ABORT) + suspend fun mark(section: RestoreSectionEntity) + + /** + * Completes an operation after all selected sections have committed. + * @param id Restore session ID. + * @author Dmitriy Moroz + */ + @Query("UPDATE restore_sessions SET isComplete = 1 WHERE id = :id") + suspend fun finish(id: String) + + /** + * Acknowledges configuration only after its startup stage was checked durably. + * @param id Restore session whose first-launch handoff has been persisted. + * @author Dmitriy Moroz + */ + @Query("UPDATE restore_sessions SET requiresConfiguration = 0 WHERE id = :id") + suspend fun acknowledgeConfiguration(id: String) +} diff --git a/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/db/persistent/entity/RestoreSectionEntity.kt b/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/db/persistent/entity/RestoreSectionEntity.kt new file mode 100644 index 000000000..f767b4679 --- /dev/null +++ b/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/db/persistent/entity/RestoreSectionEntity.kt @@ -0,0 +1,22 @@ +package com.shifthackz.aisdv1.storage.db.persistent.entity + +import androidx.room.ColumnInfo +import androidx.room.Entity + +/** + * Committed-section ledger. Gallery/statistics write this row in their data transaction. + * @param sessionId Owning restore session. + * @param category Stable completed section ID. + * @param importedCount Number of destination records durably added or applied. + * @param skippedCount Number of duplicate or unsupported entries omitted from this committed category. + * @param retainedCredentialProviders Comma-separated stable provider IDs whose shared credentials were preserved. + * @author Dmitriy Moroz + */ +@Entity(tableName = "restore_sections", primaryKeys = ["sessionId", "category"]) +data class RestoreSectionEntity( + val sessionId: String, + val category: String, + val importedCount: Long = 0, + val skippedCount: Long = 0, + @ColumnInfo(defaultValue = "''") val retainedCredentialProviders: String = "" +) diff --git a/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/db/persistent/entity/RestoreSessionEntity.kt b/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/db/persistent/entity/RestoreSessionEntity.kt new file mode 100644 index 000000000..55928dcc0 --- /dev/null +++ b/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/db/persistent/entity/RestoreSessionEntity.kt @@ -0,0 +1,23 @@ +package com.shifthackz.aisdv1.storage.db.persistent.entity + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey + +/** + * Durable restore identity containing only private archive and selection references, never secret values. + * @param id Unique restore session, separate from archive identity. + * @param archiveHandle App-owned staged archive basename. + * @param selection Selected category/provider IDs encoded as JSON. + * @param isComplete Whether every selected category has a terminal committed result. + * @param requiresConfiguration Whether the checked configuration handoff still needs acknowledgement. + * @author Dmitriy Moroz + */ +@Entity(tableName = "restore_sessions") +data class RestoreSessionEntity( + @PrimaryKey val id: String, + val archiveHandle: String, + val selection: String, + val isComplete: Boolean = false, + @ColumnInfo(defaultValue = "0") val requiresConfiguration: Boolean = false, +) diff --git a/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/di/PersistentDatabaseModule.kt b/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/di/PersistentDatabaseModule.kt index 02ec17297..dc9edaee0 100644 --- a/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/di/PersistentDatabaseModule.kt +++ b/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/di/PersistentDatabaseModule.kt @@ -5,6 +5,8 @@ import androidx.sqlite.driver.bundled.BundledSQLiteDriver import com.shifthackz.aisdv1.storage.db.persistent.PersistentDatabase import kotlinx.coroutines.Dispatchers import org.koin.core.module.Module +import com.shifthackz.aisdv1.storage.gateway.BackupStorage +import com.shifthackz.aisdv1.storage.gateway.RoomBackupStorage import org.koin.dsl.module /** @@ -22,6 +24,7 @@ expect val persistentDatabasePlatformModule: Module * @author Dmitriy Moroz */ val persistentDatabaseModule = module { + single { RoomBackupStorage(get()) } includes(persistentDatabasePlatformModule) single { getPersistentDatabase(builder = get()) diff --git a/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/gateway/BackupStorage.kt b/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/gateway/BackupStorage.kt new file mode 100644 index 000000000..4f6f8ec78 --- /dev/null +++ b/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/gateway/BackupStorage.kt @@ -0,0 +1,43 @@ +package com.shifthackz.aisdv1.storage.gateway + +import com.shifthackz.aisdv1.storage.db.persistent.dao.GenerationResultDao +import com.shifthackz.aisdv1.storage.db.persistent.dao.NetworkUsageDao +import com.shifthackz.aisdv1.storage.db.persistent.dao.RestoreSessionDao + +/** + * Storage transaction boundary used by backup implementation without exposing the Room database owner. + * @author Dmitriy Moroz + */ +interface BackupStorage { + /** + * Reads a consistent gallery/statistics snapshot through the shared reader connection. + * @param block Bounded paged reads performed in one transaction. + * @author Dmitriy Moroz + */ + suspend fun readSnapshot(block: suspend () -> T): T + + /** + * Commits additive user data and its category ledger together. + * @param block Data writes and section marker belonging to one category. + * @author Dmitriy Moroz + */ + suspend fun writeTransaction(block: suspend () -> T): T + + /** + * Returns paged gallery persistence without generation-save export side effects. + * @author Dmitriy Moroz + */ + fun generationResultDao(): GenerationResultDao + + /** + * Returns atomic durable network byte buckets. + * @author Dmitriy Moroz + */ + fun networkUsageDao(): NetworkUsageDao + + /** + * Returns nonsecret restore session and committed-section persistence. + * @author Dmitriy Moroz + */ + fun restoreSessionDao(): RestoreSessionDao +} diff --git a/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/gateway/RoomBackupStorage.kt b/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/gateway/RoomBackupStorage.kt new file mode 100644 index 000000000..41d43ee16 --- /dev/null +++ b/storage/src/commonMain/kotlin/com/shifthackz/aisdv1/storage/gateway/RoomBackupStorage.kt @@ -0,0 +1,24 @@ +package com.shifthackz.aisdv1.storage.gateway + +import androidx.room.useReaderConnection +import androidx.room.useWriterConnection +import androidx.room.deferredTransaction +import androidx.room.immediateTransaction +import com.shifthackz.aisdv1.storage.db.persistent.PersistentDatabase + +/** + * Keeps Room connection ownership inside storage while backup uses the common transaction contract. + * @param database Shared persistent Room owner; never exposed to consuming modules. + * @author Dmitriy Moroz + */ +internal class RoomBackupStorage(private val database: PersistentDatabase) : BackupStorage { + override suspend fun readSnapshot(block: suspend () -> T): T = + database.useReaderConnection { it.deferredTransaction { block() } } + + override suspend fun writeTransaction(block: suspend () -> T): T = + database.useWriterConnection { it.immediateTransaction { block() } } + + override fun generationResultDao() = database.generationResultDao() + override fun networkUsageDao() = database.networkUsageDao() + override fun restoreSessionDao() = database.restoreSessionDao() +}