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