# 04 — profiles-and-lifetimes: file workbook

[Implementation chapter](../chapters/04-profiles-and-lifetimes.md) · [Coverage index](README.md)

Each text entry includes the complete pinned file to write at the displayed path, plus an exact-byte download. Read the chapter for implementation order and behavior, then connect callers and reproduce the tests. Platform variants preserve their platform capabilities. Binary assets are retained with applicable licenses or independently recreated, not transcribed as code.

**Pinned baseline for comparison.** Use the reviewed listings in the [implementation chapters](../README.md#reading-order) and the [reviewed source archive](reviewed-source.zip) when reconstructing the app. See the [architecture review](architecture-review.md) for changes.

## `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.android.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.android.kt) · implementation · 13 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
5: object AndroidBootstrapState {
9: actual fun platformBootstrapInput(): PlatformBootstrapInput = PlatformBootstrapInput(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.android.kt) · SHA-256 `d704abb887a20d315c4123c50f41bfb2e95d58e2f1e401538432630d159fa87f`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app

import eu.friedcutlet.yokan.AndroidAppContext

object AndroidBootstrapState {
    var initialDeepLink: String? = null
}

actual fun platformBootstrapInput(): PlatformBootstrapInput = PlatformBootstrapInput(
    platformName = "Android",
    initialDeepLink = AndroidBootstrapState.initialDeepLink,
    appDataPath = AndroidAppContext.appContext?.filesDir?.absolutePath,
)
```
[complete-source-end]: #

## `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.android.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.android.kt) · implementation · 9 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
6: actual fun createPlatformProfileRegistry(): ProfileRegistry {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.android.kt) · SHA-256 `45ac90d8f886b77e0f435412c0fe8b153761af1802f22697db4353ae09adf7b5`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.AndroidAppContext
import java.io.File

actual fun createPlatformProfileRegistry(): ProfileRegistry {
    val context = checkNotNull(AndroidAppContext.appContext) { "Android context unavailable" }
    return ProfileRegistry(FileProfileRegistryPersistence(File(context.filesDir, "profiles/registry.json")))
}
```
[complete-source-end]: #

## `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.android.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.android.kt) · implementation · 20 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
9: internal actual suspend fun deletePlatformProfileStorage(id: ProfileId, exportedBackups: List<String>) = withContext(Dispatchers.IO) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.android.kt) · SHA-256 `7190fb50cdd681f83a125c097de519590a973d169c3b265db0f94796784a51b3`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.AndroidAppContext
import java.io.File
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.domain.ProfileId

internal actual suspend fun deletePlatformProfileStorage(id: ProfileId, exportedBackups: List<String>) = withContext(Dispatchers.IO) {
    val context = checkNotNull(AndroidAppContext.appContext) { "Android context unavailable" }
    deleteOwnedProfileDirectory(context.filesDir, id, exportedBackups)
    deleteOwnedProfileDirectory(context.cacheDir, id, exportedBackups)
    deleteOwnedProfileDirectory(checkNotNull(context.getDatabasePath("yokan-room.db").parentFile), id, exportedBackups)
    // Mihon bridge source preferences live in prefixed shared_prefs files (see mihonBridgePreferencesPrefix).
    val prefix = eu.friedcutlet.yokan.services.extensions.mihon.mihonBridgePreferencesPrefix(id)
    File(context.dataDir, "shared_prefs").listFiles().orEmpty()
        .filter { it.name.startsWith(prefix) && it.name.endsWith(".xml") }
        .forEach { context.deleteSharedPreferences(it.name.removeSuffix(".xml")) }
    eu.friedcutlet.yokan.services.webview.deleteProfileWebViewStorage(id)
}
```
[complete-source-end]: #

## `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.android.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.android.kt) · implementation · 11 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
8: internal actual suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease =
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.android.kt) · SHA-256 `20b8af55797a08c6345d3b0a503cd20e4ee363665c35b45a595cde85b619d2ce`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.AndroidAppContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.domain.ProfileId

internal actual suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease =
    if (id == ProfileId.Default) ProfileStorageLease {} else withContext(Dispatchers.IO) {
        acquireFileProfileLease(checkNotNull(AndroidAppContext.appContext).filesDir, id)
    }
```
[complete-source-end]: #

## `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.android.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.android.kt) · implementation · 24 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
13: internal actual suspend fun cancelProfileBackgroundWork(id: ProfileId) = withContext(Dispatchers.IO) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.android.kt) · SHA-256 `899f646fce1b18a6892fa76a1b0e29495df044762c421469f2c8b2bce654f4fb`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import android.app.NotificationManager
import android.content.Context
import androidx.work.WorkManager
import androidx.work.await
import eu.friedcutlet.yokan.AndroidAppContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkNamespace

internal actual suspend fun cancelProfileBackgroundWork(id: ProfileId) = withContext(Dispatchers.IO) {
    require(id != ProfileId.Default)
    val context = checkNotNull(AndroidAppContext.appContext)
    val work = WorkManager.getInstance(context)
    val names = ProfileWorkNamespace(id)
    listOf("yokan.metadata_refresh", "yokan.library_update", "yokan.auto_sync", "yokan.auto_backup", "yokan.download_resume").forEach {
        work.cancelUniqueWork(names.uniqueName(it)).await()
    }
    val notifications = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    val prefix = "yokan.profile.${id.value}."
    notifications.activeNotifications.filter { it.tag?.startsWith(prefix) == true }.forEach { notifications.cancel(it.tag, it.id) }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.kt) · implementation · 130 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
12: enum class StartupStatus {
18: data class StartupCheck(
24: data class PlatformBootstrapInput(
30: data class AppBootstrapReport(
40: internal fun runStartupChecks(
64: expect fun platformBootstrapInput(): PlatformBootstrapInput
66: expect fun installPlatformCrashLogger(onCrash: (Throwable) -> Unit)
68: private fun checkPersistence(database: YokanDatabase): StartupCheck {
76: private fun checkDownloadWorkers(services: YokanServices): StartupCheck = runCatching {
83: private fun checkExtensionRuntime(services: YokanServices): StartupCheck {
113: private fun checkDeepLinks(input: PlatformBootstrapInput): StartupCheck =
116: private fun checkLogging(): StartupCheck = startupOk("Logging", "in-memory startup and crash log buffer ready")
118: private fun checkDiscordRpc(input: PlatformBootstrapInput, settings: DbSettings, service: DiscordRpcService): StartupCheck = when {
126: private fun startupOk(name: String, notes: String) = StartupCheck(name, StartupStatus.Ok, notes)
128: private fun startupWarning(name: String, notes: String) = StartupCheck(name, StartupStatus.Warning, notes)
130: private fun startupError(name: String, notes: String) = StartupCheck(name, StartupStatus.Error, notes)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.kt) · SHA-256 `c1ca74d29bf7358f5421003bf79d3fadde91956d53615680b1434f8163e68851`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app

import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.discord.DiscordRpcService
import eu.friedcutlet.yokan.services.extensions.mihon.defaultMihonProxyUrl
import eu.friedcutlet.yokan.services.http.isLoopbackProxy
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.runBlockingCompat

enum class StartupStatus {
    Ok,
    Warning,
    Error,
}

data class StartupCheck(
    val name: String,
    val status: StartupStatus,
    val notes: String,
)

data class PlatformBootstrapInput(
    val platformName: String,
    val initialDeepLink: String? = null,
    val appDataPath: String? = null,
)

data class AppBootstrapReport(
    val platform: PlatformBootstrapInput,
    val checks: List<StartupCheck>,
) {
    val initialDeepLink: String? get() = platform.initialDeepLink
    val hasErrors: Boolean get() = checks.any { it.status == StartupStatus.Error }
    val summary: String get() = "${checks.count { it.status == StartupStatus.Ok }} ok, ${checks.count { it.status == StartupStatus.Warning }} warnings, ${checks.count { it.status == StartupStatus.Error }} errors"
}

/** Runs the startup checks listed in Settings → About and logs each one. */
internal fun runStartupChecks(
    input: PlatformBootstrapInput,
    services: YokanServices,
    discordRpc: DiscordRpcService,
): AppBootstrapReport {
    val checks = buildList {
        add(startupOk("Platform", "${input.platformName}${input.appDataPath?.let { " data=$it" }.orEmpty()}"))
        add(checkPersistence(services.database))
        add(checkDownloadWorkers(services))
        add(checkExtensionRuntime(services))
        add(checkDeepLinks(input))
        add(checkLogging())
        add(checkDiscordRpc(input, services.database.settings(), discordRpc))
    }
    checks.forEach { check ->
        when (check.status) {
            StartupStatus.Ok -> AppLogger.info("${check.name}: ${check.notes}")
            StartupStatus.Warning -> AppLogger.warn("${check.name}: ${check.notes}")
            StartupStatus.Error -> AppLogger.error("${check.name}: ${check.notes}")
        }
    }
    return AppBootstrapReport(input, checks)
}

expect fun platformBootstrapInput(): PlatformBootstrapInput

expect fun installPlatformCrashLogger(onCrash: (Throwable) -> Unit)

private fun checkPersistence(database: YokanDatabase): StartupCheck {
    val snapshot = database.snapshot()
    return startupOk(
        "Persistence",
        "loaded ${snapshot.mangas.size} titles, ${snapshot.chapters.size} chapters, ${snapshot.sources.size} sources",
    )
}

private fun checkDownloadWorkers(services: YokanServices): StartupCheck = runCatching {
    runBlockingCompat { services.downloader.initialize(services.database.settings().concurrentDownloads) }
    startupOk("Download workers", "initialized pool size ${services.database.settings().concurrentDownloads}; recovered ${services.downloader.activeDownloads().size} active tasks")
}.getOrElse { error ->
    startupError("Download workers", error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() })
}

private fun checkExtensionRuntime(services: YokanServices): StartupCheck {
    val sources = services.database.sources()
    val jsCount = sources.count { it.sourceCodeLanguage == DbSourceCodeLanguage.JavaScript }
    val mihonCount = sources.count { it.sourceCodeLanguage == DbSourceCodeLanguage.Mihon }
    val lnReaderCount = sources.count { it.sourceCodeLanguage == DbSourceCodeLanguage.LnReader }
    val proxy = services.database.settings().androidProxyServer ?: defaultMihonProxyUrl
    val usesLocalProxy = isLoopbackProxy(proxy)
    var serverNote = if (mihonCount > 0 && !usesLocalProxy) "; remote extension server configured" else ""
    var serverWarning: String? = null
    if (mihonCount > 0 && usesLocalProxy) {
        if (!services.extensionServer.isConfigured()) {
            serverWarning = "local extension server is not installed or bundled"
        } else {
            serverNote = "; local server startup scheduled"
        }
    }
    val runtimeFailures = sources.mapNotNull { source ->
        runCatching { services.extensionRuntimeFactory.create(source).dispose() }
            .exceptionOrNull()
            ?.let { error -> "${source.name}: ${error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() }}" }
    }
    val notes = "QuickJS=$jsCount, Mihon=$mihonCount via $proxy, LNReader=$lnReaderCount"
    val fullNotes = notes + serverNote
    return when {
        runtimeFailures.isNotEmpty() -> startupError("Extension runtime", runtimeFailures.joinToString())
        serverWarning != null -> startupWarning("Extension runtime", "$fullNotes; $serverWarning")
        else -> startupOk("Extension runtime", fullNotes)
    }
}

private fun checkDeepLinks(input: PlatformBootstrapInput): StartupCheck =
    startupOk("Deep links", input.initialDeepLink?.let { "captured initial link $it" } ?: "initialized; no initial link")

private fun checkLogging(): StartupCheck = startupOk("Logging", "in-memory startup and crash log buffer ready")

private fun checkDiscordRpc(input: PlatformBootstrapInput, settings: DbSettings, service: DiscordRpcService): StartupCheck = when {
    !settings.enableDiscordRpc -> startupOk("Discord RPC", "disabled in settings")
    else -> {
        val status = service.initialize(settings)
        if (status.connected) startupOk("Discord RPC", status.message) else startupWarning("Discord RPC", status.message)
    }
}

private fun startupOk(name: String, notes: String) = StartupCheck(name, StartupStatus.Ok, notes)

private fun startupWarning(name: String, notes: String) = StartupCheck(name, StartupStatus.Warning, notes)

private fun startupError(name: String, notes: String) = StartupCheck(name, StartupStatus.Error, notes)
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/AppStartup.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/AppStartup.kt) · implementation · 59 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
15: internal suspend fun runAppStartup(imageContext: PlatformContext): Unit = coroutineScope {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/AppStartup.kt) · SHA-256 `da0d6c484dd7be51436bf62d1433c1bdb7d17d200ad5edb4fef423dc4233f27a`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app

import coil3.PlatformContext
import coil3.SingletonImageLoader
import eu.friedcutlet.yokan.ui.image.clearCaches
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.notifications.InAppNotifications
import eu.friedcutlet.yokan.services.updates.checkForAppUpdate
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/** One-shot startup maintenance, run once from the app root after bootstrap. Each task runs concurrently. */
internal suspend fun runAppStartup(imageContext: PlatformContext): Unit = coroutineScope {
    val owner = YokanRuntime.activeSession
    val settings = owner.settings.db.value
    // "Clear chapter/episode cache on app launch": the same chapter cache as the Data and storage
    // button — Coil's disk+memory image caches (like Mangayomi's DefaultCacheManager.emptyCache())
    // and the saved chapter page lists.
    launch(Dispatchers.Default) {
        if (!owner.services.database.settings().clearChapterCacheOnAppLaunch) return@launch
        runCatching {
            SingletonImageLoader.get(imageContext).clearCaches()
            owner.repository.clearPageCache()
        }
    }
    // Auto-prune browsed (non-favorite) titles the user never interacted with
    // (no history, downloads, or tracking), so cached browse results don't
    // pile up until a manual "Clean database".
    launch(Dispatchers.Default) {
        runCatching { owner.repository.pruneBrowsedTitles() }
    }
    // Startup extension repo check (Mangayomi's main_screen behavior): when
    // "Check for extension updates" is on, fetch every item-type repository
    // shortly after launch; the refresh auto-installs updates when
    // autoExtensionsUpdates is enabled.
    if (settings.checkForExtensionUpdates) {
        launch(Dispatchers.Default) {
            delay(2_000)
            owner.sourceInstall.refreshAllRepositories()
        }
    }
    // Startup app-update check (Mangayomi main_screen): compare the latest
    // GitHub release with the installed version and surface a toast.
    if (settings.checkForAppUpdates) {
        launch {
            delay(3_000)
            catchingNonCancellation {
                checkForAppUpdate(owner.services.http)?.let { release ->
                    InAppNotifications.post(
                        "Update available: ${release.tag}",
                        "Open More → About to download it.",
                    )
                }
            }
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/ServiceRegistry.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/ServiceRegistry.kt) · implementation · 391 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
134: class YokanServices(
176: suspend fun closeAndJoin() = retirementLock.withLock {
192: fun defaultServices(
345: private fun animeExtractors(http: HttpService, cookieJar: CookieJar): List<AnimeExtractorService> = listOf(
368: private fun trackers(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/ServiceRegistry.kt) · SHA-256 `088eabf0499405efce55d1416b315bf0ce962baf4fa3953b4aa3d49f275b6195`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.backup.BackupService
import eu.friedcutlet.yokan.services.discovery.DiscoveryService
import eu.friedcutlet.yokan.services.discovery.HttpDiscoveryService
import eu.friedcutlet.yokan.services.download.DownloadAutomation
import eu.friedcutlet.yokan.services.download.DownloadService
import eu.friedcutlet.yokan.services.download.ExternalDownloads
import eu.friedcutlet.yokan.services.download.ImageDataSaver
import eu.friedcutlet.yokan.services.download.PersistentDownloadService
import eu.friedcutlet.yokan.services.download.keepDownloadsAlive
import eu.friedcutlet.yokan.services.extensions.DynamicExtensionRuntimeFactory
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory
import eu.friedcutlet.yokan.services.extensions.HttpSourceCatalogService
import eu.friedcutlet.yokan.services.extensions.SourceCatalogService
import eu.friedcutlet.yokan.services.extensions.mergeSourcePageHeaders
import eu.friedcutlet.yokan.services.extensions.mihon.DefaultExtensionServerRuntimeService
import eu.friedcutlet.yokan.services.extensions.mihon.ExtensionServerRuntimeService
import eu.friedcutlet.yokan.services.extensions.mihon.createPlatformExtensionServerAdapter
import eu.friedcutlet.yokan.services.extensions.mihon.resolveMihonProxy
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeCatalogInstallationService
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeInstallationClock
import eu.friedcutlet.yokan.services.extensions.recipe.createPlatformRecipeServices
import eu.friedcutlet.yokan.services.extensions.withSourceRuntime
import eu.friedcutlet.yokan.services.files.LocalArchiveService
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.http.EnhancedHttpService
import eu.friedcutlet.yokan.services.http.HostResolver
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.KtorHttpService
import eu.friedcutlet.yokan.services.http.ProfileHttpService
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import eu.friedcutlet.yokan.services.http.createPlatformHttpClientEngine
import eu.friedcutlet.yokan.services.http.createPlatformHttpService
import eu.friedcutlet.yokan.services.library.DefaultLibraryUpdaterService
import eu.friedcutlet.yokan.services.library.DefaultLocalEntryManagementService
import eu.friedcutlet.yokan.services.library.DefaultLocalLibraryService
import eu.friedcutlet.yokan.services.library.LibraryAiringService
import eu.friedcutlet.yokan.services.library.LibraryUpdaterService
import eu.friedcutlet.yokan.services.library.LocalEntryManagementService
import eu.friedcutlet.yokan.services.library.LocalLibraryService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.SubtitleService
import eu.friedcutlet.yokan.services.media.extractors.DoodExtractor
import eu.friedcutlet.yokan.services.media.extractors.FilemoonExtractor
import eu.friedcutlet.yokan.services.media.extractors.GogoCdnExtractor
import eu.friedcutlet.yokan.services.media.extractors.KwikExtractor
import eu.friedcutlet.yokan.services.media.extractors.Mp4UploadExtractor
import eu.friedcutlet.yokan.services.media.extractors.MyStreamExtractor
import eu.friedcutlet.yokan.services.media.extractors.MytvExtractor
import eu.friedcutlet.yokan.services.media.extractors.OkruExtractor
import eu.friedcutlet.yokan.services.media.extractors.QuarkUcExtractor
import eu.friedcutlet.yokan.services.media.extractors.SendvidExtractor
import eu.friedcutlet.yokan.services.media.extractors.SibnetExtractor
import eu.friedcutlet.yokan.services.media.extractors.StreamTapeExtractor
import eu.friedcutlet.yokan.services.media.extractors.StreamWishExtractor
import eu.friedcutlet.yokan.services.media.extractors.StreamlareExtractor
import eu.friedcutlet.yokan.services.media.extractors.VidBomExtractor
import eu.friedcutlet.yokan.services.media.extractors.VoeExtractor
import eu.friedcutlet.yokan.services.media.extractors.YourUploadExtractor
import eu.friedcutlet.yokan.services.metadata.HttpMetadataService
import eu.friedcutlet.yokan.services.metadata.MetadataService
import eu.friedcutlet.yokan.services.metadata.RecommendationService
import eu.friedcutlet.yokan.services.metadata.WatchOrderService
import eu.friedcutlet.yokan.services.notifications.NotificationService
import eu.friedcutlet.yokan.services.sync.CloudBackupSyncService
import eu.friedcutlet.yokan.services.sync.DefaultCloudBackupSyncService
import eu.friedcutlet.yokan.services.sync.GoogleDriveCloudStorageProvider
import eu.friedcutlet.yokan.services.sync.GoogleDriveSyncService
import eu.friedcutlet.yokan.services.sync.HubSyncService
import eu.friedcutlet.yokan.services.sync.HybridSyncService
import eu.friedcutlet.yokan.services.sync.MangayomiSyncService
import eu.friedcutlet.yokan.services.sync.ProfileSyncServices
import eu.friedcutlet.yokan.services.sync.SyncAccountLeases
import eu.friedcutlet.yokan.services.sync.SyncOperationMonitor
import eu.friedcutlet.yokan.services.sync.SyncService
import eu.friedcutlet.yokan.services.sync.SyncYomiSyncService
import eu.friedcutlet.yokan.services.sync.adoptConfiguredSyncAccount
import eu.friedcutlet.yokan.services.system.createNetworkMonitor
import eu.friedcutlet.yokan.services.torrent.TorrentStreams
import eu.friedcutlet.yokan.services.torrent.createPlatformTorrServerHost
import eu.friedcutlet.yokan.services.tracking.AnilistTrackerService
import eu.friedcutlet.yokan.services.tracking.AnilistTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.BangumiTrackerService
import eu.friedcutlet.yokan.services.tracking.BangumiTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.HikkaTrackerService
import eu.friedcutlet.yokan.services.tracking.HikkaTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.JellyfinTrackerService
import eu.friedcutlet.yokan.services.tracking.JellyfinTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.KavitaTrackerService
import eu.friedcutlet.yokan.services.tracking.KavitaTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.KitsuTrackerService
import eu.friedcutlet.yokan.services.tracking.KitsuTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.KomgaTrackerService
import eu.friedcutlet.yokan.services.tracking.KomgaTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.MalTrackerService
import eu.friedcutlet.yokan.services.tracking.MalTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.MangaBakaTrackerService
import eu.friedcutlet.yokan.services.tracking.MangaBakaTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.MangaUpdatesTrackerService
import eu.friedcutlet.yokan.services.tracking.MangaUpdatesTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.MetadataTrackerService
import eu.friedcutlet.yokan.services.tracking.MetadataTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.ShikimoriTrackerService
import eu.friedcutlet.yokan.services.tracking.ShikimoriTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.SimklTrackerService
import eu.friedcutlet.yokan.services.tracking.SimklTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.SuwayomiTrackerService
import eu.friedcutlet.yokan.services.tracking.SuwayomiTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.TmdbTrackerService
import eu.friedcutlet.yokan.services.tracking.TmdbTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.TrackerAccounts
import eu.friedcutlet.yokan.services.tracking.TrackerService
import eu.friedcutlet.yokan.services.tracking.TraktTrackerService
import eu.friedcutlet.yokan.services.tracking.TraktTrackerSyncId
import eu.friedcutlet.yokan.services.translation.LibreTranslateTranslatorService
import eu.friedcutlet.yokan.services.translation.TranslatorService
import eu.friedcutlet.yokan.services.tts.ProfileSpeechService
import eu.friedcutlet.yokan.services.tts.TextToSpeechService
import eu.friedcutlet.yokan.services.tts.createPlatformTextToSpeechService
import eu.friedcutlet.yokan.services.webview.WebViewRequest
import eu.friedcutlet.yokan.services.webview.WebViewService
import eu.friedcutlet.yokan.services.webview.createPlatformWebViewService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

class YokanServices(
    val database: YokanDatabase,
    val extensionRuntimeFactory: ExtensionRuntimeFactory,
    val extensionServer: ExtensionServerRuntimeService,
    val trackers: List<TrackerService>,
    val trackerAccounts: TrackerAccounts,
    val downloader: DownloadService,
    val backup: BackupService,
    val sync: SyncService,
    val cloudSync: CloudBackupSyncService,
    val sourceCatalog: SourceCatalogService,
    val libraryUpdater: LibraryUpdaterService,
    val subtitle: SubtitleService,
    val watchOrder: WatchOrderService,
    val recommendation: RecommendationService,
    val metadata: MetadataService,
    val translator: TranslatorService,
    val webView: WebViewService,
    val http: HttpService,
    textToSpeech: TextToSpeechService,
    val animeExtractors: List<AnimeExtractorService>,
    val localLibrary: LocalLibraryService,
    val localEntryManagement: LocalEntryManagementService,
    val cookieJar: CookieJar,
    val recipeCatalogInstallation: RecipeCatalogInstallationService,
    /** Owns background coroutines (download workers, foreground scheduler, startup jobs). */
    val scope: CoroutineScope,
    val downloadAutomation: DownloadAutomation,
    val imageDataSaver: ImageDataSaver,
    val externalDownloads: ExternalDownloads,
    private val platformHttp: KtorHttpService,
    isOwnerOpen: () -> Boolean,
    val libraryAirings: LibraryAiringService,
    val torrents: TorrentStreams,
) {
    val discovery: DiscoveryService by lazy {
        HttpDiscoveryService(http, database, extensionRuntimeFactory)
    }
    val textToSpeech = ProfileSpeechService(textToSpeech, scope, isOwnerOpen)
    private val retirementLock = Mutex()

    /** Session retirement waits for worker finalizers before releasing captured runtimes. */
    suspend fun closeAndJoin() = retirementLock.withLock {
        scope.coroutineContext[Job]?.cancelAndJoin()
        textToSpeech.closeAndJoin()
        extensionServer.stop()
        torrents.stop()
        extensionRuntimeFactory.clear()
        sync.closeAndJoin()
        platformHttp.closeAndJoin()
    }
}

/**
 * Builds the service graph. [files]/[archives]/[notifications]/[backup] are passed in so the whole
 * session shares one instance of each (the JVM archive service keeps extraction caches).
 * [resolveDownloadPages] resolves a chapter's pages when its download starts.
 */
fun defaultServices(
    database: YokanDatabase,
    files: LocalFileService,
    archives: LocalArchiveService,
    notifications: NotificationService,
    backup: BackupService,
    resolveDownloadPages: suspend (chapterId: Long, forceRefresh: Boolean) -> List<DbPageUrl>,
    scope: CoroutineScope,
    profileId: ProfileId,
    isOwnerOpen: () -> Boolean,
    syncLeases: SyncAccountLeases,
    /** DNS-over-HTTPS lookup for the main client; must not itself resolve through that client. */
    resolveHost: HostResolver?,
): YokanServices {
    requireNotNull(scope.coroutineContext[Job]) { "Profile services require an owner job" }
    val cookieJar = CookieJar(database, profileId) { scope.coroutineContext[Job]?.isActive == true }
    val platformHttp = createPlatformHttpService(profileId, scope, resolveHost)
    val rawHttp = ProfileHttpService(profileId, platformHttp, scope)
    val enhancedHttp = EnhancedHttpService(rawHttp, database, cookieJar)
    val http = ProfileHttpService(profileId, enhancedHttp, scope)
    val imageDataSaver = ImageDataSaver(rawHttp, cookieJar)
    // Genuine cycle, closed once here: the WebView solver retries through the enhanced client
    // (cookie jar + solver-bypass header) and the client hands challenges to the solver.
    val webView = createPlatformWebViewService(http, cookieJar, files, scope).also { webView ->
        enhancedHttp.cloudflareSolver = { url, headers -> webView.resolveCloudflare(WebViewRequest(url = url, title = "", headers = headers)) }
    }
    val animeExtractors = animeExtractors(http, cookieJar)
    val extensionServer: ExtensionServerRuntimeService = DefaultExtensionServerRuntimeService(
        database,
        http,
        createPlatformExtensionServerAdapter(profileId),
    )
    val recipeInstallationClock = RecipeInstallationClock { kotlin.time.Clock.System.now().toEpochMilliseconds() / 1_000 }
    val recipeServices = createPlatformRecipeServices(database, recipeInstallationClock)
    val runtimeFactory = DynamicExtensionRuntimeFactory(
        database = database,
        http = http,
        prepareMihonProxy = { proxy -> extensionServer.resolveMihonProxy(proxy) },
        recipeRuntime = recipeServices.runtimeBindings,
        archives = archives,
        webView = webView,
        animeExtractors = animeExtractors,
    )
    val metadata = HttpMetadataService(http)
    val syncOperationMonitor = SyncOperationMonitor()
    val cloudSync = DefaultCloudBackupSyncService(
        database = database,
        backup = backup,
        providers = listOf(GoogleDriveCloudStorageProvider(http)),
        operationMonitor = syncOperationMonitor,
        leases = syncLeases,
    )
    val serverSync = HubSyncService(
        database,
        http,
        createPlatformHttpClientEngine(profileId),
        scope = scope,
        operationMonitor = syncOperationMonitor,
        leases = syncLeases,
    )
    // Direct owned transport: the enhanced app client persists Set-Cookie into the profile jar,
    // while Mangayomi's id= JWT must remain isolated in the sync preference only.
    val mangayomiSync = MangayomiSyncService(database, rawHttp, syncOperationMonitor, syncLeases)
    // Same isolation for SyncYomi's API key and Google OAuth tokens.
    val syncYomiSync = SyncYomiSyncService(database, backup, rawHttp, syncOperationMonitor, syncLeases)
    val googleDriveSync = GoogleDriveSyncService(database, backup, rawHttp, syncOperationMonitor, syncLeases)
    val profileSync = ProfileSyncServices(
        profileId = profileId,
        delegate = HybridSyncService(serverSync, cloudSync, database, syncOperationMonitor, mangayomiSync, syncYomiSync, googleDriveSync),
        cloudDelegate = cloudSync,
        ownerScope = scope,
    )
    adoptConfiguredSyncAccount(syncLeases, database, scope)
    val localLibrary = DefaultLocalLibraryService(database, files, archives)
    // User-hosted/loopback server: direct transport like the self-hosted trackers below.
    val torrents = TorrentStreams(database, rawHttp, files, createPlatformTorrServerHost(profileId))
    var automationOwner: DownloadAutomation? = null
    val downloadPages: suspend (Long, Boolean) -> List<DbPageUrl> = { chapterId, forceRefresh ->
        val chapter = checkNotNull(database.chapter(chapterId))
        val title = checkNotNull(chapter.mangaId?.let(database::manga))
        if (title.itemType == DbItemType.Anime) {
            runtimeFactory.withSourceRuntime(database, checkNotNull(title.sourceId)) { runtime ->
                runtime.videoList(chapter.url).firstOrNull()?.let { video ->
                    // Animetail downloads torrent videos through TorrServer's stream URL.
                    val resolved = torrents.expand(listOf(video), title.name.orEmpty()).first()
                    mergeSourcePageHeaders(runtime.headers(), listOf(DbPageUrl(url = resolved.url, headers = resolved.headers)))
                }.orEmpty()
            }
        } else resolveDownloadPages(chapterId, forceRefresh)
    }
    val externalDownloads = ExternalDownloads(database, rawHttp, scope, downloadPages)
    val downloader = PersistentDownloadService(
        database = database,
        http = http,
        files = files,
        archives = archives,
        scope = scope,
        resolvePages = downloadPages,
        resolveNovelText = { chapterId ->
            val chapter = checkNotNull(database.chapter(chapterId))
            val title = checkNotNull(chapter.mangaId?.let(database::manga))
            runtimeFactory.withSourceRuntime(database, checkNotNull(title.sourceId)) { runtime ->
                runtime.cleanHtmlContent(runtime.htmlContent(chapter.name.orEmpty(), chapter.url))
            }
        },
        notifications = notifications,
        network = createNetworkMonitor(),
        onCompleted = { chapterId -> automationOwner?.downloadCompleted(chapterId) },
        imageDataSaver = imageDataSaver,
        imageHttp = rawHttp,
    ).also { keepDownloadsAlive(it, database, scope, profileId) }
    val downloadAutomation = DownloadAutomation(database, downloader, scope)
    automationOwner = downloadAutomation
    val trackers = trackers(database, http, rawHttp, metadata)
    return YokanServices(
        externalDownloads = externalDownloads,
        torrents = torrents,
        imageDataSaver = imageDataSaver,
        database = database,
        extensionRuntimeFactory = runtimeFactory,
        extensionServer = extensionServer,
        trackers = trackers,
        trackerAccounts = TrackerAccounts(database, trackers, scope),
        downloader = downloader,
        backup = backup,
        sync = profileSync.sync,
        cloudSync = profileSync.cloud,
        sourceCatalog = HttpSourceCatalogService(http, files),
        libraryUpdater = DefaultLibraryUpdaterService(database, runtimeFactory, downloadAutomation),
        libraryAirings = LibraryAiringService(database, rawHttp, scope),
        downloadAutomation = downloadAutomation,
        subtitle = SubtitleService(http),
        watchOrder = WatchOrderService(http),
        recommendation = RecommendationService(http, database),
        metadata = metadata,
        translator = LibreTranslateTranslatorService(http),
        webView = webView,
        http = http,
        textToSpeech = createPlatformTextToSpeechService(),
        animeExtractors = animeExtractors,
        localLibrary = localLibrary,
        localEntryManagement = DefaultLocalEntryManagementService(database, localLibrary),
        cookieJar = cookieJar,
        scope = scope,
        platformHttp = platformHttp,
        recipeCatalogInstallation = recipeServices.installation,
        isOwnerOpen = isOwnerOpen,
    )
}

// All 16 anime extractors from the Flutter `lib/services/anime_extractors/` directory are ported.
// Sendvid and YourUpload sometimes need source-supplied headers (Referer mostly); those still get
// forwarded through `extract(url, headers)`.
private fun animeExtractors(http: HttpService, cookieJar: CookieJar): List<AnimeExtractorService> = listOf(
    StreamTapeExtractor(http),
    VoeExtractor(http),
    StreamWishExtractor(http),
    FilemoonExtractor(http),
    GogoCdnExtractor(http),
    DoodExtractor(http),
    Mp4UploadExtractor(http),
    MyStreamExtractor(http),
    MytvExtractor(http),
    OkruExtractor(http),
    SendvidExtractor(http),
    SibnetExtractor(http),
    StreamlareExtractor(http),
    VidBomExtractor(http),
    YourUploadExtractor(http),
    QuarkUcExtractor(http, cookieJar),
    // Kwik / Pahewin — AnimePahe's HLS / MP4 wrapper. HLS path is
    // packed-eval; MP4 path is the kwik.cx custom obfuscator + form
    // POST. See KwikExtractor.kt for caveats around Cloudflare.
    KwikExtractor(http),
)

private fun trackers(
    database: YokanDatabase,
    http: HttpService,
    rawHttp: HttpService,
    metadata: MetadataService,
): List<TrackerService> = listOf(
    MalTrackerService(MalTrackerSyncId, database, http),
    AnilistTrackerService(AnilistTrackerSyncId, database, http),
    KitsuTrackerService(KitsuTrackerSyncId, database, http),
    SimklTrackerService(SimklTrackerSyncId, database, http),
    TraktTrackerService(TraktTrackerSyncId, database, http),
    MetadataTrackerService(MetadataTrackerSyncId, database, metadata),
    MangaUpdatesTrackerService(MangaUpdatesTrackerSyncId, database, http),
    ShikimoriTrackerService(ShikimoriTrackerSyncId, database, http),
    BangumiTrackerService(BangumiTrackerSyncId, database, http),
    HikkaTrackerService(HikkaTrackerSyncId, database, http),
    MangaBakaTrackerService(MangaBakaTrackerSyncId, database, http),
    TmdbTrackerService(TmdbTrackerSyncId, database, http),
    // User-hosted servers (often LAN addresses) bypass the DoH/cookie layer, like the sync servers.
    KomgaTrackerService(KomgaTrackerSyncId, database, rawHttp),
    KavitaTrackerService(KavitaTrackerSyncId, database, rawHttp),
    SuwayomiTrackerService(SuwayomiTrackerSyncId, database, rawHttp),
    JellyfinTrackerService(JellyfinTrackerSyncId, database, rawHttp),
)
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/YokanRuntime.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/YokanRuntime.kt) · implementation · 235 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
34: object YokanRuntime {
78: suspend fun runBackgroundTask(
86: suspend fun runBackgroundDownloads(
116: fun bootstrap(
136: fun bootstrapReport(): AppBootstrapReport = report ?: bootstrap()
142: fun reschedulePeriodicTasks() = reschedulePeriodicTasks(activeSession)
144: private fun reschedulePeriodicTasks(owner: eu.friedcutlet.yokan.app.profiles.ProfileSession) {
176: private fun startup(input: PlatformBootstrapInput): AppBootstrapReport {
196: private fun startForeground(owner: eu.friedcutlet.yokan.app.profiles.ProfileSession) {
203: private fun scheduleExtensionServerStart(owner: eu.friedcutlet.yokan.app.profiles.ProfileSession) {
227: private data class PeriodicSchedule(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/YokanRuntime.kt) · SHA-256 `f1421bc6db9a69e9a82dc23ccd95ce1185220dbe28d46191f4e4ee251c927a26`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app

import eu.friedcutlet.yokan.app.profiles.ProfileBackgroundWork
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult
import eu.friedcutlet.yokan.services.download.DownloadService
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.services.applock.AppLockController
import eu.friedcutlet.yokan.services.applock.createPlatformAppLockController
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.discord.DiscordRpcService
import eu.friedcutlet.yokan.services.discord.createPlatformDiscordRpcService
import eu.friedcutlet.yokan.services.extensions.mihon.ExtensionServerRuntimeMode
import eu.friedcutlet.yokan.services.extensions.mihon.defaultMihonProxyUrl
import eu.friedcutlet.yokan.services.extensions.mihon.extensionServerPortFromUrl
import eu.friedcutlet.yokan.services.http.isLoopbackProxy
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.logging.CrashReportStore
import eu.friedcutlet.yokan.services.scheduling.BackgroundScheduler
import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskOutcome
import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskRunner
import eu.friedcutlet.yokan.services.scheduling.backupFrequencyHours
import eu.friedcutlet.yokan.services.scheduling.periodicMinutes
import eu.friedcutlet.yokan.ui.screens.reader.ReaderSystemUiController
import eu.friedcutlet.yokan.ui.screens.reader.createReaderSystemUiController
import eu.friedcutlet.yokan.util.PlatformLock
import kotlinx.coroutines.launch
import kotlin.concurrent.Volatile

/**
 * Process-wide facade over the currently published session. Mutable dependencies capture that owner;
 * device resources and profile commands survive foreground session retirement.
 */
object YokanRuntime {
    internal val profileUi = eu.friedcutlet.yokan.app.profiles.ProfileUiLifetime()
    internal val profileCoordinator: eu.friedcutlet.yokan.app.profiles.ProfileCoordinator by lazy {
        eu.friedcutlet.yokan.app.profiles.ProfileCoordinator(
            profiles,
            eu.friedcutlet.yokan.app.profiles.createPlatformProfileSession(ProfileId.Default, profiles.syncLeases(ProfileId.Default), ::reschedulePeriodicTasks),
            openSession = { eu.friedcutlet.yokan.app.profiles.openPlatformProfileSession(it, profiles.syncLeases(it), ::reschedulePeriodicTasks) },
            prepare = { owner ->
                owner.attachLogging()
                reschedulePeriodicTasks(owner)
                if (foregroundStarted) startForeground(owner)
            },
            detach = profileUi::detach,
            deleteStorage = { id ->
                eu.friedcutlet.yokan.app.profiles.cancelProfileBackgroundWork(id)
                val exports = profiles.refresh().profiles.single { it.id == id }.exportedBackups
                eu.friedcutlet.yokan.app.profiles.deleteProfileStorage(id, exports)
                scheduleLock.withLock { lastSchedules.remove(id) }
            },
        )
    }
    internal val activeSession: eu.friedcutlet.yokan.app.profiles.ProfileSession get() = profileCoordinator.currentSession
    val database get() = activeSession.database
    val localFiles get() = activeSession.localFiles
    val notifications get() = activeSession.notifications
    val services get() = activeSession.services
    internal val together get() = activeSession.together
    val repository get() = activeSession.repository
    val periodicTasks get() = activeSession.periodicTasks
    val settings get() = activeSession.settings
    val libraryIndex get() = activeSession.libraryIndex
    val libraryUpdates get() = activeSession.libraryUpdates
    val localLibrary get() = activeSession.localLibrary
    val colorizationQueue get() = activeSession.colorizationQueue
    val migration get() = activeSession.migration
    val chapterDownloads get() = activeSession.chapterDownloads
    val sourceInstall get() = activeSession.sourceInstall
    val discordRpc: DiscordRpcService by lazy { createPlatformDiscordRpcService() }
    val readerSystemUi: ReaderSystemUiController by lazy { createReaderSystemUiController() }
    val profiles by lazy { eu.friedcutlet.yokan.app.profiles.createPlatformProfileRegistry() }
    private val backgroundWork by lazy {
        ProfileBackgroundWork(profiles, supported = { true }, sessions = profileCoordinator)
    }

    suspend fun runBackgroundTask(
        owner: String?,
        allowLegacyDefault: Boolean = false,
        task: suspend PeriodicTaskRunner.() -> PeriodicTaskOutcome,
    ): ProfileWorkResult<PeriodicTaskOutcome> = backgroundWork.run(owner, allowLegacyDefault) { session ->
        session.periodicTasks.task()
    }

    suspend fun runBackgroundDownloads(
        owner: String?,
        allowLegacyDefault: Boolean = false,
        task: suspend DownloadService.() -> Unit,
    ): ProfileWorkResult<Unit> = backgroundWork.run(owner, allowLegacyDefault) { session ->
        session.services.downloader.task()
    }

    val appIcons by lazy { eu.friedcutlet.yokan.services.appicons.createPlatformAppIconService() }
    val appLock: AppLockController by lazy { createPlatformAppLockController() }

    // Serializes [bootstrap]: App.kt, desktop main, iOS BGTasks and Android workers can all call it
    // concurrently.
    private val bootstrapLock = PlatformLock()

    @Volatile
    private var report: AppBootstrapReport? = null
    private var foregroundStarted = false

    private val scheduleLock = PlatformLock()
    private val lastSchedules = mutableMapOf<ProfileId, PeriodicSchedule>()

    /**
     * Runs the startup checks once per process; later calls return the same report.
     *
     * [background] callers (OS workers, BGTasks) only need services: they skip the embedded
     * extension server and the in-app [ForegroundScheduler], which start on the first foreground
     * call instead. OS task rescheduling runs in both modes because iOS BGTasks must re-submit
     * themselves after a cold background launch.
     */
    fun bootstrap(
        input: PlatformBootstrapInput = platformBootstrapInput(),
        background: Boolean = false,
    ): AppBootstrapReport = bootstrapLock.withLock {
        val current = report ?: startup(input).also { started ->
            services.scope.launch {
                catchingNonCancellation { profiles.refresh() }
                    .onFailure { AppLogger.warn("Profile registry unavailable; existing Default storage remains available") }
            }
            report = started
            runCatching { reschedulePeriodicTasks() }
                .onFailure { AppLogger.warn("Could not schedule periodic tasks: ${it.message.orEmpty()}") }
        }
        if (!background && !foregroundStarted) {
            foregroundStarted = true
            startForeground(activeSession)
        }
        current
    }

    fun bootstrapReport(): AppBootstrapReport = report ?: bootstrap()

    /**
     * No-op until [bootstrap] has run, and when the settings-derived schedule is unchanged since
     * the last call; [BackgroundScheduler.schedule] itself is idempotent.
     */
    fun reschedulePeriodicTasks() = reschedulePeriodicTasks(activeSession)

    private fun reschedulePeriodicTasks(owner: eu.friedcutlet.yokan.app.profiles.ProfileSession) {
        if (owner.status.value != eu.friedcutlet.yokan.app.profiles.ProfileSessionStatus.Open) return
        val db = owner.database.settings()
        val syncPreference = owner.database.syncPreferences().firstOrNull()
        val syncSeconds = syncPreference
            ?.takeIf { it.syncOn && !it.authToken.isNullOrBlank() }
            ?.autoSyncFrequency
            ?: 0
        val schedule = PeriodicSchedule(
            metadataRefreshMinutes = periodicMinutes(if (db.metadataServerEnabled) db.metadataRefreshFrequencySeconds else 0),
            libraryUpdateMinutes = periodicMinutes(db.libraryUpdateFrequencySeconds),
            libraryUpdateDailyAtMinutes = db.libraryUpdateDailyAtMinutes,
            autoSyncMinutes = periodicMinutes(syncSeconds),
            autoBackupHours = backupFrequencyHours(db.backupFrequency),
            requireUnmetered = db.downloadOnlyOnWifi,
            libraryConstraints = db.features.library.deviceConstraints,
        )
        scheduleLock.withLock {
            if (schedule == lastSchedules[owner.id]) return@withLock
            owner.backgroundScheduler.schedule(
                metadataRefreshMinutes = schedule.metadataRefreshMinutes,
                libraryUpdateMinutes = schedule.libraryUpdateMinutes,
                libraryUpdateDailyAtMinutes = schedule.libraryUpdateDailyAtMinutes,
                autoSyncMinutes = schedule.autoSyncMinutes,
                autoBackupHours = schedule.autoBackupHours,
                requireUnmetered = schedule.requireUnmetered,
                libraryConstraints = schedule.libraryConstraints,
            )
            lastSchedules[owner.id] = schedule
        }
    }

    private fun startup(input: PlatformBootstrapInput): AppBootstrapReport {
        val crashFiles = eu.friedcutlet.yokan.services.files.createPlatformLocalFileService(ProfileId.Default)
        installPlatformCrashLogger { throwable ->
            // Broken pipes are routine when a client (player, WebView resource
            // fetch, etc.) disconnects mid-write — drop them to debug so they
            // don't masquerade as crashes.
            val name = throwable::class.simpleName.orEmpty()
            val message = throwable.message.orEmpty()
            val isBrokenPipe = name == "SocketException" && message.contains("broken pipe", ignoreCase = true)
            if (isBrokenPipe) {
                AppLogger.warn("Suppressed $name: $message")
            } else {
                CrashReportStore.record(crashFiles, throwable)
                AppLogger.error("Unhandled $name: ${CrashReportStore.redact(message)}")
            }
        }
        activeSession.attachLogging()
        return runStartupChecks(input, services, discordRpc)
    }

    private fun startForeground(owner: eu.friedcutlet.yokan.app.profiles.ProfileSession) {
        scheduleExtensionServerStart(owner)
        if (owner.colorizationQueue.supported) owner.colorizationQueue.start()
        owner.foregroundScheduler.start()
        owner.syncTriggers.onTrigger(eu.friedcutlet.yokan.services.sync.SyncTriggerKind.AppStart)
    }

    private fun scheduleExtensionServerStart(owner: eu.friedcutlet.yokan.app.profiles.ProfileSession) {
        val services = owner.services
        val database = owner.database
        if (services.extensionServer.mode == ExtensionServerRuntimeMode.IosSideloadedJvm) return
        if (database.sources().none { it.sourceCodeLanguage == DbSourceCodeLanguage.Mihon }) return
        val proxy = database.settings().androidProxyServer ?: defaultMihonProxyUrl
        if (!isLoopbackProxy(proxy) || !services.extensionServer.isConfigured()) return
        services.scope.launch {
            catchingNonCancellation {
                services.extensionServer.startIfConfigured(extensionServerPortFromUrl(proxy))
            }.onSuccess { status ->
                AppLogger.info(
                    "Extension runtime: local server ${status?.phase?.name?.lowercase() ?: "not configured"}",
                )
            }.onFailure { error ->
                AppLogger.warn(
                    "Extension runtime: ${error.message.orEmpty().ifBlank { "local extension server failed to start" }}",
                )
            }
        }
    }
}

/** The arguments of [BackgroundScheduler.schedule], compared to skip redundant rescheduling. */
private data class PeriodicSchedule(
    val metadataRefreshMinutes: Long,
    val libraryUpdateMinutes: Long,
    val libraryUpdateDailyAtMinutes: Int,
    val autoSyncMinutes: Long,
    val autoBackupHours: Long,
    val requireUnmetered: Boolean,
    val libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints,
)
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileBackgroundWork.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileBackgroundWork.kt) · implementation · 42 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
9: internal interface ProfileWorkSessions {
10: suspend fun <T> run(id: ProfileId, action: suspend (ProfileSession) -> T): ProfileWorkResult<T>
17: internal class ProfileBackgroundWork(
22: suspend fun <T> run(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileBackgroundWork.kt) · SHA-256 `97ee8371d33c1e237754ac3e92f8fe867a860ddfc210dedadf5d905db2468d52`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult

internal interface ProfileWorkSessions {
    suspend fun <T> run(id: ProfileId, action: suspend (ProfileSession) -> T): ProfileWorkResult<T>
}

/**
 * Checks fresh metadata before opening any database. No lookup uses lastActive or falls back from
 * an explicit invalid/unavailable owner. Production uses the coordinator's storage lease; retired owners never recreate their data.
 */
internal class ProfileBackgroundWork(
    private val registry: ProfileRegistry,
    private val supported: (ProfileId) -> Boolean,
    private val sessions: ProfileWorkSessions,
) {
    suspend fun <T> run(
        serializedOwner: String?,
        allowLegacyDefault: Boolean = false,
        action: suspend (ProfileSession) -> T,
    ): ProfileWorkResult<T> {
        currentCoroutineContext().ensureActive()
        val id = if (serializedOwner == null) {
            if (!allowLegacyDefault) return ProfileWorkResult.Skipped
            ProfileId.Default
        } else {
            try { ProfileId(serializedOwner) }
            catch (_: IllegalArgumentException) { return ProfileWorkResult.Skipped }
        }
        val snapshot = try { registry.refresh() }
        catch (error: CancellationException) { throw error }
        catch (_: Exception) { return ProfileWorkResult.Retry }
        currentCoroutineContext().ensureActive()
        if (snapshot.available(id) == null || !supported(id)) return ProfileWorkResult.Skipped
        return sessions.run(id, action)
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileBackupOperations.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileBackupOperations.kt) · implementation · 90 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
15: internal data class TargetedBackupPlan(val target: ProfileId, val plan: BackupPlan)
18: internal class ProfileBackupOperations(private val registry: ProfileRegistry, private val coordinator: ProfileCoordinator) {
19: suspend fun export(id: ProfileId, options: BackupOptions, password: String?): BackupResult? = coordinator.withProfile(id) { owner ->
29: suspend fun open(id: ProfileId, bytes: ByteArray, password: String?): BackupOpenResult = coordinator.withProfile(id) { owner ->
35: suspend fun read(id: ProfileId, path: String): ByteArray = coordinator.withProfile(id) { it.backup.readBackupFile(path) }
36: suspend fun apply(target: TargetedBackupPlan, mode: RestoreMode): RestorePreview = coordinator.replaceProfileData(target.target) { owner ->
41: suspend fun snapshots(id: ProfileId): List<SafetySnapshot> = coordinator.withProfile(id) { it.backup.listSafetySnapshots() }
42: suspend fun rollback(id: ProfileId, snapshot: SafetySnapshot): RestorePreview = coordinator.replaceProfileData(id) { owner ->
49: internal fun profileRestorePlan(plan: BackupPlan, current: DbSettings): BackupPlan {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileBackupOperations.kt) · SHA-256 `018d3316a5e6131e16b782f68457931d9c6e68c330b01c67b05b96a4891a25bd`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.services.files.exportFile
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.backup.SafetySnapshot
import eu.friedcutlet.yokan.services.backup.BackupPlan
import eu.friedcutlet.yokan.services.backup.BackupOpenResult
import eu.friedcutlet.yokan.services.backup.RestoreMode
import eu.friedcutlet.yokan.services.backup.BackupOptions
import eu.friedcutlet.yokan.services.backup.BackupResult
import eu.friedcutlet.yokan.services.backup.BackupSection
import eu.friedcutlet.yokan.services.backup.RestorePreview

internal data class TargetedBackupPlan(val target: ProfileId, val plan: BackupPlan)

/** All stages carry the selected ID. Payload metadata never chooses or creates a destination. */
internal class ProfileBackupOperations(private val registry: ProfileRegistry, private val coordinator: ProfileCoordinator) {
    suspend fun export(id: ProfileId, options: BackupOptions, password: String?): BackupResult? = coordinator.withProfile(id) { owner ->
        val backup = owner.backup
        val exported = if (password.isNullOrEmpty()) backup.exportBackup(options) else backup.exportEncryptedBackup(options, password)
        val path = exportFile(exported.bytes, exported.fileName, exported.contentType,
            owner.database.settings().autoBackupLocation?.takeIf { it.isNotBlank() } ?: owner.localFiles.backupRoot)
        path?.let {
            registry.recordExport(id, it)
            BackupResult(exported.fileName, exported.bytes.size.toLong(), exported.itemCount, it)
        }
    }
    suspend fun open(id: ProfileId, bytes: ByteArray, password: String?): BackupOpenResult = coordinator.withProfile(id) { owner ->
        when (val opened = owner.backup.openBackup(bytes, password)) {
            is BackupOpenResult.Ready -> BackupOpenResult.Ready(profileRestorePlan(opened.plan, owner.database.settings()))
            is BackupOpenResult.Failure -> opened
        }
    }
    suspend fun read(id: ProfileId, path: String): ByteArray = coordinator.withProfile(id) { it.backup.readBackupFile(path) }
    suspend fun apply(target: TargetedBackupPlan, mode: RestoreMode): RestorePreview = coordinator.replaceProfileData(target.target) { owner ->
        // Re-read destination device fields after final progress has drained; never adopt imported grants.
        val plan = profileRestorePlan(target.plan, owner.database.settings()).withMode(mode)
        owner.backup.applyBackup(plan, mode)
    }
    suspend fun snapshots(id: ProfileId): List<SafetySnapshot> = coordinator.withProfile(id) { it.backup.listSafetySnapshots() }
    suspend fun rollback(id: ProfileId, snapshot: SafetySnapshot): RestorePreview = coordinator.replaceProfileData(id) { owner ->
        require(snapshot in owner.backup.listSafetySnapshots()) { "Safety snapshot belongs to another target or no longer exists" }
        owner.backup.rollbackSafetySnapshot(snapshot)
    }
}

/** Profile data can move; OS permissions, native paths and destination credentials stay with their owner. */
internal fun profileRestorePlan(plan: BackupPlan, current: DbSettings): BackupPlan {
    val incoming = plan.snapshot
    val settings = incoming.settings?.copy(
        cookiesList = current.cookiesList,
        sourcePreferences = current.sourcePreferences,
        downloadLocation = current.downloadLocation,
        autoBackupLocation = current.autoBackupLocation,
        localFolders = current.localFolders,
        namedLocalFolders = current.namedLocalFolders,
        downloadLocalFolderName = current.downloadLocalFolderName,
        jrePath = current.jrePath,
        extensionServerPath = current.extensionServerPath,
        androidProxyServer = current.androidProxyServer,
        themeSeedImagePath = current.themeSeedImagePath,
        lastTrackerLibraryLocation = current.lastTrackerLibraryLocation,
        desktopLaunchAtLogin = current.desktopLaunchAtLogin,
        backupEncryptionEnabled = current.backupEncryptionEnabled,
        backupEncryptionPassword = current.backupEncryptionPassword,
        metadataServerUrl = current.metadataServerUrl,
        metadataServerToken = current.metadataServerToken,
        features = current.features,
        btServerAddress = current.btServerAddress,
        btServerPort = current.btServerPort,
    )
    val sections = plan.includedSections - BackupSection.TrackPreferences
    val snapshot = incoming.copy(
        settings = settings,
        includedSections = sections.toList(),
        trackPreferences = emptyList(),
        chapters = incoming.chapters.map { it.copy(archivePath = "", downloadSize = null) },
        mangas = incoming.mangas.map { manga ->
            if (manga.isLocalArchive) manga.copy(link = null) else manga
        },
    )
    return BackupPlan(
        preview = plan.preview.copy(warnings = (plan.preview.warnings + "Device paths, local file links and login credentials are not imported. Downloaded files require relinking.").distinct()),
        snapshot = snapshot,
        includedSections = sections,
        resolvedPassword = null,
        mode = plan.mode,
    )
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileCoordinator.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileCoordinator.kt) · implementation · 289 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
16: internal sealed interface ProfileActivationState {
17: data class Ready(val session: ProfileSession, val recoveryMessage: String? = null) : ProfileActivationState
18: data class Switching(val from: ProfileId, val to: ProfileId) : ProfileActivationState
19: data class RecoveryRequired(val profile: ProfileId, val message: String) : ProfileActivationState
27: internal class ProfileCoordinator(
42: private class WorkLease(val session: ProfileSession, var references: Int = 0)
46: override suspend fun <T> run(id: ProfileId, action: suspend (ProfileSession) -> T): ProfileWorkResult<T> {
76: suspend fun switchTo(id: ProfileId) = mutex.withLock {
84: suspend fun recover() = mutex.withLock {
103: suspend fun create(name: String): ProfileId = mutex.withLock {
115: suspend fun resumeProvisioning(id: ProfileId) = mutex.withLock {
125: suspend fun rename(id: ProfileId, name: String) = mutex.withLock {
130: suspend fun delete(id: ProfileId) = mutex.withLock {
150: suspend fun <T> withProfile(id: ProfileId, action: suspend (ProfileSession) -> T): T = mutex.withLock {
166: suspend fun <T> replaceProfileData(id: ProfileId, action: suspend (ProfileSession) -> T): T = mutex.withLock {
197: private suspend fun <T> ProfileSession.runLeasedWork(action: suspend (ProfileSession) -> T): T =
204: private suspend fun provisionLocked(id: ProfileId) {
210: private suspend fun switchLocked(id: ProfileId) = withContext(NonCancellable) {
243: private suspend fun publishFresh(id: ProfileId, message: String? = null) = publish(checkedOpen(id), message)
245: private suspend fun publish(replacement: ProfileSession, message: String? = null) {
257: private suspend fun checkedOpen(id: ProfileId): ProfileSession {
266: private suspend fun release(session: ProfileSession) {
274: private suspend fun releaseSuppressing(session: ProfileSession, error: Exception) {
278: private fun failRecovery(id: ProfileId, error: Exception, fallback: String) {
282: private suspend fun retryReleases() = withContext(NonCancellable) {
286: private fun requireReady() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileCoordinator.kt) · SHA-256 `6b320f996edaae0bc031a83f803eab9dd19c4bdcdcb95152edb8346cdeb2e90b`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult

internal sealed interface ProfileActivationState {
    data class Ready(val session: ProfileSession, val recoveryMessage: String? = null) : ProfileActivationState
    data class Switching(val from: ProfileId, val to: ProfileId) : ProfileActivationState
    data class RecoveryRequired(val profile: ProfileId, val message: String) : ProfileActivationState
}

/**
 * Serializes activation and storage leases. A retiring owner is never republished: recovery opens a
 * fresh session only after every failed release succeeds. The UI detach hook must await composition
 * disposal (including its final progress saves) before session retirement begins.
 */
internal class ProfileCoordinator(
    private val registry: ProfileRegistry,
    initialSession: ProfileSession,
    private val openSession: suspend (ProfileId) -> ProfileSession,
    private val prepare: suspend (ProfileSession) -> Unit,
    private val detach: suspend (ProfileSession) -> Unit,
    private val deleteStorage: suspend (ProfileId) -> Unit,
) : ProfileWorkSessions {
    private val mutex = Mutex()
    private val _state = MutableStateFlow<ProfileActivationState>(ProfileActivationState.Ready(initialSession))
    val state = _state.asStateFlow()
    @kotlin.concurrent.Volatile
    private var active = initialSession
    val currentSession: ProfileSession get() = active
    private val pendingRetirements = mutableListOf<ProfileSession>()
    private class WorkLease(val session: ProfileSession, var references: Int = 0)
    private val workLeases = mutableMapOf<ProfileId, WorkLease>()

    /** Long OS jobs do not hold the mutation mutex. Retirement cancels/joins their captured session. */
    override suspend fun <T> run(id: ProfileId, action: suspend (ProfileSession) -> T): ProfileWorkResult<T> {
        val lease = mutex.withLock {
            currentCoroutineContext().ensureActive()
            if (_state.value !is ProfileActivationState.Ready) return ProfileWorkResult.Retry
            retryReleases()
            if (registry.refresh().available(id) == null) return ProfileWorkResult.Skipped
            val target = workLeases[id] ?: WorkLease(if (active.id == id) active else checkedOpen(id))
                .also { workLeases[id] = it }
            target.references++
            target
        }
        return try {
            lease.session.runBackgroundWork(action)
        } catch (cancelled: CancellationException) {
            currentCoroutineContext().ensureActive()
            if (lease.session.status.value == ProfileSessionStatus.Open) throw cancelled
            ProfileWorkResult.Skipped
        } finally {
            withContext(NonCancellable) {
                mutex.withLock {
                    lease.references--
                    if (lease.references == 0) {
                        if (workLeases[id] === lease) workLeases.remove(id)
                        if (lease.session !== active) release(lease.session)
                    }
                }
            }
        }
    }

    suspend fun switchTo(id: ProfileId) = mutex.withLock {
        currentCoroutineContext().ensureActive()
        requireNotNull(registry.refresh().available(id)) { "Profile is unavailable" }
        retryReleases()
        if (_state.value is ProfileActivationState.Ready && active.id == id) return@withLock
        switchLocked(id)
    }

    suspend fun recover() = mutex.withLock {
        currentCoroutineContext().ensureActive()
        withContext(NonCancellable) {
            if (_state.value is ProfileActivationState.Ready) {
                retryReleases()
            } else {
                try {
                    detach(active)
                    release(active)
                    retryReleases()
                    publishFresh(active.id)
                } catch (error: Exception) {
                    failRecovery(active.id, error, "Profile recovery failed")
                    throw error
                }
            }
        }
    }

    suspend fun create(name: String): ProfileId = mutex.withLock {
        currentCoroutineContext().ensureActive()
        requireReady()
        retryReleases()
        val id = ProfileId.random()
        registry.beginCreate(name, id)
        // Provisioning stays visible in metadata if a database/storage commit fails. Retry resumes
        // the same ID; abandoning it requires the normal staged deletion path.
        provisionLocked(id)
        id
    }

    suspend fun resumeProvisioning(id: ProfileId) = mutex.withLock {
        currentCoroutineContext().ensureActive()
        requireReady()
        retryReleases()
        require(registry.refresh().profiles.any { it.id == id && it.status == ProfileStatus.Provisioning }) {
            "Profile is not provisioning"
        }
        provisionLocked(id)
    }

    suspend fun rename(id: ProfileId, name: String) = mutex.withLock {
        currentCoroutineContext().ensureActive()
        registry.rename(id, name)
    }

    suspend fun delete(id: ProfileId) = mutex.withLock {
        currentCoroutineContext().ensureActive()
        require(id != ProfileId.Default) { "Default cannot be deleted" }
        val snapshot = registry.refresh()
        if (id in snapshot.retiredIds) return@withLock
        require(snapshot.profiles.any { it.id == id }) { "Unknown profile" }
        retryReleases()
        if (active.id == id) switchLocked(ProfileId.Default)
        requireReady()
        // Keep the tombstone stage until both scoped scheduler/storage cleanup and its durable
        // metadata commit complete. The mutex excludes backups and background storage leases.
        registry.beginDelete(id)
        withContext(NonCancellable) {
            workLeases[id]?.session?.let { release(it) }
            deleteStorage(id)
            registry.finishDelete(id)
        }
    }

    /** Pins an explicit target through the entire operation; metadata in a backup never selects it. */
    suspend fun <T> withProfile(id: ProfileId, action: suspend (ProfileSession) -> T): T = mutex.withLock {
        currentCoroutineContext().ensureActive()
        requireReady()
        retryReleases()
        requireNotNull(registry.refresh().available(id)) { "Profile is unavailable" }
        if (active.id == id) {
            active.runLeasedWork(action)
        } else {
            val background = workLeases[id]?.session
            val session = background ?: checkedOpen(id)
            try { session.runLeasedWork(action) }
            finally { if (background == null) withContext(NonCancellable) { release(session) } }
        }
    }

    /** Data replacement runs after final UI progress and background finalizers, using a fresh DB owner. */
    suspend fun <T> replaceProfileData(id: ProfileId, action: suspend (ProfileSession) -> T): T = mutex.withLock {
        currentCoroutineContext().ensureActive()
        requireReady()
        retryReleases()
        requireNotNull(registry.refresh().available(id)) { "Profile is unavailable" }
        withContext(NonCancellable) {
            workLeases[id]?.session?.takeIf { it !== active }?.let { release(it) }
            val foreground = active.id == id
            if (foreground) {
                _state.update { ProfileActivationState.Switching(id, id) }
                try { detach(active); release(active) }
                catch (error: Exception) {
                    failRecovery(id, error, "Profile shutdown failed")
                    throw error
                }
            }
            try {
                val target = checkedOpen(id)
                val result = try { target.runLeasedWork(action) } finally { release(target) }
                if (foreground) publishFresh(id)
                result
            } catch (error: Exception) {
                if (foreground) {
                    try { retryReleases(); publishFresh(id, error.message ?: "Restore failed") }
                    catch (recovery: Exception) { failRecovery(id, recovery, "Profile recovery failed") }
                }
                throw error
            }
        }
    }

    private suspend fun <T> ProfileSession.runLeasedWork(action: suspend (ProfileSession) -> T): T =
        when (val result = runBackgroundWork(action)) {
            is ProfileWorkResult.Completed -> result.value
            ProfileWorkResult.Skipped -> error("Profile retired before the operation started")
            ProfileWorkResult.Retry -> error("Profile operation requires retry")
        }

    private suspend fun provisionLocked(id: ProfileId) {
        val session = checkedOpen(id)
        try { session.database } finally { withContext(NonCancellable) { release(session) } }
        registry.markReady(id)
    }

    private suspend fun switchLocked(id: ProfileId) = withContext(NonCancellable) {
        val previous = active.id
        // Reserve and validate only storage before detaching. A foreign owner or broken database
        // must not take down the current foreground session. Native services wait until retirement.
        workLeases[id]?.session?.let { release(it) }
        val candidate = checkedOpen(id)
        try { candidate.database }
        catch (error: Exception) {
            releaseSuppressing(candidate, error)
            throw error
        }
        _state.update { ProfileActivationState.Switching(previous, id) }
        try {
            detach(active)
            release(active)
        } catch (error: Exception) {
            releaseSuppressing(candidate, error)
            failRecovery(previous, error, "Profile shutdown failed")
            throw error
        }
        try {
            publish(candidate)
        } catch (error: Exception) {
            try {
                retryReleases()
                publishFresh(previous, error.message ?: "Profile activation failed")
            } catch (recovery: Exception) {
                failRecovery(previous, recovery, "Profile recovery failed")
            }
            throw error
        }
    }

    private suspend fun publishFresh(id: ProfileId, message: String? = null) = publish(checkedOpen(id), message)

    private suspend fun publish(replacement: ProfileSession, message: String? = null) {
        try {
            prepare(replacement)
            registry.recordActive(replacement.id)
        } catch (error: Exception) {
            releaseSuppressing(replacement, error)
            throw error
        }
        active = replacement
        _state.update { ProfileActivationState.Ready(replacement, message) }
    }

    private suspend fun checkedOpen(id: ProfileId): ProfileSession {
        val session = openSession(id)
        if (session.id != id || session.status.value != ProfileSessionStatus.Open) {
            withContext(NonCancellable) { release(session) }
            error("Session factory returned a different or retired profile")
        }
        return session
    }

    private suspend fun release(session: ProfileSession) {
        if (session !in pendingRetirements) pendingRetirements.add(session)
        session.close()
        pendingRetirements.remove(session)
        workLeases.entries.removeAll { it.value.session === session }
    }

    /** Releases [session] during [error] handling; a cleanup failure is attached to [error]. */
    private suspend fun releaseSuppressing(session: ProfileSession, error: Exception) {
        try { release(session) } catch (cleanup: Exception) { error.addSuppressed(cleanup) }
    }

    private fun failRecovery(id: ProfileId, error: Exception, fallback: String) {
        _state.update { ProfileActivationState.RecoveryRequired(id, error.message ?: fallback) }
    }

    private suspend fun retryReleases() = withContext(NonCancellable) {
        pendingRetirements.toList().forEach { release(it) }
    }

    private fun requireReady() {
        check(_state.value is ProfileActivationState.Ready) { "Recover the retiring profile before continuing" }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.kt) · implementation · 201 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
19: enum class ProfileStatus { Provisioning, Ready, Deleting }
21: data class ProfileRecord(
30: data class ProfileSyncLease(val key: String, val owner: ProfileId)
32: data class ProfileRegistrySnapshot(
40: fun available(id: ProfileId): ProfileRecord? = profiles.singleOrNull { it.id == id && it.status == ProfileStatus.Ready }
48: internal fun validateProfileRegistry(snapshot: ProfileRegistrySnapshot): ProfileRegistrySnapshot {
70: private fun profileName(name: String): String = name.trim().also { normalized ->
74: internal fun encodeProfileRegistry(snapshot: ProfileRegistrySnapshot): String = RegistryJson.encodeToString(validateProfileRegistry(snapshot)).also {
77: internal fun decodeProfileRegistry(raw: String): ProfileRegistrySnapshot {
83: interface ProfileRegistryPersistence {
84: suspend fun read(): String?
85: suspend fun compareAndSet(expected: String?, replacement: String): Boolean
87: sealed interface ProfileRegistryState {
88: data object Uninitialized : ProfileRegistryState
89: data class Ready(val snapshot: ProfileRegistrySnapshot) : ProfileRegistryState
90: data object Unavailable : ProfileRegistryState
94: class ProfileRegistry(private val persistence: ProfileRegistryPersistence) {
99: suspend fun refresh(): ProfileRegistrySnapshot = edit { it }
100: suspend fun beginCreate(name: String, id: ProfileId = ProfileId.random()): ProfileRegistrySnapshot = edit { old ->
104: suspend fun markReady(id: ProfileId): ProfileRegistrySnapshot = edit { old ->
109: suspend fun rename(id: ProfileId, name: String): ProfileRegistrySnapshot = edit { old ->
114: suspend fun recordExport(id: ProfileId, path: String): ProfileRegistrySnapshot = edit { old ->
128: suspend fun claimSyncLease(owner: ProfileId, key: String) {
143: suspend fun releaseSyncLease(owner: ProfileId, key: String): ProfileRegistrySnapshot = edit { old ->
146: fun syncLeases(owner: ProfileId) = object : eu.friedcutlet.yokan.services.sync.SyncAccountLeases {
147: override suspend fun claim(key: String) = claimSyncLease(owner, key)
148: override suspend fun release(key: String) { releaseSyncLease(owner, key) }
152: suspend fun recordActive(id: ProfileId): ProfileRegistrySnapshot = edit { old ->
157: suspend fun beginDelete(id: ProfileId): ProfileRegistrySnapshot = edit { old ->
167: suspend fun finishDelete(id: ProfileId): ProfileRegistrySnapshot = edit { old ->
174: private suspend fun edit(transform: (ProfileRegistrySnapshot) -> ProfileRegistrySnapshot): ProfileRegistrySnapshot = mutex.withLock {
200: expect fun createPlatformProfileRegistry(): ProfileRegistry
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.kt) · SHA-256 `43319bbe5c8bab6991fbf5afc709f480060be2600d57d650d6cd852f2581e88b`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import eu.friedcutlet.yokan.domain.ProfileId


@Serializable
enum class ProfileStatus { Provisioning, Ready, Deleting }
@Serializable
data class ProfileRecord(
    val id: ProfileId,
    val name: String,
    val status: ProfileStatus = ProfileStatus.Ready,
    /** Explicit save destinations are device metadata, never imported from backups. */
    val exportedBackups: List<String> = emptyList(),
)
/** Device-wide claim on one remote sync account; see [ProfileRegistry.claimSyncLease]. */
@Serializable
data class ProfileSyncLease(val key: String, val owner: ProfileId)
@Serializable
data class ProfileRegistrySnapshot(
    val version: Int = 1,
    val profiles: List<ProfileRecord> = listOf(ProfileRecord(ProfileId.Default, "Default")),
    val lastActive: ProfileId = ProfileId.Default,
    val retiredIds: List<ProfileId> = emptyList(),
    val syncLeases: List<ProfileSyncLease> = emptyList(),
) {
    val hasAdditionalProfiles: Boolean get() = profiles.any { it.id != ProfileId.Default && it.status == ProfileStatus.Ready }
    fun available(id: ProfileId): ProfileRecord? = profiles.singleOrNull { it.id == id && it.status == ProfileStatus.Ready }
}

internal const val MaxProfileRegistryBytes = 262_144
internal const val MaxRetiredProfileIds = 4096
internal const val MaxSyncLeaseKeyLength = 2048
private val RegistryJson = Json { encodeDefaults = true }

internal fun validateProfileRegistry(snapshot: ProfileRegistrySnapshot): ProfileRegistrySnapshot {
    require(snapshot.version == 1) { "Unsupported profile registry version" }
    require(snapshot.profiles.size in 1..64 && snapshot.retiredIds.size <= MaxRetiredProfileIds) { "Profile registry limit exceeded" }
    require(snapshot.profiles.map { it.id }.distinct().size == snapshot.profiles.size) { "Duplicate profile IDs" }
    require(snapshot.retiredIds.distinct().size == snapshot.retiredIds.size) { "Duplicate retired profile IDs" }
    require(snapshot.retiredIds.none { id -> id == ProfileId.Default || snapshot.profiles.any { it.id == id } }) { "Retired profile reused" }
    require(snapshot.profiles.singleOrNull { it.id == ProfileId.Default } == ProfileRecord(ProfileId.Default, "Default")) { "Default profile must remain permanent" }
    snapshot.profiles.forEach {
        require(it.name == profileName(it.name)) { "Invalid stored profile name" }
        require(it.exportedBackups.distinct().size == it.exportedBackups.size && it.exportedBackups.size <= 512) { "Invalid exported backup records" }
        it.exportedBackups.forEach { path -> require(path.isNotBlank() && path.length <= 4096 && path.none { c -> c.code < 32 }) { "Invalid export destination" } }
    }
    require(snapshot.profiles.map { it.name.lowercase() }.distinct().size == snapshot.profiles.size) { "Duplicate profile names" }
    require(snapshot.syncLeases.map { it.key }.distinct().size == snapshot.syncLeases.size &&
        snapshot.syncLeases.map { it.owner }.distinct().size == snapshot.syncLeases.size) { "Duplicate sync leases" }
    snapshot.syncLeases.forEach { lease ->
        require(lease.key.isNotEmpty() && lease.key.length <= MaxSyncLeaseKeyLength) { "Invalid sync lease" }
        require(snapshot.profiles.any { it.id == lease.owner && it.status != ProfileStatus.Deleting }) { "Sync lease owner is unavailable" }
    }
    require(snapshot.available(snapshot.lastActive) != null) { "Active profile is unavailable" }
    return snapshot
}
private fun profileName(name: String): String = name.trim().also { normalized ->
    require(normalized.isNotEmpty() && normalized.length <= 80 && normalized.none { it.code < 32 || it.code in 127..159 }) { "Invalid profile name" }
    normalized.encodeToByteArray(throwOnInvalidSequence = true)
}
internal fun encodeProfileRegistry(snapshot: ProfileRegistrySnapshot): String = RegistryJson.encodeToString(validateProfileRegistry(snapshot)).also {
    require(it.encodeToByteArray().size <= MaxProfileRegistryBytes) { "Profile registry limit exceeded" }
}
internal fun decodeProfileRegistry(raw: String): ProfileRegistrySnapshot {
    require(raw.encodeToByteArray().size <= MaxProfileRegistryBytes) { "Profile registry limit exceeded" }
    return validateProfileRegistry(RegistryJson.decodeFromString<ProfileRegistrySnapshot>(raw))
}

/** CAS must be serialized across every process/tab sharing this device registry and atomic on disk. */
interface ProfileRegistryPersistence {
    suspend fun read(): String?
    suspend fun compareAndSet(expected: String?, replacement: String): Boolean
}
sealed interface ProfileRegistryState {
    data object Uninitialized : ProfileRegistryState
    data class Ready(val snapshot: ProfileRegistrySnapshot) : ProfileRegistryState
    data object Unavailable : ProfileRegistryState
}

/** Metadata only. A session coordinator must provision/close/delete storage before committing stages. */
class ProfileRegistry(private val persistence: ProfileRegistryPersistence) {
    private val mutex = Mutex()
    private val _state = MutableStateFlow<ProfileRegistryState>(ProfileRegistryState.Uninitialized)
    val state = _state.asStateFlow()

    suspend fun refresh(): ProfileRegistrySnapshot = edit { it }
    suspend fun beginCreate(name: String, id: ProfileId = ProfileId.random()): ProfileRegistrySnapshot = edit { old ->
        require(id != ProfileId.Default && id !in old.retiredIds && old.profiles.none { it.id == id }) { "Profile ID unavailable" }
        old.copy(profiles = old.profiles + ProfileRecord(id, profileName(name), ProfileStatus.Provisioning))
    }
    suspend fun markReady(id: ProfileId): ProfileRegistrySnapshot = edit { old ->
        val record = requireNotNull(old.profiles.singleOrNull { it.id == id }) { "Unknown profile" }
        require(record.status == ProfileStatus.Provisioning) { "Profile is not provisioning" }
        old.copy(profiles = old.profiles.map { if (it.id == id) it.copy(status = ProfileStatus.Ready) else it })
    }
    suspend fun rename(id: ProfileId, name: String): ProfileRegistrySnapshot = edit { old ->
        require(id != ProfileId.Default && old.available(id) != null) { "Profile cannot be renamed" }
        old.copy(profiles = old.profiles.map { if (it.id == id) it.copy(name = profileName(name)) else it })
    }
    /** Record a successful explicit export while the target lease is still held. Default is never deleted. */
    suspend fun recordExport(id: ProfileId, path: String): ProfileRegistrySnapshot = edit { old ->
        if (id == ProfileId.Default) old else {
            requireNotNull(old.available(id)) { "Export profile is unavailable" }
            old.copy(profiles = old.profiles.map {
                if (it.id == id) it.copy(exportedBackups = (it.exportedBackups + path).distinct()) else it
            })
        }
    }

    /**
     * A profile has one sync preference, so it holds at most one lease: claiming replaces the owner's
     * previous lease. Idempotent for the holder; fails while another profile holds [key]. A conflict
     * leaves the registry untouched (and [state] Ready) instead of failing the edit.
     */
    suspend fun claimSyncLease(owner: ProfileId, key: String) {
        require(key.isNotEmpty() && key.length <= MaxSyncLeaseKeyLength) { "This sync account address is too long." }
        val next = edit { old ->
            val claimable = old.profiles.any { it.id == owner && it.status != ProfileStatus.Deleting } &&
                old.syncLeases.none { it.key == key && it.owner != owner }
            if (!claimable) old else old.copy(syncLeases = old.syncLeases.filterNot { it.owner == owner } + ProfileSyncLease(key, owner))
        }
        val held = next.syncLeases.singleOrNull { it.key == key }
        if (held?.owner == owner) return
        val name = next.profiles.singleOrNull { it.id == held?.owner }?.name
        throw IllegalStateException(
            if (name == null) "This profile can no longer connect sync accounts."
            else "This sync account is already connected to profile ‘$name’. Log out there first.",
        )
    }
    suspend fun releaseSyncLease(owner: ProfileId, key: String): ProfileRegistrySnapshot = edit { old ->
        old.copy(syncLeases = old.syncLeases.filterNot { it.owner == owner && it.key == key })
    }
    fun syncLeases(owner: ProfileId) = object : eu.friedcutlet.yokan.services.sync.SyncAccountLeases {
        override suspend fun claim(key: String) = claimSyncLease(owner, key)
        override suspend fun release(key: String) { releaseSyncLease(owner, key) }
    }

    /** Call only after the replacement session is ready and the old session has been retired. */
    suspend fun recordActive(id: ProfileId): ProfileRegistrySnapshot = edit { old ->
        require(old.available(id) != null) { "Profile is unavailable" }
        old.copy(lastActive = id)
    }
    /** The coordinator must first safely switch away from an active extra profile. */
    suspend fun beginDelete(id: ProfileId): ProfileRegistrySnapshot = edit { old ->
        require(id != ProfileId.Default && id != old.lastActive) { "Switch away before deleting this profile" }
        require(old.profiles.any { it.id == id }) { "Unknown profile" }
        require(old.retiredIds.size < MaxRetiredProfileIds) { "Profile deletion capacity reached" }
        old.copy(
            profiles = old.profiles.map { if (it.id == id) it.copy(status = ProfileStatus.Deleting) else it },
            syncLeases = old.syncLeases.filterNot { it.owner == id },
        )
    }
    /** Commit only after app-owned data is gone; interrupted deletions remain recoverable. */
    suspend fun finishDelete(id: ProfileId): ProfileRegistrySnapshot = edit { old ->
        if (id in old.retiredIds) old else {
            require(old.profiles.any { it.id == id && it.status == ProfileStatus.Deleting }) { "Profile is not deleting" }
            old.copy(profiles = old.profiles.filterNot { it.id == id }, retiredIds = old.retiredIds + id)
        }
    }

    private suspend fun edit(transform: (ProfileRegistrySnapshot) -> ProfileRegistrySnapshot): ProfileRegistrySnapshot = mutex.withLock {
        try {
            currentCoroutineContext().ensureActive()
            // Once a store commit begins, join its result before publishing metadata. This does not
            // make provisioning/switching irreversible: those are separate coordinator operations.
            withContext(NonCancellable) {
                repeat(16) {
                    val raw = persistence.read()
                    val old = raw?.let(::decodeProfileRegistry) ?: ProfileRegistrySnapshot()
                    val next = validateProfileRegistry(transform(old))
                    if ((raw != null && next == old) || persistence.compareAndSet(raw, encodeProfileRegistry(next))) {
                        _state.update { ProfileRegistryState.Ready(next) }
                        return@withContext next
                    }
                }
                error("Profile registry changed repeatedly; retry")
            }
        } catch (error: CancellationException) {
            throw error
        } catch (error: Exception) {
            _state.update { ProfileRegistryState.Unavailable }
            throw error
        }
    }
}

expect fun createPlatformProfileRegistry(): ProfileRegistry

```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSession.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSession.kt) · implementation · 300 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
63: enum class ProfileSessionStatus { Open, Retiring, RetirementFailed, Closed }
66: internal class ProfileSession(
117: private fun buildServices(): YokanServices = defaultServices(
233: fun attachLogging() { loggingTarget }
236: suspend fun <T> runBackgroundWork(action: suspend (ProfileSession) -> T): ProfileWorkResult<T> {
243: suspend fun close() = retirementLock.withLock retirement@{
264: private fun <T> owned(close: suspend (T) -> Unit = {}, factory: () -> T): OwnedResource<T> =
268: fun <T> ownResource(factory: () -> T, close: suspend (T) -> Unit): T = resourceLock.withLock {
277: fun initialize(): T = value.value
278: fun peek(): T? = if (value.isInitialized()) value.value else null
279: override fun getValue(thisRef: ProfileSession, property: KProperty<*>): T = resourceLock.withLock {
283: suspend fun closeIfInitialized() {
293: internal fun createPlatformProfileSession(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSession.kt) · SHA-256 `c346e95b6da3833658f5a1942d14262984f3587bab3d6f7551262b5f519c6bae`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.app.YokanServices
import eu.friedcutlet.yokan.app.defaultServices
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.createProfileDatabase
import eu.friedcutlet.yokan.database.sync.SyncIdentityMigration
import eu.friedcutlet.yokan.services.colorization.LocalColorizationQueue
import eu.friedcutlet.yokan.services.colorization.PanelColorizer
import eu.friedcutlet.yokan.services.download.ChapterDownloads
import eu.friedcutlet.yokan.services.extensions.ChapterPageResolver
import eu.friedcutlet.yokan.services.extensions.ProfileReaderContent
import eu.friedcutlet.yokan.services.extensions.SourceInstallService
import eu.friedcutlet.yokan.services.files.LocalArchiveService
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.files.createPlatformLocalArchiveService
import eu.friedcutlet.yokan.services.files.createPlatformLocalFileService
import eu.friedcutlet.yokan.services.http.DohResolver
import eu.friedcutlet.yokan.services.http.createPlatformHttpService
import eu.friedcutlet.yokan.services.library.LibraryUpdateController
import eu.friedcutlet.yokan.services.library.LocalLibraryController
import eu.friedcutlet.yokan.services.logging.LogSink
import eu.friedcutlet.yokan.services.media.AniSkipService
import eu.friedcutlet.yokan.services.media.player.MediaStreamProxy
import eu.friedcutlet.yokan.services.media.player.createPlatformMediaStreamProxy
import eu.friedcutlet.yokan.services.migration.MigrationService
import eu.friedcutlet.yokan.services.notifications.NotificationService
import eu.friedcutlet.yokan.services.notifications.ProfileNotificationService
import eu.friedcutlet.yokan.services.notifications.createPlatformNotificationService
import eu.friedcutlet.yokan.services.scheduling.BackgroundScheduler
import eu.friedcutlet.yokan.services.scheduling.ForegroundScheduler
import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskRunner
import eu.friedcutlet.yokan.services.scheduling.createPlatformBackgroundScheduler
import eu.friedcutlet.yokan.services.runJoined
import eu.friedcutlet.yokan.services.sync.SyncTriggerCoordinator
import eu.friedcutlet.yokan.ui.screens.browse.SourceHomeCache
import eu.friedcutlet.yokan.util.PlatformLock
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult

enum class ProfileSessionStatus { Open, Retiring, RetirementFailed, Closed }

/** Owns captured dependencies. Retirement is terminal; a failed retirement can be retried, not reactivated. */
internal class ProfileSession(
    val id: ProfileId,
    private val databaseFactory: (ProfileId) -> YokanDatabase = ::createProfileDatabase,
    private val filesFactory: (ProfileId) -> LocalFileService = ::createPlatformLocalFileService,
    private val archivesFactory: (ProfileId) -> LocalArchiveService = ::createPlatformLocalArchiveService,
    private val notificationsFactory: (ProfileId) -> NotificationService = ::createPlatformNotificationService,
    private val servicesFactory: (ProfileSession) -> YokanServices = { it.buildServices() },
    private val onScheduleChanged: (ProfileSession) -> Unit = {},
    dispatcher: CoroutineDispatcher = Dispatchers.Default,
    private val joinTimeoutMillis: Long = 15_000,
    private val storageLease: ProfileStorageLease = ProfileStorageLease {},
    private val syncLeases: eu.friedcutlet.yokan.services.sync.SyncAccountLeases = eu.friedcutlet.yokan.services.sync.SyncAccountLeases.None,
) {
    private val resourceLock = PlatformLock()
    private val retirementLock = Mutex()
    private val resources = mutableListOf<OwnedResource<*>>()
    private val _status = MutableStateFlow(ProfileSessionStatus.Open)
    val status = _status.asStateFlow()
    private val job = SupervisorJob()
    val scope = CoroutineScope(job + dispatcher)

    init {
        require(joinTimeoutMillis > 0)
        ownResource(factory = { storageLease }, close = { it.close() })
    }

    private val databaseResource = owned<YokanDatabase>(close = { it.close() }) {
        databaseFactory(id)
            .also(SyncIdentityMigration::ensure)
    }
    val database: YokanDatabase by databaseResource
    val localFiles: LocalFileService by owned(close = { it.close() }) { filesFactory(id) }
    val localArchive: LocalArchiveService by owned { archivesFactory(id) }
    val notifications: NotificationService by owned {
        ProfileNotificationService(
            id,
            notificationsFactory(id),
            // Notifications must never open storage: an unopened database has no privacy setting to honour yet.
            hideContent = { databaseResource.peek()?.settings()?.features?.privacy?.hideNotificationContent == true },
        ) { _status.value == ProfileSessionStatus.Open }
    }
    val backup: eu.friedcutlet.yokan.services.backup.BackupService by owned {
        eu.friedcutlet.yokan.services.backup.DefaultBackupService(database, localFiles, eu.friedcutlet.yokan.services.backup.createPlatformBackupCompression(), notifications)
    }
    val services: YokanServices by owned(close = { it.closeAndJoin() }) {
        servicesFactory(this)
    }
    val together by owned(close = { it.closeAndJoin() }) {
        eu.friedcutlet.yokan.services.together.ProfileTogetherSession(id, database, scope)
    }

    private fun buildServices(): YokanServices = defaultServices(
        database = database,
        files = localFiles,
        archives = localArchive,
        notifications = notifications,
        backup = backup,
        scope = scope,
        profileId = id,
        isOwnerOpen = { _status.value == ProfileSessionStatus.Open },
        syncLeases = syncLeases,
        resolveHost = dohResolver::resolve,
        // Called when a download starts, never while building services (chapterPages needs repository → services).
        resolveDownloadPages = { chapterId, forceRefresh ->
            val chapter = checkNotNull(database.chapter(chapterId)) { "The chapter is no longer in the library" }
            chapterPages.pages(chapter, chapter.mangaId?.let(database::manga)?.sourceId, forceRefresh)
        },
    )

    /** Runs in services.scope, so session retirement cancels pending triggered syncs. */
    val syncTriggers: SyncTriggerCoordinator by owned {
        SyncTriggerCoordinator(database, services.scope) { periodicTasks.sync() }
    }
    val repository: YokanRepository by owned {
        DefaultYokanRepository(database, services.downloadAutomation, services.trackerAccounts, syncTriggers::onTrigger)
    }
    val chapterPages: ChapterPageResolver by owned {
        ChapterPageResolver(repository, database, services.extensionRuntimeFactory)
    }
    val readerContent by owned(close = { it.closeAndJoin() }) {
        ProfileReaderContent(
            id, database, services.extensionRuntimeFactory, chapterPages, localFiles, localArchive, scope,
            isOwnerOpen = { _status.value == ProfileSessionStatus.Open },
            torrents = services.torrents,
        )
    }
    val automaticUpdateGate by owned { eu.friedcutlet.yokan.services.scheduling.AutomaticUpdateGate() }
    val periodicTasks: PeriodicTaskRunner by owned {
        PeriodicTaskRunner(
            database = database,
            repository = repository,
            metadata = services.metadata,
            libraryUpdater = services.libraryUpdater,
            sync = services.sync,
            backup = services.backup,
            notifications = notifications,
            updateGate = automaticUpdateGate,
        )
    }
    val foregroundScheduler: ForegroundScheduler by owned { ForegroundScheduler(database, periodicTasks, services.scope) }
    val backgroundScheduler: BackgroundScheduler by owned { createPlatformBackgroundScheduler(database, id) }
    /** Uses its own transport, so resolving the DoH provider itself goes through system DNS. */
    val dohResolver: DohResolver by owned { DohResolver(database, createPlatformHttpService(id, scope)) }
    /** Recently closed Source Homes, restored when the same source is reopened in this profile. */
    val sourceHomeCache by owned { SourceHomeCache(capacity = 5) }
    val aniSkip: AniSkipService by owned { AniSkipService(services.http) }
    val mediaStreamProxy: MediaStreamProxy by owned(close = { it.closeAndJoin() }) { createPlatformMediaStreamProxy() }
    val playerServices by owned(close = { it.closeAndJoin() }) {
        eu.friedcutlet.yokan.services.media.player.ProfilePlayerServices(
            id, localFiles, aniSkip, mediaStreamProxy, scope,
            isOwnerOpen = { _status.value == ProfileSessionStatus.Open },
        )
    }
    val cast by owned(close = { it.close() }) { eu.friedcutlet.yokan.services.media.cast.createCastController(scope) }
    val settings: SettingsStore by owned { SettingsStore(repository, scope) { onScheduleChanged(this) } }
    val libraryIndex: LibraryIndexStore by owned { LibraryIndexStore(repository, services.scope,
        trackerScoreRanges = services.trackers.associate { tracker -> tracker.scoreValue().let { tracker.syncId to (it.first..it.second) } }) }
    val libraryUpdates: LibraryUpdateController by owned {
        LibraryUpdateController(services.libraryUpdater, repository, notifications, services.scope)
    }
    val localLibrary: LocalLibraryController by owned {
        val capturedDatabase = database
        LocalLibraryController(
            localLibrary = services.localLibrary,
            entryManagement = services.localEntryManagement,
            repository = repository,
            metadata = services.metadata,
            trackers = services.trackers,
            files = localFiles,
            settings = settings,
            persistSettings = { capturedDatabase.awaitPersistence() },
            importScope = scope,
            isOwnerOpen = { _status.value == ProfileSessionStatus.Open },
            artwork = eu.friedcutlet.yokan.services.library.LocalVideoArtwork(
                capturedDatabase, localFiles, services.localLibrary,
                eu.friedcutlet.yokan.services.media.createPlatformVideoFrameExtractor(),
            ),
        )
    }
    val colorizationQueue: LocalColorizationQueue by owned {
        LocalColorizationQueue(database, localFiles, localArchive, PanelColorizer(), services.localLibrary, services.scope)
    }
    val migration: MigrationService by owned {
        MigrationService(repository, database, services.extensionRuntimeFactory, settings, services.scope)
    }
    val chapterDownloads: ChapterDownloads by owned {
        ChapterDownloads(
            repository = repository,
            database = database,
            downloader = services.downloader,
            notifications = notifications,
            settings = settings,
            localFiles = localFiles,
            scope = scope,
            externalDownloads = services.externalDownloads,
        )
    }
    val sourceInstall: SourceInstallService by owned {
        SourceInstallService(database, repository, services.sourceCatalog, services.extensionRuntimeFactory, settings, chapterPages)
    }

    private val loggingTarget by owned(close = { LogSink.detach(it) }) {
        val db = database
        LogSink.attach(localFiles) { db.snapshots().value.settings.enableFileLogging }
    }

    /** Only the active composition root may publish its log target. */
    fun attachLogging() { loggingTarget }

    /** OS callbacks are children of this owner; caller expiry and session retirement both join them. */
    suspend fun <T> runBackgroundWork(action: suspend (ProfileSession) -> T): ProfileWorkResult<T> {
        currentCoroutineContext().ensureActive()
        if (_status.value != ProfileSessionStatus.Open) return ProfileWorkResult.Skipped
        return ProfileWorkResult.Completed(scope.runJoined { action(this@ProfileSession) })
    }

    /** Call only after UI/reader progress owners have saved and stopped using this session. */
    suspend fun close() = retirementLock.withLock retirement@{
        val cleanup = resourceLock.withLock snapshot@{
            if (_status.value == ProfileSessionStatus.Closed) return@snapshot null
            _status.update { ProfileSessionStatus.Retiring }
            resources.asReversed().toList()
        } ?: return@retirement
        withContext(NonCancellable) {
            try {
                // No resource is released until cancelled child finalizers have finished their writes.
                withTimeout(joinTimeoutMillis) { job.cancelAndJoin() }
                cleanup.forEach { resource ->
                    withTimeout(joinTimeoutMillis) { resource.closeIfInitialized() }
                }
                _status.update { ProfileSessionStatus.Closed }
            } catch (error: Throwable) {
                _status.update { ProfileSessionStatus.RetirementFailed }
                throw error
            }
        }
    }

    private fun <T> owned(close: suspend (T) -> Unit = {}, factory: () -> T): OwnedResource<T> =
        OwnedResource(close, factory).also { resources += it }

    /** Register context-dependent resources atomically with retirement, after their captured dependencies. */
    fun <T> ownResource(factory: () -> T, close: suspend (T) -> Unit): T = resourceLock.withLock {
        check(_status.value == ProfileSessionStatus.Open) { "Profile session is retiring or closed" }
        val resource = OwnedResource(close, factory)
        resource.initialize().also { resources += resource }
    }

    private inner class OwnedResource<T>(private val close: suspend (T) -> Unit, factory: () -> T) : ReadOnlyProperty<ProfileSession, T> {
        private val value = lazy(factory)
        private var released = false
        fun initialize(): T = value.value
        fun peek(): T? = if (value.isInitialized()) value.value else null
        override fun getValue(thisRef: ProfileSession, property: KProperty<*>): T = resourceLock.withLock {
            check(_status.value == ProfileSessionStatus.Open) { "Profile session is retiring or closed" }
            value.value
        }
        suspend fun closeIfInitialized() {
            if (!released && value.isInitialized()) {
                close(value.value)
                released = true
            }
        }
    }
}

/** Additional profiles remain gated until platform credentials and background jobs are isolated. */
internal fun createPlatformProfileSession(
    id: ProfileId,
    syncLeases: eu.friedcutlet.yokan.services.sync.SyncAccountLeases,
    onScheduleChanged: (ProfileSession) -> Unit = {},
): ProfileSession {
    check(id == ProfileId.Default) { "Additional profile sessions are not enabled yet" }
    return ProfileSession(id, onScheduleChanged = onScheduleChanged, syncLeases = syncLeases)
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.kt) · implementation · 14 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
6: internal suspend fun deleteProfileStorage(id: ProfileId, exportedBackups: List<String> = emptyList()) {
14: internal expect suspend fun deletePlatformProfileStorage(id: ProfileId, exportedBackups: List<String>)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.kt) · SHA-256 `ef047166966bb4c789689f67ce74d256f5f678c5e391cdd678cca7b99daea8b4`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.domain.ProfileId

/** Call only under the coordinator's deletion lease, after all sessions/work for this ID retire. */
internal suspend fun deleteProfileStorage(id: ProfileId, exportedBackups: List<String> = emptyList()) {
    require(id != ProfileId.Default) { "Default storage cannot be deleted" }
    val lease = acquireProfileStorageLease(id)
    try { deletePlatformProfileStorage(id, exportedBackups) }
    finally { kotlinx.coroutines.withContext(kotlinx.coroutines.NonCancellable) { lease.close() } }
}

/** Uses app-owned roots, never settings paths or external-folder grants. */
internal expect suspend fun deletePlatformProfileStorage(id: ProfileId, exportedBackups: List<String>)
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.kt) · implementation · 32 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
7: internal fun interface ProfileStorageLease { suspend fun close() }
8: internal expect suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease
10: internal suspend fun openPlatformProfileSession(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.kt) · SHA-256 `ebe7361b8e96798f8f8d9ccc5f5e50af7356220ee4b7cff047f500e7f3b6957b`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import kotlinx.coroutines.ensureActive
import eu.friedcutlet.yokan.domain.ProfileId

/** Held until the owner's database and native writes have drained. Lock files live outside its data. */
internal fun interface ProfileStorageLease { suspend fun close() }
internal expect suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease

internal suspend fun openPlatformProfileSession(
    id: ProfileId,
    syncLeases: eu.friedcutlet.yokan.services.sync.SyncAccountLeases,
    onScheduleChanged: (ProfileSession) -> Unit = {},
): ProfileSession {
    kotlinx.coroutines.currentCoroutineContext().ensureActive()
    val lease = acquireProfileStorageLease(id)
    var session: ProfileSession? = null
    return try {
        kotlinx.coroutines.currentCoroutineContext().ensureActive()
        ProfileSession(id, storageLease = lease, onScheduleChanged = onScheduleChanged, syncLeases = syncLeases).also {
            session = it
            it.localFiles.prepare()
        }
    }
    catch (error: Throwable) {
        kotlinx.coroutines.withContext(kotlinx.coroutines.NonCancellable) {
            try { session?.close() ?: lease.close() }
            catch (closing: Throwable) { error.addSuppressed(closing) }
        }
        throw error
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileUiLifetime.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileUiLifetime.kt) · implementation · 32 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
11: internal class ProfileUiLifetime {
14: fun mount(session: ProfileSession): () -> Unit {
24: suspend fun detach(session: ProfileSession) = withTimeout(15_000) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileUiLifetime.kt) · SHA-256 `abfd3ce7777d306f5cb7009d0cfe959df037040a4bd55bb07e56834cbe5ce2f0`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.util.PlatformLock
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.yield

/** Composition disposal captures final progress before the navigator begins awaited retirement. */
internal class ProfileUiLifetime {
    private val lock = PlatformLock()
    private val mounts = mutableMapOf<ProfileSession, MutableSet<CompletableDeferred<Unit>>>()
    fun mount(session: ProfileSession): () -> Unit {
        val ticket = CompletableDeferred<Unit>()
        lock.withLock { mounts.getOrPut(session) { mutableSetOf() }.add(ticket) }
        return {
            lock.withLock {
                mounts[session]?.let { it.remove(ticket); if (it.isEmpty()) mounts.remove(session) }
                ticket.complete(Unit)
            }
        }
    }
    suspend fun detach(session: ProfileSession) = withTimeout(15_000) {
        val tickets = lock.withLock { mounts[session]?.toList().orEmpty() }
        withContext(Dispatchers.Main) {
            tickets.forEach { it.await() }
            // Resume after the synchronous apply/disposal pass, including child disposers.
            yield()
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.kt) · implementation · 6 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
6: internal expect suspend fun cancelProfileBackgroundWork(id: ProfileId)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.kt) · SHA-256 `5afc9d8515a7b6f8fc1d9614e7be5d3d5a13a6192f99dce76353cbd0739cfb71`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.domain.ProfileId

/** Removes only the selected owner's OS jobs and notifications, without opening its database. */
internal expect suspend fun cancelProfileBackgroundWork(id: ProfileId)
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/domain/ProfileId.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/domain/ProfileId.kt) · implementation · 23 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
9: value class ProfileId(val value: String) {
13: fun random(): ProfileId = ProfileId("p_" + Random.nextBytes(16).toHexString())
18: data class ProfileStorageNamespace(val id: ProfileId) {
22: fun ownedRoot(base: String): String = relativeRoot?.let { "${base.trimEnd('/')}/$it" } ?: base.trimEnd('/')
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/domain/ProfileId.kt) · SHA-256 `c433dfefdeb6235d458f6afa6e9f61abcdaea11f2e88deb606e81d18aa16f7d5`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.domain

import kotlinx.serialization.Serializable
import kotlin.jvm.JvmInline
import kotlin.random.Random

@Serializable
@JvmInline
value class ProfileId(val value: String) {
    init { require(value == "default" || Regex("p_[0-9a-f]{32}").matches(value)) { "Invalid profile ID" } }
    companion object {
        val Default = ProfileId("default")
        fun random(): ProfileId = ProfileId("p_" + Random.nextBytes(16).toHexString())
    }
}

/** Only stable IDs enter paths/keys. Default aliases legacy locations; no adoption copy is needed. */
data class ProfileStorageNamespace(val id: ProfileId) {
    val relativeRoot: String? get() = if (id == ProfileId.Default) null else "profiles/${id.value}"
    val databaseRelativePath: String get() = relativeRoot?.let { "$it/yokan-room.db" } ?: "yokan-room.db"
    val browserSnapshotKey: String get() = if (id == ProfileId.Default) "yokan-database-v1" else "yokan-database-v1:${id.value}"
    fun ownedRoot(base: String): String = relativeRoot?.let { "${base.trimEnd('/')}/$it" } ?: base.trimEnd('/')
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfileBackupScreen.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfileBackupScreen.kt) · implementation · 77 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
16: internal data class ProfileBackupControls(
32: internal fun ProfileBackupScreen(export: Boolean, onBack: () -> Unit) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfileBackupScreen.kt) · SHA-256 `a8b605c8f399df3d4344413111a49872c043e55f5bc605a28064a3df072d885d`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.settings.profiles

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.backup.*
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*

internal data class ProfileBackupControls(
    val state: ProfileBackupsState,
    val select: (ProfileId) -> Unit,
    val password: (String) -> Unit,
    val format: (BackupFormat) -> Unit,
    val mode: (RestoreMode) -> Unit,
    val export: () -> Unit,
    val chooseFile: () -> Unit,
    val unlock: () -> Unit,
    val apply: () -> Unit,
    val snapshots: () -> Unit,
    val rollback: (ProfileId, SafetySnapshot) -> Unit,
)
internal val LocalProfileBackupControls = staticCompositionLocalOf<ProfileBackupControls> { error("Backup controls unavailable") }

@Composable
internal fun ProfileBackupScreen(export: Boolean, onBack: () -> Unit) {
    val controls = LocalProfileBackupControls.current
    val state = controls.state
    val targetName = state.profiles.firstOrNull { it.id == state.target }?.name.orEmpty()
    SettingsScaffold(stringResource(if (export) Res.string.profiles_backup_export else Res.string.profiles_backup_restore), onBack) {
        if (state.profiles.size > 1) item(key = "backup-profile-selector") {
            Column(Modifier.padding(16.dp)) {
                Text(stringResource(if (export) Res.string.profiles_backup_source else Res.string.profiles_backup_target), style = MaterialTheme.typography.titleMedium)
                state.profiles.forEach { profile -> key(profile.id.value) {
                    Row { RadioButton(profile.id == state.target, onClick = { controls.select(profile.id) }, enabled = !state.busy); TextButton(onClick = { controls.select(profile.id) }, enabled = !state.busy) { Text(profile.name) } }
                } }
            }
        }
        item(key = "backup-guidance") { Text(stringResource(Res.string.profiles_backup_guidance), modifier = Modifier.padding(16.dp)) }
        item(key = "backup-password") { OutlinedTextField(state.password, controls.password, label = { Text(stringResource(Res.string.profiles_backup_password)) }, visualTransformation = PasswordVisualTransformation(), singleLine = true, enabled = !state.busy, modifier = Modifier.fillMaxWidth().padding(16.dp)) }
        if (export) {
            item(key = "backup-formats") { Row(Modifier.padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                BackupFormat.entries.forEach { format -> FilterChip(state.format == format, onClick = { controls.format(format) }, label = { Text(format.name) }, enabled = !state.busy && (format == BackupFormat.Yokan || state.password.isEmpty())) }
            } }
            item(key = "backup-export") { Button(onClick = controls.export, enabled = state.available && !state.busy && (state.format == BackupFormat.Yokan || state.password.isEmpty()), modifier = Modifier.padding(16.dp)) { Text(stringResource(Res.string.profiles_backup_export_named, targetName)) } }
        } else {
            item(key = "backup-open") { Row(Modifier.padding(16.dp)) {
                TextButton(onClick = controls.chooseFile, enabled = state.available && !state.busy) { Text(stringResource(Res.string.profiles_backup_choose)) }
                TextButton(onClick = controls.unlock, enabled = state.available && !state.busy && state.password.isNotEmpty()) { Text(stringResource(Res.string.profiles_backup_unlock)) }
            } }
            state.plan?.let { target ->
                item(key = "backup-preview") { Column(Modifier.padding(16.dp)) {
                    Text(stringResource(Res.string.profiles_backup_preview, targetName, target.plan.preview.itemCount), style = MaterialTheme.typography.titleMedium)
                    target.plan.preview.warnings.forEach { Text(it, style = MaterialTheme.typography.bodySmall) }
                    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { RestoreMode.entries.forEach { mode -> FilterChip(state.mode == mode, onClick = { controls.mode(mode) }, label = { Text(mode.name) }, enabled = !state.busy) } }
                    Button(onClick = controls.apply, enabled = state.available && !state.busy) { Text(stringResource(Res.string.profiles_backup_apply)) }
                } }
            }
            item(key = "backup-snapshots-refresh") { TextButton(onClick = controls.snapshots, enabled = state.available && !state.busy) { Text(stringResource(Res.string.profiles_backup_snapshots)) } }
            items(state.snapshots, key = { it.backupPath }, contentType = { "snapshot" }) { snapshot ->
                Column(Modifier.padding(16.dp)) {
                    Text(snapshot.description)
                    TextButton(onClick = { controls.rollback(state.target, snapshot) }, enabled = !state.busy) { Text(stringResource(Res.string.profiles_backup_rollback)) }
                }
            }
        }
        state.error?.let { error -> item(key = "backup-error") { Text(error, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp)) } }
        state.message?.let { message -> item(key = "backup-result") { Text(message, modifier = Modifier.padding(16.dp)) } }
        if (state.busy) item(key = "backup-busy") { LinearProgressIndicator(Modifier.fillMaxWidth()) }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfileBackupsViewModel.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfileBackupsViewModel.kt) · implementation · 128 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.

Declaration checklist (source line numbers):
```text
22: internal data class ProfileBackupsState(
37: internal class ProfileBackupsViewModel(
59: fun select(id: ProfileId) {
65: fun password(value: String) = _state.update { it.copy(password = value, error = null) }
66: fun format(value: BackupFormat) = _state.update { it.copy(format = value) }
67: fun mode(value: RestoreMode) = _state.update { it.copy(mode = value) }
68: fun refreshSnapshots(id: ProfileId = _state.value.target) = command {
72: fun export() {
79: fun chooseFile() {
87: fun unlock() {
91: private suspend fun open(id: ProfileId, password: String?) {
101: fun apply() {
112: fun rollback(id: ProfileId, snapshot: SafetySnapshot) = command {
118: private fun command(action: suspend () -> Unit) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfileBackupsViewModel.kt) · SHA-256 `530563b394b965c9a5eb20a5749f4fbddbc3d5bcdc2229c03dab881d8c2c3cc4`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.settings.profiles

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.app.profiles.*
import eu.friedcutlet.yokan.services.backup.*
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.files.pickFile
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.compose.resources.getString
import yokan.composeapp.generated.resources.*
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.app.profiles.ProfileBackupOperations
import eu.friedcutlet.yokan.app.profiles.TargetedBackupPlan

internal data class ProfileBackupsState(
    val profiles: List<ProfileRecord> = emptyList(),
    val target: ProfileId = ProfileId.Default,
    val available: Boolean = false,
    val busy: Boolean = false,
    val password: String = "",
    val format: BackupFormat = BackupFormat.Yokan,
    val mode: RestoreMode = RestoreMode.Merge,
    val plan: TargetedBackupPlan? = null,
    val snapshots: List<SafetySnapshot> = emptyList(),
    val message: String? = null,
    val error: String? = null,
)

/** Lives in the device store, so an active-target restore survives navigator retirement. */
internal class ProfileBackupsViewModel(
    private val registry: ProfileRegistry,
    private val operations: ProfileBackupOperations,
    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
    private val _state = MutableStateFlow(ProfileBackupsState())
    val state = _state.asStateFlow()
    private var input: ByteArray? = null
    init {
        viewModelScope.launch {
            registry.state.collect { value ->
                val snapshot = (value as? ProfileRegistryState.Ready)?.snapshot
                _state.update { current ->
                    val records = snapshot?.profiles?.filter { it.status == ProfileStatus.Ready }.orEmpty()
                    val target = if (records.any { it.id == current.target }) current.target else ProfileId.Default
                    if (target != current.target) input = null
                    current.copy(profiles = records, available = snapshot != null, target = target,
                        plan = current.plan.takeIf { target == current.target }, snapshots = current.snapshots.takeIf { target == current.target }.orEmpty())
                }
            }
        }
    }
    fun select(id: ProfileId) {
        if (_state.value.busy || _state.value.profiles.none { it.id == id }) return
        input = null
        _state.update { it.copy(target = id, plan = null, snapshots = emptyList(), password = "", message = null, error = null) }
        refreshSnapshots(id)
    }
    fun password(value: String) = _state.update { it.copy(password = value, error = null) }
    fun format(value: BackupFormat) = _state.update { it.copy(format = value) }
    fun mode(value: RestoreMode) = _state.update { it.copy(mode = value) }
    fun refreshSnapshots(id: ProfileId = _state.value.target) = command {
        val snapshots = operations.snapshots(id)
        _state.update { if (it.target == id) it.copy(snapshots = snapshots) else it }
    }
    fun export() {
        val selected = _state.value
        command {
            val result = operations.export(selected.target, BackupOptions(format = selected.format), selected.password.takeIf { it.isNotEmpty() })
            _state.update { it.copy(message = result?.let { result -> result.path }, password = "") }
        }
    }
    fun chooseFile() {
        val id = _state.value.target
        command {
            val path = pickFile(listOf("tachibk", "proto", "json", "gz", "backup", "yokanbak")) ?: return@command
            input = operations.read(id, path)
            open(id, _state.value.password.takeIf { it.isNotEmpty() })
        }
    }
    fun unlock() {
        val selected = _state.value
        command { open(selected.target, selected.password.takeIf { it.isNotEmpty() }) }
    }
    private suspend fun open(id: ProfileId, password: String?) {
        val bytes = input ?: return
        when (val opened = operations.open(id, bytes, password)) {
            is BackupOpenResult.Ready -> _state.update { if (it.target == id) it.copy(plan = TargetedBackupPlan(id, opened.plan), password = "", error = null) else it }
            is BackupOpenResult.Failure -> {
                val message = getString(Res.string.profiles_backup_open_failed)
                _state.update { it.copy(plan = null, error = message) }
            }
        }
    }
    fun apply() {
        val selected = _state.value
        val plan = selected.plan ?: return
        command {
            val result = operations.apply(plan, selected.mode)
            input = null
            val snapshots = operations.snapshots(plan.target)
            val message = getString(Res.string.profiles_backup_restored, result.itemCount)
            _state.update { it.copy(plan = null, password = "", snapshots = snapshots, message = message) }
        }
    }
    fun rollback(id: ProfileId, snapshot: SafetySnapshot) = command {
        operations.rollback(id, snapshot)
        val snapshots = operations.snapshots(id)
        val message = getString(Res.string.profiles_backup_rolled_back)
        _state.update { if (it.target == id) it.copy(snapshots = snapshots, message = message) else it }
    }
    private fun command(action: suspend () -> Unit) {
        if (_state.value.busy) return
        _state.update { it.copy(busy = true, error = null, message = null) }
        viewModelScope.launch {
            try {
                catchingNonCancellation { withContext(workDispatcher) { action() } }
                    .onFailure { error -> _state.update { it.copy(error = error.message ?: "Backup operation failed") } }
            } finally { _state.update { it.copy(busy = false) } }
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfilesScreen.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfilesScreen.kt) · implementation · 95 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
15: internal data class ProfileControls(
30: internal fun ProfilesScreen(onBack: () -> Unit) {
80: internal fun ProfileQuickSwitch() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfilesScreen.kt) · SHA-256 `000bd8f225df186269b04eec300ed253711456759991aa7074d1264144d41cd9`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.settings.profiles

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.app.profiles.*
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
import eu.friedcutlet.yokan.domain.ProfileId

internal data class ProfileControls(
    val state: ProfilesState,
    val switchTo: (ProfileId) -> Unit,
    val create: () -> Unit,
    val rename: (ProfileRecord) -> Unit,
    val delete: (ProfileRecord) -> Unit,
    val retry: (ProfileId) -> Unit,
    val refresh: () -> Unit,
    val nameChanged: (String) -> Unit,
    val confirm: () -> Unit,
    val dismiss: () -> Unit,
)
internal val LocalProfileControls = staticCompositionLocalOf<ProfileControls> { error("Profile controls unavailable") }

@Composable
internal fun ProfilesScreen(onBack: () -> Unit) {
    val controls = LocalProfileControls.current
    val state = controls.state
    SettingsScaffold(stringResource(Res.string.profiles_title), onBack) {
        item(key = "profile-guidance") { Text(stringResource(Res.string.profiles_guidance), modifier = Modifier.padding(16.dp)) }
        item(key = "profile-capabilities") { Text(stringResource(Res.string.profiles_capabilities), style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(16.dp)) }
        state.error?.let { error -> item(key = "profile-error") { Text(error, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp)) } }
        if (!state.available) item(key = "profile-refresh") {
            TextButton(onClick = controls.refresh, enabled = !state.busy) { Text(stringResource(Res.string.profiles_retry)) }
        }
        items(state.registry.profiles, key = { it.id.value }, contentType = { "profile" }) { record ->
            Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp)) {
                Text(record.name, style = MaterialTheme.typography.titleMedium)
                if (record.id == state.activeId) Text(stringResource(Res.string.profiles_active), color = MaterialTheme.colorScheme.primary)
                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                    when (record.status) {
                        ProfileStatus.Ready -> {
                            if (record.id != state.activeId) TextButton(onClick = { controls.switchTo(record.id) }, enabled = state.available && !state.busy) { Text(stringResource(Res.string.profiles_switch)) }
                            if (record.id != ProfileId.Default) TextButton(onClick = { controls.rename(record) }, enabled = !state.busy) { Text(stringResource(Res.string.profiles_rename)) }
                        }
                        ProfileStatus.Provisioning -> TextButton(onClick = { controls.retry(record.id) }, enabled = !state.busy) { Text(stringResource(Res.string.profiles_retry)) }
                        ProfileStatus.Deleting -> Text(stringResource(Res.string.profiles_deletion_pending))
                    }
                    if (record.id != ProfileId.Default) TextButton(onClick = { controls.delete(record) }, enabled = !state.busy) { Text(stringResource(Res.string.profiles_delete)) }
                }
            }
        }
        item(key = "profile-create") { Button(onClick = controls.create, enabled = state.available && !state.busy, modifier = Modifier.padding(16.dp)) { Text(stringResource(Res.string.profiles_create)) } }
        if (state.busy) item(key = "profile-busy") { LinearProgressIndicator(Modifier.fillMaxWidth()) }
    }
    when (val dialog = state.dialog) {
        is ProfileDialog.Name -> AlertDialog(
            onDismissRequest = { if (!state.busy) controls.dismiss() },
            title = { Text(stringResource(if (dialog.id == null) Res.string.profiles_create else Res.string.profiles_rename)) },
            text = { Column { OutlinedTextField(dialog.draft, controls.nameChanged, label = { Text(stringResource(Res.string.profiles_name)) }, singleLine = true, enabled = !state.busy); state.error?.let { Text(it, color = MaterialTheme.colorScheme.error) } } },
            confirmButton = { TextButton(onClick = controls.confirm, enabled = !state.busy && dialog.draft.isNotBlank()) { Text(stringResource(Res.string.action_save)) } },
            dismissButton = { TextButton(onClick = controls.dismiss, enabled = !state.busy) { Text(stringResource(Res.string.action_cancel)) } },
        )
        is ProfileDialog.Delete -> AlertDialog(
            onDismissRequest = { if (!state.busy) controls.dismiss() },
            title = { Text(stringResource(Res.string.profiles_delete_named, dialog.profile.name)) },
            text = { Column { Text(stringResource(Res.string.profiles_delete_guidance)); state.error?.let { Text(it, color = MaterialTheme.colorScheme.error) } } },
            confirmButton = { TextButton(onClick = controls.confirm, enabled = !state.busy) { Text(stringResource(Res.string.profiles_delete)) } },
            dismissButton = { TextButton(onClick = controls.dismiss, enabled = !state.busy) { Text(stringResource(Res.string.action_cancel)) } },
        )
        null -> Unit
    }
}

@Composable
internal fun ProfileQuickSwitch() {
    val controls = LocalProfileControls.current
    val state = controls.state
    if (!state.registry.hasAdditionalProfiles) return
    var expanded by remember { mutableStateOf(false) }
    Box(Modifier.padding(horizontal = 16.dp)) {
        TextButton(onClick = { expanded = true }, enabled = state.available && !state.busy) {
            Text(stringResource(Res.string.profiles_current, state.registry.available(state.activeId)?.name.orEmpty()))
        }
        DropdownMenu(expanded, { expanded = false }) {
            state.registry.profiles.filter { it.status == ProfileStatus.Ready }.forEach { record ->
                key(record.id.value) { DropdownMenuItem(text = { Text(record.name) }, onClick = { expanded = false; controls.switchTo(record.id) }) }
            }
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfilesViewModel.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfilesViewModel.kt) · implementation · 95 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.

Declaration checklist (source line numbers):
```text
16: internal sealed interface ProfileDialog {
17: data class Name(val id: ProfileId? = null, val draft: String = "") : ProfileDialog
18: data class Delete(val profile: ProfileRecord) : ProfileDialog
20: internal data class ProfilesState(
30: internal class ProfilesViewModel(
55: fun resumeLastProfile() {
63: fun refresh() = command { registry.refresh() }
64: fun switchTo(id: ProfileId) = command { coordinator.switchTo(id) }
65: fun recover() = command { coordinator.recover() }
66: fun retryProvisioning(id: ProfileId) = command { coordinator.resumeProvisioning(id) }
67: fun showCreate() = _state.update { it.copy(dialog = ProfileDialog.Name(), error = null) }
68: fun showRename(record: ProfileRecord) = _state.update { it.copy(dialog = ProfileDialog.Name(record.id, record.name), error = null) }
69: fun showDelete(record: ProfileRecord) = _state.update { it.copy(dialog = ProfileDialog.Delete(record), error = null) }
70: fun dismissDialog() = _state.update { it.copy(dialog = null) }
71: fun changeName(draft: String) = _state.update {
75: fun confirm() {
85: private fun command(action: suspend () -> Unit) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfilesViewModel.kt) · SHA-256 `04dcdab6f438174f93a606933815b38d3a70e7398e621fe680fc98721f39e5b6`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.settings.profiles

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.app.profiles.*
import eu.friedcutlet.yokan.services.catchingNonCancellation
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.domain.ProfileId

internal sealed interface ProfileDialog {
    data class Name(val id: ProfileId? = null, val draft: String = "") : ProfileDialog
    data class Delete(val profile: ProfileRecord) : ProfileDialog
}
internal data class ProfilesState(
    val registry: ProfileRegistrySnapshot = ProfileRegistrySnapshot(),
    val activeId: ProfileId = ProfileId.Default,
    val available: Boolean = false,
    val busy: Boolean = false,
    val error: String? = null,
    val dialog: ProfileDialog? = null,
)

/** Device-owned: activation must never run in a navigator ViewModel that it is about to retire. */
internal class ProfilesViewModel(
    private val registry: ProfileRegistry,
    private val coordinator: ProfileCoordinator,
    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
    private val _state = MutableStateFlow(ProfilesState(activeId = coordinator.currentSession.id))
    val state = _state.asStateFlow()
    private var resumed = false
    init {
        viewModelScope.launch {
            registry.state.collect { update -> _state.update {
                when (update) {
                    is ProfileRegistryState.Ready -> it.copy(registry = update.snapshot, available = true)
                    else -> it.copy(available = false)
                }
            } }
        }
        viewModelScope.launch {
            coordinator.state.collect { update ->
                if (update is ProfileActivationState.Ready) _state.update {
                    it.copy(activeId = update.session.id, error = update.recoveryMessage ?: it.error)
                }
            }
        }
    }
    fun resumeLastProfile() {
        if (resumed) return
        resumed = true
        command {
            val snapshot = registry.refresh()
            if (snapshot.lastActive != coordinator.currentSession.id) coordinator.switchTo(snapshot.lastActive)
        }
    }
    fun refresh() = command { registry.refresh() }
    fun switchTo(id: ProfileId) = command { coordinator.switchTo(id) }
    fun recover() = command { coordinator.recover() }
    fun retryProvisioning(id: ProfileId) = command { coordinator.resumeProvisioning(id) }
    fun showCreate() = _state.update { it.copy(dialog = ProfileDialog.Name(), error = null) }
    fun showRename(record: ProfileRecord) = _state.update { it.copy(dialog = ProfileDialog.Name(record.id, record.name), error = null) }
    fun showDelete(record: ProfileRecord) = _state.update { it.copy(dialog = ProfileDialog.Delete(record), error = null) }
    fun dismissDialog() = _state.update { it.copy(dialog = null) }
    fun changeName(draft: String) = _state.update {
        val dialog = it.dialog as? ProfileDialog.Name ?: return@update it
        it.copy(dialog = dialog.copy(draft = draft.take(80)))
    }
    fun confirm() {
        when (val dialog = _state.value.dialog) {
            is ProfileDialog.Name -> command {
                if (dialog.id == null) coordinator.create(dialog.draft) else coordinator.rename(dialog.id, dialog.draft)
                dismissDialog()
            }
            is ProfileDialog.Delete -> command { coordinator.delete(dialog.profile.id); dismissDialog() }
            null -> Unit
        }
    }
    private fun command(action: suspend () -> Unit) {
        if (_state.value.busy) return
        _state.update { it.copy(busy = true, error = null) }
        viewModelScope.launch {
            try {
                catchingNonCancellation { withContext(workDispatcher) { action() } }
                    .onFailure { error -> _state.update { it.copy(error = error.message ?: "Profile operation failed") } }
            } finally { _state.update { it.copy(busy = false) } }
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileBackgroundWorkTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileBackgroundWorkTest.kt) · test / fixture · 235 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
33: class ProfileBackgroundWorkTest {
71: suspend fun rejected() = assertEquals(ProfileWorkResult.Skipped, routing.run(A.value) { error("Must not execute") })
114: override suspend fun read(): String? = throw IllegalStateException("Disk unavailable")
115: override suspend fun compareAndSet(expected: String?, replacement: String) = error("Must not write")
123: override suspend fun read(): String? = throw CancellationException("Expired worker")
124: override suspend fun compareAndSet(expected: String?, replacement: String) = error("Must not write")
205: private fun openingWork(
210: override suspend fun <T> run(id: ProfileId, action: suspend (ProfileSession) -> T): ProfileWorkResult<T> {
217: private class MemoryStore(var raw: String? = null) : ProfileRegistryPersistence {
218: override suspend fun read() = raw
219: override suspend fun compareAndSet(expected: String?, replacement: String): Boolean {
225: private class ClosingDatabase(private val delegate: InMemoryYokanDatabase = InMemoryYokanDatabase()) : YokanDatabase by delegate {
228: override suspend fun close() { noteAtClose = delegate.manga(42)?.privateNote; closed = true }
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileBackgroundWorkTest.kt) · SHA-256 `33ca5309031cd5f2a8b12126b547ce5c137f13b731e7e9f9e887a2d8b8780a95`.

### Complete file

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)

package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskOutcome
import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskStatus
import eu.friedcutlet.yokan.services.scheduling.shouldRetry
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.cancel
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkNamespace

class ProfileBackgroundWorkTest {
    @Test fun alreadyExpiredCallerCannotDispatchIntoALiveSession() = runTest {
        val owner = ProfileSession(A, dispatcher = UnconfinedTestDispatcher(testScheduler))
        var effects = 0
        val caller = launch {
            currentCoroutineContext().cancel()
            assertFailsWith<CancellationException> { owner.runBackgroundWork { effects++ } }
        }
        caller.join()
        assertEquals(0, effects); assertEquals(ProfileSessionStatus.Open, owner.status.value)
        assertEquals(ProfileWorkResult.Completed("Still usable"), owner.runBackgroundWork { "Still usable" })
        owner.close()
    }

    @Test fun delayedWorkUsesRecordedOwnerAfterRenameAndActiveProfileChange() = runTest {
        val registry = ProfileRegistry(MemoryStore())
        registry.beginCreate("A", A); registry.markReady(A)
        registry.beginCreate("B", B); registry.markReady(B)
        registry.rename(A, "Renamed A"); registry.recordActive(B)
        val a = InMemoryYokanDatabase(); val b = InMemoryYokanDatabase()
        val owners = mapOf(
            A to ProfileSession(A, databaseFactory = { a }, dispatcher = StandardTestDispatcher(testScheduler)),
            B to ProfileSession(B, databaseFactory = { b }, dispatcher = StandardTestDispatcher(testScheduler)),
        )
        val routing = openingWork(registry, { true }) { owners.getValue(it) }
        assertEquals(ProfileWorkResult.Completed(A), routing.run(A.value) {
            it.database.upsertManga(DbManga(id = 42, privateNote = "A's progress")); it.id
        })
        assertEquals("A's progress", a.manga(42)?.privateNote)
        assertEquals(null, b.manga(42))
        assertEquals(B, registry.refresh().lastActive)
        owners.values.forEach { it.close() }
    }

    @Test fun freshRegistryRejectsUnknownProvisioningDeletingAndRetiredWithoutOpeningStorage() = runTest {
        val store = MemoryStore(); val registry = ProfileRegistry(store)
        var opens = 0
        val routing = openingWork(registry, { true }) { opens++; error("Must not open") }
        suspend fun rejected() = assertEquals(ProfileWorkResult.Skipped, routing.run(A.value) { error("Must not execute") })
        rejected()
        registry.beginCreate("A", A); rejected()
        registry.markReady(A)
        // Mutate through another instance: admission must refresh rather than trust its cached Ready state.
        val other = ProfileRegistry(store)
        other.beginDelete(A); rejected()
        other.finishDelete(A); rejected()
        assertEquals(0, opens)
        assertEquals(listOf(A), registry.refresh().retiredIds)
    }

    @Test fun malformedExplicitIdsNeverBecomeDefaultAndLegacyAdoptionIsOptIn() = runTest {
        val registry = ProfileRegistry(MemoryStore())
        val owner = ProfileSession(ProfileId.Default, dispatcher = StandardTestDispatcher(testScheduler))
        var opens = 0
        val routing = openingWork(registry, { true }) { opens++; assertEquals(ProfileId.Default, it); owner }
        for (raw in listOf("", "../default", "DEFAULT", "p_123", "default ")) {
            assertEquals(ProfileWorkResult.Skipped, routing.run(raw, allowLegacyDefault = true) { error("Invalid owner") })
        }
        assertEquals(ProfileWorkResult.Skipped, routing.run(null) { error("No recorded owner") })
        assertEquals(0, opens)
        assertEquals(ProfileWorkResult.Completed(ProfileId.Default), routing.run(null, allowLegacyDefault = true) { it.id })
        assertEquals(ProfileWorkResult.Completed(ProfileId.Default), routing.run("default") { it.id })
        assertEquals(2, opens)
        owner.close()
    }

    @Test fun unsupportedReadyOwnerIsSkippedWithoutFallingBackToDefault() = runTest {
        val registry = ProfileRegistry(MemoryStore())
        registry.beginCreate("A", A); registry.markReady(A)
        val routing = openingWork(registry, { it == ProfileId.Default }) { error("Unsupported owner opened") }
        assertEquals(ProfileWorkResult.Skipped, routing.run(A.value) { error("Unsupported owner executed") })
    }

    @Test fun unavailableRegistryRetriesWithoutOpeningOrOverwritingMetadata() = runTest {
        for (raw in listOf("{broken", "{\"version\":999}")) {
            val store = MemoryStore(raw)
            val routing = openingWork(ProfileRegistry(store), { true }) { error("Unreadable metadata opened storage") }
            assertEquals(ProfileWorkResult.Retry, routing.run("default") { error("Must not execute") })
            assertEquals(raw, store.raw)
        }
        val store = object : ProfileRegistryPersistence {
            override suspend fun read(): String? = throw IllegalStateException("Disk unavailable")
            override suspend fun compareAndSet(expected: String?, replacement: String) = error("Must not write")
        }
        val routing = openingWork(ProfileRegistry(store), { true }) { error("Must not open") }
        assertEquals(ProfileWorkResult.Retry, routing.run("default") { error("Must not execute") })
    }

    @Test fun cancellationDuringAdmissionPropagatesRatherThanRetrying() = runTest {
        val store = object : ProfileRegistryPersistence {
            override suspend fun read(): String? = throw CancellationException("Expired worker")
            override suspend fun compareAndSet(expected: String?, replacement: String) = error("Must not write")
        }
        val routing = openingWork(ProfileRegistry(store), { true }) { error("Must not open") }
        assertFailsWith<CancellationException> { routing.run("default") { error("Must not execute") } }
    }

    @Test fun providerCannotRouteWorkToAnotherProfile() = runTest {
        val registry = ProfileRegistry(MemoryStore())
        registry.beginCreate("A", A); registry.markReady(A)
        val wrong = ProfileSession(ProfileId.Default, dispatcher = StandardTestDispatcher(testScheduler))
        val routing = openingWork(registry, { true }) { wrong }
        assertFailsWith<IllegalStateException> { routing.run(A.value) { error("Wrong profile executed") } }
        wrong.close()
    }

    @Test fun callerExpiryCancelsAndJoinsItsWorkWhileSiblingSessionWorkSurvives() = runTest {
        val owner = ProfileSession(A, dispatcher = StandardTestDispatcher(testScheduler))
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        var finalized = false
        val sibling = owner.scope.launch { awaitCancellation() }
        val caller = launch {
            owner.runBackgroundWork {
                try { entered.complete(Unit); awaitCancellation() }
                finally { withContext(NonCancellable) { release.await(); finalized = true } }
            }
        }
        entered.await(); caller.cancel(); testScheduler.runCurrent()
        assertFalse(caller.isCompleted); assertFalse(finalized); assertTrue(sibling.isActive)
        release.complete(Unit); caller.join()
        assertTrue(finalized); assertTrue(sibling.isActive)
        assertEquals(ProfileWorkResult.Completed("Next job"), owner.runBackgroundWork { "Next job" })
        owner.close()
    }

    @Test fun retirementJoinsBackgroundFinalProgressBeforeDatabaseCloseAndRejectsLateWork() = runTest {
        val db = ClosingDatabase()
        val owner = ProfileSession(A, databaseFactory = { db }, dispatcher = StandardTestDispatcher(testScheduler))
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        val caller = async {
            owner.runBackgroundWork {
                val captured = it.database
                try { entered.complete(Unit); awaitCancellation() }
                finally { withContext(NonCancellable) { release.await(); captured.upsertManga(DbManga(id = 42, privateNote = "Final")) } }
            }
        }
        entered.await()
        val closing = launch { owner.close() }; testScheduler.runCurrent()
        assertFalse(db.closed); assertFalse(closing.isCompleted)
        assertEquals(ProfileWorkResult.Skipped, owner.runBackgroundWork { error("Late work") })
        release.complete(Unit); closing.join()
        assertFailsWith<CancellationException> { caller.await() }
        assertTrue(db.closed); assertEquals("Final", db.noteAtClose)
        assertEquals(ProfileWorkResult.Skipped, owner.runBackgroundWork { error("Closed work") })
    }

    @Test fun workFailureDoesNotRetireOwnerOrCancelSiblingJobs() = runTest {
        val owner = ProfileSession(A, dispatcher = StandardTestDispatcher(testScheduler))
        val sibling = owner.scope.launch { awaitCancellation() }
        assertFailsWith<IllegalStateException> { owner.runBackgroundWork { error("Task failed") } }
        assertTrue(sibling.isActive)
        assertEquals(ProfileSessionStatus.Open, owner.status.value)
        assertEquals(ProfileWorkResult.Completed(42), owner.runBackgroundWork { 42 })
        sibling.cancelAndJoin(); owner.close()
    }

    @Test fun workNamesPreserveDefaultAndPartitionScheduleCancellationByStableId() {
        for (name in listOf("yokan.metadata_refresh", "yokan.library_update", "yokan.auto_sync", "yokan.auto_backup")) {
            val names = listOf(ProfileId.Default, A, B).map { ProfileWorkNamespace(it).uniqueName(name) }
            assertEquals(name, names.first()); assertEquals(3, names.distinct().size)
            assertEquals("$name.${A.value}", names[1])
        }
    }

    @Test fun onlyRecoverableAdmissionAndTaskFailuresRetry() {
        assertFalse((ProfileWorkResult.Skipped as ProfileWorkResult<PeriodicTaskOutcome>).shouldRetry)
        assertTrue((ProfileWorkResult.Retry as ProfileWorkResult<PeriodicTaskOutcome>).shouldRetry)
        assertFalse(ProfileWorkResult.Completed(PeriodicTaskOutcome(PeriodicTaskStatus.Completed, "Done")).shouldRetry)
        assertTrue(ProfileWorkResult.Completed(PeriodicTaskOutcome(PeriodicTaskStatus.Failed, "Retry")).shouldRetry)
    }

    /** Routes work into whatever session [openSession] returns, checking it is the requested owner. */
    private fun openingWork(
        registry: ProfileRegistry,
        supported: (ProfileId) -> Boolean,
        openSession: suspend (ProfileId) -> ProfileSession,
    ) = ProfileBackgroundWork(registry, supported, object : ProfileWorkSessions {
        override suspend fun <T> run(id: ProfileId, action: suspend (ProfileSession) -> T): ProfileWorkResult<T> {
            val session = openSession(id)
            check(session.id == id) { "Background work opened a different profile" }
            return session.runBackgroundWork(action)
        }
    })

    private class MemoryStore(var raw: String? = null) : ProfileRegistryPersistence {
        override suspend fun read() = raw
        override suspend fun compareAndSet(expected: String?, replacement: String): Boolean {
            if (raw != expected) return false
            raw = replacement; return true
        }
    }

    private class ClosingDatabase(private val delegate: InMemoryYokanDatabase = InMemoryYokanDatabase()) : YokanDatabase by delegate {
        var closed = false
        var noteAtClose: String? = null
        override suspend fun close() { noteAtClose = delegate.manga(42)?.privateNote; closed = true }
    }

    private companion object {
        val A = ProfileId("p_" + "a".repeat(32))
        val B = ProfileId("p_" + "b".repeat(32))
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileCoordinatorTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileCoordinatorTest.kt) · test / fixture · 257 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
17: class ProfileCoordinatorTest {
223: private class Fixture(private val dispatcher: CoroutineDispatcher) {
226: override suspend fun read() = raw
227: override suspend fun compareAndSet(expected: String?, replacement: String): Boolean {
239: private fun session(id: ProfileId): ProfileSession = ProfileSession(id, dispatcher = dispatcher, databaseFactory = {
240: object : YokanDatabase by InMemoryYokanDatabase() {
241: override suspend fun close() {
253: suspend fun ready(id: ProfileId) { registry.beginCreate("Books", id); registry.markReady(id) }
254: fun readyState() = assertIs<ProfileActivationState.Ready>(coordinator.state.value)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileCoordinatorTest.kt) · SHA-256 `b9c31f8a58277fe9b190cb38cf8ce1c46f639e784f9d339fec34d257ba018a62`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabase
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.withContext
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import kotlin.test.*
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult

class ProfileCoordinatorTest {
    @Test fun switchingValidatesStorageBeforeDetachmentAndDrainsBeforePreparation() = runTest {
        val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A)
        val gate = CompletableDeferred<Unit>()
        f.detachGate = gate
        val switching = launch { f.coordinator.switchTo(A) }
        testScheduler.runCurrent()
        assertIs<ProfileActivationState.Switching>(f.coordinator.state.value)
        assertEquals(listOf("open:${A.value}", "detach:default"), f.events)
        assertEquals(ProfileId.Default, f.registry.refresh().lastActive)
        gate.complete(Unit); switching.join()
        assertEquals(listOf("open:${A.value}", "detach:default", "close:default", "prepare:${A.value}"), f.events)
        assertEquals(A, f.readyState().session.id)
        assertEquals(A, f.registry.refresh().lastActive)
        f.coordinator.withProfile(A) { assertSame(f.readyState().session, it) }
        f.readyState().session.close()
    }

    @Test fun failedActivationReopensPreviousOwnerWithoutRepublishingRetiredObjects() = runTest {
        val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A); f.rejectPrepare = A
        val old = f.readyState().session
        assertFailsWith<IllegalStateException> { f.coordinator.switchTo(A) }
        assertEquals(ProfileSessionStatus.Closed, old.status.value)
        val recovered = f.readyState()
        assertEquals(ProfileId.Default, recovered.session.id)
        assertNotSame(old, recovered.session)
        assertEquals("Prepare failed", recovered.recoveryMessage)
        assertEquals(ProfileId.Default, f.registry.refresh().lastActive)
        assertTrue(f.events.indexOf("close:${A.value}") < f.events.indexOf("open:default"))
        recovered.session.close()
    }

    @Test fun failedRetirementCannotPrepareAnythingUntilSuccessfulRetry() = runTest {
        val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A); f.rejectClose = ProfileId.Default
        val old = f.readyState().session
        assertFailsWith<IllegalStateException> { f.coordinator.switchTo(A) }
        assertIs<ProfileActivationState.RecoveryRequired>(f.coordinator.state.value)
        assertEquals(ProfileSessionStatus.RetirementFailed, old.status.value)
        assertFalse(f.events.any { it == "prepare:${A.value}" })
        assertFailsWith<IllegalStateException> { f.coordinator.withProfile(A) {} }
        assertFailsWith<IllegalStateException> { f.coordinator.recover() }
        assertFalse(f.events.any { it == "prepare:${A.value}" })
        f.rejectClose = null; f.coordinator.recover()
        assertNotSame(old, f.readyState().session)
        assertEquals(ProfileId.Default, f.readyState().session.id)
        f.readyState().session.close()
    }

    @Test fun canceledSwitchStillPublishesConsistentOwnerAfterDetachment() = runTest {
        val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A)
        val gate = CompletableDeferred<Unit>(); f.detachGate = gate
        val switching = launch { f.coordinator.switchTo(A) }
        testScheduler.runCurrent(); switching.cancel(); gate.complete(Unit); switching.join()
        assertEquals(A, f.readyState().session.id)
        assertEquals(A, f.registry.refresh().lastActive)
        f.readyState().session.close()
    }

    @Test fun inactiveLeasePinsTargetUntilReleaseAndDeletionCannotRaceIt() = runTest {
        val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A)
        val active = f.readyState().session
        val gate = CompletableDeferred<Unit>(); val entered = CompletableDeferred<Unit>()
        val operation = launch { f.coordinator.withProfile(A) { target ->
            assertEquals(A, target.id); target.database
            entered.complete(Unit); gate.await()
        } }
        entered.await()
        val deletion = launch { f.coordinator.delete(A) }
        testScheduler.runCurrent()
        assertFalse(f.events.any { it.startsWith("delete:") })
        gate.complete(Unit); operation.join(); deletion.join()
        assertSame(active, f.readyState().session)
        assertEquals(ProfileSessionStatus.Open, active.status.value)
        assertEquals(listOf(A), f.registry.refresh().retiredIds)
        assertTrue(f.events.indexOf("close:${A.value}") < f.events.indexOf("delete:${A.value}"))
        assertFailsWith<IllegalArgumentException> { f.coordinator.withProfile(A) {} }
        active.close()
    }

    @Test fun deletionOfActiveProfileSwitchesToDefaultAndPreservesDeletionStageOnFailure() = runTest {
        val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A); f.coordinator.switchTo(A); f.rejectDelete = true
        assertFailsWith<IllegalStateException> { f.coordinator.delete(A) }
        assertEquals(ProfileId.Default, f.readyState().session.id)
        assertEquals(ProfileStatus.Deleting, f.registry.refresh().profiles.single { it.id == A }.status)
        f.rejectDelete = false; f.coordinator.delete(A); f.coordinator.delete(A)
        assertEquals(listOf(A), f.registry.refresh().retiredIds)
        assertFailsWith<IllegalArgumentException> { f.coordinator.delete(ProfileId.Default) }
        f.readyState().session.close()
    }

    @Test fun provisioningFailureRetainsStableIdAndCanResumeWithoutAnotherProfile() = runTest {
        val f = Fixture(StandardTestDispatcher(testScheduler)); f.rejectNewClose = true
        assertFailsWith<IllegalStateException> { f.coordinator.create("Books") }
        val staged = f.registry.refresh().profiles.single { it.id != ProfileId.Default }
        assertEquals(ProfileStatus.Provisioning, staged.status)
        f.rejectNewClose = false; f.coordinator.resumeProvisioning(staged.id)
        assertEquals(2, f.registry.refresh().profiles.size)
        assertEquals(ProfileStatus.Ready, f.registry.refresh().available(staged.id)?.status)
        f.coordinator.rename(staged.id, "Renamed")
        assertEquals("Renamed", f.registry.refresh().available(staged.id)?.name)
        f.readyState().session.close()
    }

    @Test fun invalidOrUnavailableTargetsNeverDetachActiveProfile() = runTest {
        val f = Fixture(StandardTestDispatcher(testScheduler))
        assertFailsWith<IllegalArgumentException> { f.coordinator.switchTo(A) }
        assertFailsWith<IllegalArgumentException> { f.coordinator.withProfile(A) {} }
        assertTrue(f.events.isEmpty())
        f.readyState().session.close()
    }

    @Test fun switchingCanRetireLongActiveBackgroundJobWithoutWaitingForItsLeaseMutex() = runTest {
        val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A)
        val started = CompletableDeferred<Unit>(); val finalizing = CompletableDeferred<Unit>(); val finish = CompletableDeferred<Unit>()
        var result: ProfileWorkResult<Unit>? = null
        val worker = launch { result = f.coordinator.run(ProfileId.Default) {
            try { started.complete(Unit); awaitCancellation() }
            finally { withContext(NonCancellable) { finalizing.complete(Unit); finish.await() } }
        } }
        started.await()
        val switching = launch { f.coordinator.switchTo(A) }
        finalizing.await()
        assertFalse(f.events.any { it == "prepare:${A.value}" })
        finish.complete(Unit); switching.join(); worker.join()
        assertIs<ProfileWorkResult.Skipped>(result)
        assertEquals(A, f.readyState().session.id)
        f.readyState().session.close()
    }

    @Test fun inactiveBackgroundWorkersShareOwnerAndDeletionJoinsBothBeforeRemovingData() = runTest {
        val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A)
        val started = CompletableDeferred<Unit>(); val secondStarted = CompletableDeferred<Unit>()
        var firstOwner: ProfileSession? = null; var secondOwner: ProfileSession? = null
        val first = launch { f.coordinator.run(A) { firstOwner = it; started.complete(Unit); awaitCancellation() } }
        started.await()
        val second = launch { f.coordinator.run(A) { secondOwner = it; secondStarted.complete(Unit); awaitCancellation() } }
        secondStarted.await()
        assertSame(firstOwner, secondOwner)
        f.coordinator.delete(A); first.join(); second.join()
        assertEquals(ProfileSessionStatus.Closed, firstOwner?.status?.value)
        assertEquals(1, f.events.count { it == "open:${A.value}" })
        assertTrue(f.events.indexOf("close:${A.value}") < f.events.indexOf("delete:${A.value}"))
        assertIs<ProfileWorkResult.Skipped>(f.coordinator.run(A) { error("Deleted storage reopened") })
        f.readyState().session.close()
    }

    @Test fun activationRetiresAlreadyRunningTargetWorkerBeforeOpeningItsForegroundDatabase() = runTest {
        val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A)
        val started = CompletableDeferred<Unit>(); var workerOwner: ProfileSession? = null
        val worker = launch { f.coordinator.run(A) { workerOwner = it; started.complete(Unit); awaitCancellation() } }
        started.await()
        f.coordinator.switchTo(A); worker.join()
        assertNotSame(workerOwner, f.readyState().session)
        assertEquals(ProfileSessionStatus.Closed, workerOwner?.status?.value)
        val targetEvents = f.events.filter { it.endsWith(A.value) }
        assertEquals(listOf("open:${A.value}", "close:${A.value}", "open:${A.value}", "prepare:${A.value}"), targetEvents)
        f.readyState().session.close()
    }

    @Test fun unavailableReplacementStorageKeepsCurrentOwnerLive() = runTest {
        val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A); f.rejectOpen = A
        val old = f.readyState().session
        assertFailsWith<IllegalStateException> { f.coordinator.switchTo(A) }
        assertSame(old, f.readyState().session)
        assertEquals(ProfileSessionStatus.Open, old.status.value)
        assertEquals(listOf("open:${A.value}"), f.events)
        assertEquals(ProfileId.Default, f.registry.refresh().lastActive)
        old.close()
    }

    @Test fun activeRestoreDetachesAndRetiresForegroundBeforeReplacingDataThenPublishesFreshOwner() = runTest {
        val f = Fixture(StandardTestDispatcher(testScheduler))
        val old = f.readyState().session
        var restoreOwner: ProfileSession? = null
        f.coordinator.replaceProfileData(ProfileId.Default) { restoreOwner = it; f.events.add("restore") }
        assertEquals(listOf("detach:default", "close:default", "open:default", "restore", "close:default", "open:default", "prepare:default"), f.events)
        assertEquals(ProfileSessionStatus.Closed, old.status.value)
        assertEquals(ProfileSessionStatus.Closed, restoreOwner?.status?.value)
        val fresh = f.readyState().session
        assertNotSame(old, fresh); assertNotSame(restoreOwner, fresh)
        assertNull(f.readyState().recoveryMessage)
        fresh.close()
    }

    @Test fun failedActiveRestoreStillPublishesUsableOwnerWithMessage() = runTest {
        val f = Fixture(StandardTestDispatcher(testScheduler))
        val old = f.readyState().session
        assertFailsWith<IllegalStateException> { f.coordinator.replaceProfileData(ProfileId.Default) { error("Corrupt backup") } }
        val recovered = f.readyState()
        assertNotSame(old, recovered.session)
        assertEquals(ProfileSessionStatus.Open, recovered.session.status.value)
        assertEquals("Corrupt backup", recovered.recoveryMessage)
        recovered.session.close()
    }

    @Test fun inactiveRestoreUsesTargetStorageWithoutDetachingForeground() = runTest {
        val f = Fixture(StandardTestDispatcher(testScheduler)); f.ready(A)
        val active = f.readyState().session
        val target = f.coordinator.replaceProfileData(A) { it.id }
        assertEquals(A, target)
        assertSame(active, f.readyState().session)
        assertEquals(ProfileSessionStatus.Open, active.status.value)
        assertEquals(listOf("open:${A.value}", "close:${A.value}"), f.events)
        active.close()
    }

    private class Fixture(private val dispatcher: CoroutineDispatcher) {
        private var raw: String? = null
        val registry = ProfileRegistry(object : ProfileRegistryPersistence {
            override suspend fun read() = raw
            override suspend fun compareAndSet(expected: String?, replacement: String): Boolean {
                if (raw != expected) return false
                raw = replacement; return true
            }
        })
        val events = mutableListOf<String>()
        var detachGate: CompletableDeferred<Unit>? = null
        var rejectOpen: ProfileId? = null
        var rejectPrepare: ProfileId? = null
        var rejectClose: ProfileId? = null
        var rejectNewClose = false
        var rejectDelete = false
        private fun session(id: ProfileId): ProfileSession = ProfileSession(id, dispatcher = dispatcher, databaseFactory = {
            object : YokanDatabase by InMemoryYokanDatabase() {
                override suspend fun close() {
                    events.add("close:${id.value}")
                    if (id == rejectClose || (id != ProfileId.Default && rejectNewClose)) error("Close failed")
                }
            }
        }).also { it.database }
        val coordinator = ProfileCoordinator(registry, session(ProfileId.Default),
            openSession = { id -> events.add("open:${id.value}"); if (id == rejectOpen) error("Storage reserved elsewhere"); session(id) },
            prepare = { owner -> events.add("prepare:${owner.id.value}"); if (owner.id == rejectPrepare) error("Prepare failed") },
            detach = { owner -> events.add("detach:${owner.id.value}"); detachGate?.await() },
            deleteStorage = { id -> events.add("delete:${id.value}"); if (rejectDelete) error("Delete failed") },
        )
        suspend fun ready(id: ProfileId) { registry.beginCreate("Books", id); registry.markReady(id) }
        fun readyState() = assertIs<ProfileActivationState.Ready>(coordinator.state.value)
    }
    companion object { private val A = ProfileId("p_${"a".repeat(32)}") }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistryTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistryTest.kt) · test / fixture · 220 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
16: class ProfileRegistryTest {
192: private class MemoryRegistry : ProfileRegistryPersistence {
200: override suspend fun read(): String? {
209: override suspend fun compareAndSet(expected: String?, replacement: String): Boolean {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistryTest.kt) · SHA-256 `acbda2a9ccd8e79fd1cd7b9f6db514590081af0aa55a39f82b67c1f9abb442cb`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertIs
import kotlin.test.assertTrue
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.domain.ProfileStorageNamespace

class ProfileRegistryTest {
    @Test fun adoptionCreatesOnlyDefaultAndKeepsStableMetadataOnRestart() = runTest {
        val store = MemoryRegistry()
        val registry = ProfileRegistry(store)
        assertEquals(ProfileRegistrySnapshot(), registry.refresh())
        val firstRaw = store.raw
        assertEquals(ProfileRegistrySnapshot(), ProfileRegistry(store).refresh())
        assertEquals(firstRaw, store.raw)
        assertEquals(1, store.commits)
        assertFalse(registry.refresh().hasAdditionalProfiles)
    }

    @Test fun provisionRenameActivateDeleteAndTombstonesSurviveRestart() = runTest {
        val store = MemoryRegistry(); val registry = ProfileRegistry(store)
        registry.refresh()
        assertEquals(ProfileStatus.Provisioning, registry.beginCreate("  読書 🌙  ", A).profiles.last().status)
        assertFalse(ProfileRegistry(store).refresh().hasAdditionalProfiles)
        assertFailsWith<IllegalArgumentException> { registry.recordActive(A) }
        registry.markReady(A)
        assertTrue(ProfileRegistry(store).refresh().hasAdditionalProfiles)
        registry.rename(A, "Renamed")
        assertEquals("Renamed", registry.recordActive(A).available(A)?.name)
        assertEquals(A, ProfileRegistry(store).refresh().lastActive)
        assertFailsWith<IllegalArgumentException> { registry.beginDelete(A) }
        registry.recordActive(ProfileId.Default)
        val deleting = registry.beginDelete(A)
        assertFalse(deleting.hasAdditionalProfiles)
        assertEquals(ProfileStatus.Deleting, ProfileRegistry(store).refresh().profiles.last().status)
        assertFailsWith<IllegalArgumentException> { registry.recordActive(A) }
        val deleted = registry.finishDelete(A)
        assertEquals(listOf(A), deleted.retiredIds)
        assertEquals(deleted, registry.finishDelete(A))
        assertEquals(deleted, ProfileRegistry(store).refresh())
        assertFailsWith<IllegalArgumentException> { registry.beginCreate("Reused", A) }
    }

    @Test fun defaultInvalidNamesDuplicateIdsAndMissingOwnersCannotBeCommitted() = runTest {
        val store = MemoryRegistry(); val registry = ProfileRegistry(store)
        registry.refresh(); registry.beginCreate("Books", A); registry.markReady(A)
        val saved = store.raw
        assertFailsWith<IllegalArgumentException> { registry.rename(ProfileId.Default, "Other") }
        assertFailsWith<IllegalArgumentException> { registry.beginDelete(ProfileId.Default) }
        assertFailsWith<IllegalArgumentException> { registry.finishDelete(ProfileId.Default) }
        assertFailsWith<IllegalArgumentException> { registry.beginCreate("Another", A) }
        assertFailsWith<IllegalArgumentException> { registry.beginCreate("books", B) }
        assertFailsWith<IllegalArgumentException> { registry.beginCreate("default", B) }
        assertFailsWith<IllegalArgumentException> { registry.beginCreate("\n\t", B) }
        assertFailsWith<IllegalArgumentException> { registry.beginCreate("a\nb", B) }
        assertFailsWith<IllegalArgumentException> { registry.beginCreate("a".repeat(81), B) }
        assertFailsWith<Exception> { registry.beginCreate("\uD800", B) }
        assertFailsWith<IllegalArgumentException> { registry.recordActive(B) }
        assertFailsWith<IllegalArgumentException> { registry.rename(B, "Unknown") }
        assertEquals(saved, store.raw)
        assertEquals(2, registry.refresh().profiles.size)
    }

    @Test fun exportDestinationsSurviveDeletionStagingAndCannotBeAddedToUnavailableOwners() = runTest {
        val store = MemoryRegistry(); val registry = ProfileRegistry(store)
        registry.beginCreate("Books", A); registry.markReady(A)
        registry.recordExport(A, "/exports/books.json")
        registry.recordExport(A, "/exports/books.json")
        assertEquals(listOf("/exports/books.json"), ProfileRegistry(store).refresh().available(A)?.exportedBackups)
        assertEquals(listOf("/exports/books.json"), registry.beginDelete(A).profiles.single { it.id == A }.exportedBackups)
        assertFailsWith<IllegalArgumentException> { registry.recordExport(A, "/another.json") }
        registry.recordExport(ProfileId.Default, "/default.json")
        assertEquals(ProfileRecord(ProfileId.Default, "Default"), registry.refresh().available(ProfileId.Default))
    }

    @Test fun badOrFutureRegistryIsNeverReplacedByAnEmptyDefault() = runTest {
        for (raw in listOf("{", "{} garbage", "{\"version\":2}",
            "{\"profiles\":[]}", "{\"lastActive\":\"p_${"a".repeat(32)}\"}",
            "{\"profiles\":[{\"id\":\"../outside\",\"name\":\"Unsafe\"}]}",
            "{\"unrecognized\":true}", " ".repeat(MaxProfileRegistryBytes + 1))) {
            val store = MemoryRegistry().also { it.raw = raw }
            val registry = ProfileRegistry(store)
            assertFailsWith<Exception> { registry.refresh() }
            assertEquals(raw, store.raw)
            assertEquals(0, store.commits)
            assertIs<ProfileRegistryState.Unavailable>(registry.state.value)
        }
    }

    @Test fun failedCommitRetainsThePriorRegistryAndCanBeRetried() = runTest {
        val store = MemoryRegistry(); val registry = ProfileRegistry(store)
        registry.refresh(); val saved = store.raw
        store.reject = true
        assertFailsWith<IllegalStateException> { registry.beginCreate("New", A) }
        assertEquals(saved, store.raw)
        assertIs<ProfileRegistryState.Unavailable>(registry.state.value)
        store.reject = false
        registry.refresh(); registry.beginCreate("New", A)
        assertEquals(ProfileStatus.Provisioning, ProfileRegistry(store).refresh().profiles.last().status)
    }

    @Test fun concurrentRegistryInstancesRetryAgainstCurrentMetadataWithoutLosingProfiles() = runTest {
        val store = MemoryRegistry()
        val left = ProfileRegistry(store); val right = ProfileRegistry(store)
        left.refresh()
        store.barrier = CompletableDeferred()
        val a = async { left.beginCreate("A", A) }
        val b = async { right.beginCreate("B", B) }
        a.await(); b.await()
        val result = ProfileRegistry(store).refresh()
        assertEquals(setOf(ProfileId.Default, A, B), result.profiles.map { it.id }.toSet())
        assertTrue(store.conflicts > 0)
    }

    @Test fun cancellationAfterCommitStartsJoinsItsResult() = runTest {
        val store = MemoryRegistry(); val registry = ProfileRegistry(store)
        registry.refresh()
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        store.beforeCommit = { entered.complete(Unit); release.await() }
        val writer = launch { registry.beginCreate("Joined", A) }
        entered.await(); writer.cancel(); release.complete(Unit); writer.join()
        store.beforeCommit = null
        assertEquals(A, ProfileRegistry(store).refresh().profiles.last().id)
    }

    @Test fun deletionCapacityIsCheckedBeforeDataRemovalCanBegin() = runTest {
        val store = MemoryRegistry().also {
            it.raw = encodeProfileRegistry(ProfileRegistrySnapshot(
                profiles = listOf(ProfileRecord(ProfileId.Default, "Default"), ProfileRecord(A, "Books")),
                retiredIds = List(MaxRetiredProfileIds) { index -> ProfileId("p_${index.toString(16).padStart(32, '0')}") },
            ))
        }
        val saved = store.raw
        val registry = ProfileRegistry(store)
        registry.refresh()
        assertFailsWith<IllegalArgumentException> { registry.beginDelete(A) }
        assertEquals(saved, store.raw)
        assertEquals(ProfileStatus.Ready, ProfileRegistry(store).refresh().available(A)?.status)
    }

    @Test fun syncLeasesAreExclusiveIdempotentReleasedAndDroppedWithTheirProfile() = runTest {
        val store = MemoryRegistry().also {
            // Pre-lease registry JSON (no syncLeases field) still decodes.
            it.raw = """{"version":1,"profiles":[{"id":"default","name":"Default"},{"id":"${A.value}","name":"Reader"},""" +
                """{"id":"${B.value}","name":"Other"}],"lastActive":"default","retiredIds":[]}"""
        }
        val registry = ProfileRegistry(store)
        assertEquals(emptyList(), registry.refresh().syncLeases)
        registry.claimSyncLease(A, "hub|https://hub.test|a@b")
        registry.claimSyncLease(A, "hub|https://hub.test|a@b")
        val conflict = assertFailsWith<IllegalStateException> { registry.claimSyncLease(B, "hub|https://hub.test|a@b") }
        assertEquals("This sync account is already connected to profile ‘Reader’. Log out there first.", conflict.message)
        assertIs<ProfileRegistryState.Ready>(registry.state.value)
        // One lease per profile: switching accounts frees the old one.
        registry.claimSyncLease(A, "cloud|gdrive|a@b")
        registry.claimSyncLease(B, "hub|https://hub.test|a@b")
        assertEquals(listOf(ProfileSyncLease("cloud|gdrive|a@b", A), ProfileSyncLease("hub|https://hub.test|a@b", B)),
            ProfileRegistry(store).refresh().syncLeases)
        registry.releaseSyncLease(A, "hub|https://hub.test|a@b") // not A's: no effect
        registry.releaseSyncLease(B, "hub|https://hub.test|a@b")
        registry.claimSyncLease(A, "hub|https://hub.test|a@b")
        registry.beginDelete(A)
        assertEquals(emptyList(), registry.refresh().syncLeases)
        assertFailsWith<IllegalStateException> { registry.claimSyncLease(A, "hub|https://hub.test|a@b") }
        registry.claimSyncLease(B, "hub|https://hub.test|a@b")
        registry.finishDelete(A)
        assertEquals(listOf(ProfileSyncLease("hub|https://hub.test|a@b", B)), ProfileRegistry(store).refresh().syncLeases)
    }

    @Test fun namespaceUsesOnlyValidatedIdsAndDefaultKeepsLegacyLocations() {
        val default = ProfileStorageNamespace(ProfileId.Default)
        assertEquals("yokan-room.db", default.databaseRelativePath)
        assertEquals("yokan-database-v1", default.browserSnapshotKey)
        assertEquals("/existing", default.ownedRoot("/existing/"))
        val extra = ProfileStorageNamespace(A)
        assertEquals("profiles/${A.value}/yokan-room.db", extra.databaseRelativePath)
        assertEquals("yokan-database-v1:${A.value}", extra.browserSnapshotKey)
        assertEquals("/existing/profiles/${A.value}", extra.ownedRoot("/existing/"))
        for (bad in listOf("", "Default", "../outside", "/tmp", "p_ABC", "p_${"a".repeat(31)}", "p_${"a".repeat(33)}")) {
            assertFailsWith<IllegalArgumentException> { ProfileId(bad) }
        }
        assertEquals(100, List(100) { ProfileId.random() }.distinct().size)
    }
    private class MemoryRegistry : ProfileRegistryPersistence {
        var raw: String? = null
        var commits = 0
        var conflicts = 0
        var reject = false
        var barrier: CompletableDeferred<Unit>? = null
        private var reads = 0
        var beforeCommit: (suspend () -> Unit)? = null
        override suspend fun read(): String? {
            val result = raw
            barrier?.let { gate ->
                reads++
                if (reads == 2) { barrier = null; gate.complete(Unit) }
                gate.await()
            }
            return result
        }
        override suspend fun compareAndSet(expected: String?, replacement: String): Boolean {
            beforeCommit?.invoke()
            if (reject) error("Storage unavailable")
            if (raw != expected) { conflicts++; return false }
            raw = replacement; commits++; return true
        }
    }
    companion object {
        val A = ProfileId("p_${"a".repeat(32)}")
        val B = ProfileId("p_${"b".repeat(32)}")
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSessionTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSessionTest.kt) · test / fixture · 132 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
22: class ProfileSessionTest {
123: private class ProbeDatabase(private val memory: InMemoryYokanDatabase = InMemoryYokanDatabase()) : YokanDatabase by memory {
125: override suspend fun close() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSessionTest.kt) · SHA-256 `ed4e76e7a8a52673a189a09e0eff613d6b31c5bacd256208425c1de771d57037`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabase
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertSame
import kotlin.test.assertTrue
import eu.friedcutlet.yokan.domain.ProfileId

@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
class ProfileSessionTest {
    @Test fun unusedSessionClosesWithoutOpeningLazyResources() = runTest {
        var opens = 0
        val owner = ProfileSession(ProfileId.Default, databaseFactory = { opens++; error("Unused database") })
        owner.close(); owner.close()
        assertEquals(0, opens)
        assertEquals(ProfileSessionStatus.Closed, owner.status.value)
        assertFailsWith<IllegalStateException> { owner.database }
    }

    @Test fun independentOwnersCaptureTheirDatabaseAndRetirementDoesNotTouchAnother() = runTest {
        val a = ProbeDatabase(); val b = ProbeDatabase()
        val left = ProfileSession(A, databaseFactory = { assertEquals(A, it); a })
        val right = ProfileSession(B, databaseFactory = { assertEquals(B, it); b })
        assertSame(a, left.database); assertSame(a, left.database)
        assertSame(b, right.database)
        a.upsertManga(DbManga(id = 42, privateNote = "A")); b.upsertManga(DbManga(id = 42, privateNote = "B"))
        left.close()
        assertEquals(1, a.closes); assertEquals(0, b.closes)
        assertEquals("B", right.database.manga(42)?.privateNote)
        assertFailsWith<IllegalStateException> { left.database }
        right.close()
    }

    @Test fun cancellationJoinsFinalProgressBeforeClosingDatabase() = runTest {
        val db = ProbeDatabase()
        val owner = ProfileSession(A, databaseFactory = { db }, dispatcher = StandardTestDispatcher(testScheduler))
        val captured = owner.database
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        owner.scope.launch {
            try { entered.complete(Unit); awaitCancellation() }
            finally {
                withContext(NonCancellable) { release.await(); captured.upsertManga(DbManga(id = 42, privateNote = "Final progress")) }
            }
        }
        entered.await()
        val retiring = launch { owner.close() }
        testScheduler.runCurrent()
        assertEquals(ProfileSessionStatus.Retiring, owner.status.value)
        assertEquals(0, db.closes)
        retiring.cancel(); release.complete(Unit); retiring.join()
        assertEquals("Final progress", db.noteAtClose)
        assertEquals(ProfileSessionStatus.Closed, owner.status.value)
        assertEquals(1, db.closes)
    }

    @Test fun failedFlushCanBeRetriedWithoutRecreatingResources() = runTest {
        val db = ProbeDatabase(); var opens = 0
        val owner = ProfileSession(A, databaseFactory = { opens++; db })
        owner.database.upsertManga(DbManga(id = 42, privateNote = "Keep"))
        db.reject = true
        assertFailsWith<IllegalStateException> { owner.close() }
        assertEquals(ProfileSessionStatus.RetirementFailed, owner.status.value)
        assertFalse(db.released)
        assertFailsWith<IllegalStateException> { owner.database }
        db.reject = false; owner.close(); owner.close()
        assertEquals(1, opens); assertTrue(db.released)
        assertEquals("Keep", db.noteAtClose)
    }

    @Test fun joinTimeoutKeepsDatabaseUntilFinalizerCompletesAndRetirementRetries() = runTest {
        val db = ProbeDatabase()
        val owner = ProfileSession(A, databaseFactory = { db }, dispatcher = StandardTestDispatcher(testScheduler), joinTimeoutMillis = 100)
        owner.database
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        owner.scope.launch { try { entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { release.await() } } }
        entered.await()
        assertFailsWith<kotlinx.coroutines.TimeoutCancellationException> { owner.close() }
        assertEquals(0, db.closes)
        assertEquals(ProfileSessionStatus.RetirementFailed, owner.status.value)
        release.complete(Unit); owner.close()
        assertEquals(1, db.closes)
    }

    @Test fun platformFactoryRejectsExtraProfilesBeforeAllocatingResources() {
        assertFailsWith<IllegalStateException> { createPlatformProfileSession(A, eu.friedcutlet.yokan.services.sync.SyncAccountLeases.None) }
    }

    @Test fun contextResourceFailureRetainsDatabaseAndRetriesBeforeItsRelease() = runTest {
        val db = ProbeDatabase(); var releases = 0; var reject = true
        val owner = ProfileSession(A, databaseFactory = { db })
        val captured = owner.ownResource(factory = { owner.database }, close = {
            assertSame(db, it); releases++; if (reject) error("Transport cleanup failed")
        })
        assertSame(db, captured)
        assertFailsWith<IllegalStateException> { owner.close() }
        assertEquals(ProfileSessionStatus.RetirementFailed, owner.status.value)
        assertEquals(0, db.closes)
        reject = false; owner.close(); owner.close()
        assertEquals(2, releases); assertEquals(1, db.closes)
    }

    @Test fun retiredOwnerRejectsContextResourceBeforeItsFactoryRuns() = runTest {
        val owner = ProfileSession(A); var allocations = 0
        owner.close()
        assertFailsWith<IllegalStateException> {
            owner.ownResource(factory = { allocations++; Any() }, close = {})
        }
        assertEquals(0, allocations)
    }

    private class ProbeDatabase(private val memory: InMemoryYokanDatabase = InMemoryYokanDatabase()) : YokanDatabase by memory {
        var closes = 0; var released = false; var reject = false; var noteAtClose: String? = null
        override suspend fun close() {
            closes++
            if (reject) error("Persistence unavailable")
            noteAtClose = manga(42)?.privateNote; released = true
        }
    }
    companion object { val A = ProfileId("p_${"a".repeat(32)}"); val B = ProfileId("p_${"b".repeat(32)}") }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSnapshotRetirementTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSnapshotRetirementTest.kt) · test / fixture · 65 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
16: class ProfileSnapshotRetirementTest {
57: private class Store(private val onSave: () -> Unit) : DatabaseSnapshotStore {
59: override fun load() = saved
60: override fun save(snapshot: YokanDatabaseSnapshot) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSnapshotRetirementTest.kt) · SHA-256 `ec7ed75d2d47fdec83281184c59162b5817fda1b026925efa5d6ee5d24b32522`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.database.DatabaseSnapshotStore
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.SnapshotYokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class ProfileSnapshotRetirementTest {
    @Test fun closeStopsPersistenceThenFlushesAndLateSavesCannotOverwriteStorage() = runTest {
        val events = mutableListOf<String>(); val store = Store { events += "save" }
        val db = SnapshotYokanDatabase(store, stopPersistence = { events += "stop" })
        db.upsertManga(DbManga(id = 42, privateNote = "Saved"))
        db.close()
        assertEquals(listOf("stop", "save"), events)
        assertEquals("Saved", store.saved?.mangas?.single()?.privateNote)
        db.close()
        // A retained old in-memory reference cannot write through after retirement.
        db.upsertManga(DbManga(id = 42, privateNote = "Late"))
        assertFalse(db.persistIfDirty()); assertFalse(db.persist())
        assertFailsWith<IllegalStateException> { db.awaitPersistence() }
        assertFailsWith<IllegalStateException> { db.replaceAllAtomically(db.snapshot(), null, emptySet()) }
        assertEquals("Saved", store.saved?.mangas?.single()?.privateNote)
        assertEquals(listOf("stop", "save"), events)
    }

    @Test fun failedClosePreservesDirtySnapshotAndCanRetryAfterQuotaRecovery() = runTest {
        val store = Store {}; val db = SnapshotYokanDatabase(store)
        db.upsertManga(DbManga(id = 42, privateNote = "Original")); db.awaitPersistence()
        db.upsertManga(DbManga(id = 42, privateNote = "Pending")); store.reject = true
        assertFailsWith<IllegalStateException> { db.close() }
        assertTrue(db.saveFailed.value)
        assertEquals("Original", store.saved?.mangas?.single()?.privateNote)
        assertEquals("Pending", db.manga(42)?.privateNote)
        store.reject = false; db.close()
        assertEquals("Pending", store.saved?.mangas?.single()?.privateNote)
        assertFalse(db.saveFailed.value)
    }

    @Test fun cancelledCloseStillJoinsPersistenceShutdownAndFinalSave() = runTest {
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>(); val store = Store {}
        val db = SnapshotYokanDatabase(store, stopPersistence = { entered.complete(Unit); release.await() })
        db.upsertManga(DbManga(id = 42, privateNote = "Final"))
        val closing = launch { db.close() }
        entered.await(); closing.cancel(); release.complete(Unit); closing.join()
        assertEquals("Final", store.saved?.mangas?.single()?.privateNote)
        assertFalse(db.persistIfDirty())
    }

    private class Store(private val onSave: () -> Unit) : DatabaseSnapshotStore {
        var saved: YokanDatabaseSnapshot? = null; var reject = false
        override fun load() = saved
        override fun save(snapshot: YokanDatabaseSnapshot) {
            if (reject) error("Quota exceeded")
            onSave(); saved = snapshot
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.desktop.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.desktop.kt) · implementation · 26 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
7: object DesktopBootstrapState {
11: actual fun platformBootstrapInput(): PlatformBootstrapInput = PlatformBootstrapInput(
20: internal fun desktopLaunchLink(args: Array<String>): String? {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.desktop.kt) · SHA-256 `a877c4e40a7ccc0c12bdf3a4e99c904d4144341447edcdca06c9e21e32aa76e5`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app

import eu.friedcutlet.yokan.services.files.desktopDataRoot
import eu.friedcutlet.yokan.ui.navigation.searchDeepLink
import java.io.File

object DesktopBootstrapState {
    var args: Array<String> = emptyArray()
}

actual fun platformBootstrapInput(): PlatformBootstrapInput = PlatformBootstrapInput(
    platformName = "Desktop",
    initialDeepLink = desktopLaunchLink(DesktopBootstrapState.args),
    appDataPath = desktopDataRoot.absolutePath,
)

private val linkSchemes = listOf("yokan://", "tachiyomi://", "mihon://", "aniyomi://", "animetail://", "http://", "https://", "file:")

/** `--search <query>` / `--search=<query>`, an app link, or a backup file path (file associations pass the path). */
internal fun desktopLaunchLink(args: Array<String>): String? {
    val search = args.indexOf("--search").takeIf { it >= 0 }?.let { args.getOrNull(it + 1) }
        ?: args.firstOrNull { it.startsWith("--search=") }?.removePrefix("--search=")
    if (!search.isNullOrBlank()) return searchDeepLink(search.trim())
    return args.firstOrNull { arg -> linkSchemes.any(arg::startsWith) }
        ?: args.firstOrNull { !it.startsWith("-") && File(it).isFile }?.let { File(it).absoluteFile.toURI().toString() }
}
```
[complete-source-end]: #

## `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.desktop.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.desktop.kt) · implementation · 7 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
6: actual fun createPlatformProfileRegistry(): ProfileRegistry =
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.desktop.kt) · SHA-256 `7f43a9345962dbd44cf287c390e175ff02acc7951a7126e40b4895dd1e94c81f`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.services.files.desktopDataRoot
import java.io.File

actual fun createPlatformProfileRegistry(): ProfileRegistry =
    ProfileRegistry(FileProfileRegistryPersistence(File(desktopDataRoot, "profiles/registry.json")))
```
[complete-source-end]: #

## `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.desktop.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.desktop.kt) · implementation · 10 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
8: internal actual suspend fun deletePlatformProfileStorage(id: ProfileId, exportedBackups: List<String>) = withContext(Dispatchers.IO) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.desktop.kt) · SHA-256 `2210c4ff552e4c2b4047f03384ef4940dea4d55b8924ae10b4caa260605b4a7a`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.services.files.desktopDataRoot
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.domain.ProfileId

internal actual suspend fun deletePlatformProfileStorage(id: ProfileId, exportedBackups: List<String>) = withContext(Dispatchers.IO) {
    deleteOwnedProfileDirectory(desktopDataRoot, id, exportedBackups)
}
```
[complete-source-end]: #

## `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.desktop.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.desktop.kt) · implementation · 11 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
8: internal actual suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease =
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.desktop.kt) · SHA-256 `e2cb220373c5090aa8a04c90ee6e8cfce9b9b9dee7f5c61d72bdfb3849898ed8`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.services.files.desktopDataRoot
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.domain.ProfileId

internal actual suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease =
    if (id == ProfileId.Default) ProfileStorageLease {} else withContext(Dispatchers.IO) {
        acquireFileProfileLease(desktopDataRoot, id)
    }
```
[complete-source-end]: #

## `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.desktop.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.desktop.kt) · implementation · 5 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
5: internal actual suspend fun cancelProfileBackgroundWork(id: ProfileId) { require(id != ProfileId.Default) }
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.desktop.kt) · SHA-256 `6075112f70257ccd256f0853f34524bce0ee74187f8bfd10a8e17c3ed16f5891`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.domain.ProfileId

internal actual suspend fun cancelProfileBackgroundWork(id: ProfileId) { require(id != ProfileId.Default) }
```
[complete-source-end]: #

## `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/DesktopLaunchLinkTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/DesktopLaunchLinkTest.kt) · test / fixture · 22 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
9: class DesktopLaunchLinkTest {
11: fun mapsSearchFlagsLinksAndBackupFiles() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/DesktopLaunchLinkTest.kt) · SHA-256 `1e05702e45a43493d0f5c3100bfbcb38b91da24032a2727d5ff7bc5768f38de0`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app

import eu.friedcutlet.yokan.ui.navigation.searchDeepLink
import java.io.File
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull

class DesktopLaunchLinkTest {
    @Test
    fun mapsSearchFlagsLinksAndBackupFiles() {
        assertEquals(searchDeepLink("One Piece"), desktopLaunchLink(arrayOf("--tray", "--search", "One Piece")))
        assertEquals(searchDeepLink("Berserk"), desktopLaunchLink(arrayOf("--search=Berserk")))
        assertEquals("mihon://add-repo?url=x", desktopLaunchLink(arrayOf("--tray", "mihon://add-repo?url=x")))

        val backup = File.createTempFile("library", ".tachibk").apply { deleteOnExit() }
        assertEquals(backup.absoluteFile.toURI().toString(), desktopLaunchLink(arrayOf(backup.path)))

        assertNull(desktopLaunchLink(arrayOf("--tray", "missing.tachibk")))
        assertNull(desktopLaunchLink(arrayOf("--search")))
    }
}
```
[complete-source-end]: #

## `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSessionRoomTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSessionRoomTest.kt) · test / fixture · 153 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
25: class ProfileSessionRoomTest {
147: private object SilentNotifications : NotificationService {
148: override fun supported() = false
149: override fun notify(payload: NotificationPayload) = Unit
150: override fun cancel(channel: NotificationChannel, tag: String?) = Unit
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSessionRoomTest.kt) · SHA-256 `c8e4dbc7ba149c336e9338f9f03cd8bab48c08b860ee1bfe5fe5e652ddf75741`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import androidx.sqlite.driver.bundled.BundledSQLiteDriver
import androidx.sqlite.execSQL
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.room.RoomYokanDatabase
import eu.friedcutlet.yokan.database.room.createDesktopProfileRoomDatabase
import eu.friedcutlet.yokan.services.files.createDesktopProfileFileService
import eu.friedcutlet.yokan.services.files.JvmLocalArchiveService
import eu.friedcutlet.yokan.services.notifications.NotificationService
import eu.friedcutlet.yokan.services.notifications.NotificationPayload
import eu.friedcutlet.yokan.services.notifications.NotificationChannel
import eu.friedcutlet.yokan.services.logging.LogSink
import java.nio.file.Files
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.TimeoutCancellationException
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertSame
import kotlin.test.assertTrue
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.domain.ProfileStorageNamespace

class ProfileSessionRoomTest {
    @Test fun roomCloseDrainsQueuedWritesRejectsStaleMutationsAndReopensIndependently() = runBlocking {
        val root = Files.createTempDirectory("yokan-profile-retire").toFile()
        try {
            val db = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, A))
            (1L..100L).forEach { db.upsertManga(DbManga(id = it, privateNote = "A $it")) }
            db.close(); db.close()
            val before = db.snapshot()
            assertFailsWith<IllegalStateException> { db.upsertManga(DbManga(id = 42, privateNote = "Stale")) }
            assertEquals(before, db.snapshot())
            assertFailsWith<IllegalStateException> { db.updateSettings(db.settings()) }
            assertFailsWith<IllegalStateException> { db.batch { db.removeManga(42) } }
            assertFailsWith<IllegalStateException> { db.awaitPersistence() }
            val reopened = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, A))
            try { assertEquals(100, reopened.mangas().size); assertEquals("A 42", reopened.manga(42)?.privateNote) }
            finally { reopened.close() }
            val b = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, B))
            try { assertTrue(b.mangas().isEmpty()) } finally { b.close() }
        } finally { root.deleteRecursively() }
    }

    @Test fun busyRoomCloseTimesOutWithoutDroppingWritesAndCanBeRetried() = runBlocking {
        val root = Files.createTempDirectory("yokan-profile-busy").toFile()
        val room = createDesktopProfileRoomDatabase(root, A)
        val db = RoomYokanDatabase(room, closeTimeoutMillis = 200)
        try {
            db.awaitPersistence()
            val lock = BundledSQLiteDriver().open(java.io.File(root, ProfileStorageNamespace(A).databaseRelativePath).path)
            var transactionStarted = false
            try {
                // Room's empty flush barrier can still be finishing its transaction.
                // Wait for that brief contention before deliberately holding the write lock.
                lock.execSQL("PRAGMA busy_timeout = 5000")
                lock.execSQL("BEGIN IMMEDIATE")
                transactionStarted = true
                db.upsertManga(DbManga(id = 42, privateNote = "Queued"))
                assertFailsWith<TimeoutCancellationException> { db.close() }
                // The failed close has not released Room or discarded its queue.
                db.upsertManga(DbManga(id = 43, privateNote = "Retry"))
            } finally {
                try { if (transactionStarted) lock.execSQL("ROLLBACK") }
                finally { lock.close() }
            }
            db.awaitPersistence(); db.close()
            val reopened = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, A))
            try { assertEquals("Queued", reopened.manga(42)?.privateNote); assertEquals("Retry", reopened.manga(43)?.privateNote) }
            finally { reopened.close() }
        } finally { room.close(); root.deleteRecursively() }
    }

    @Test fun defaultServiceGraphSharesSessionScopeAndRetiresActualRoomAndObservers() = runBlocking {
        val root = Files.createTempDirectory("yokan-default-session").toFile()
        try {
            val owner = ProfileSession(ProfileId.Default,
                databaseFactory = { RoomYokanDatabase(createDesktopProfileRoomDatabase(root, it)) },
                filesFactory = { createDesktopProfileFileService(root, it) },
                archivesFactory = { JvmLocalArchiveService(createDesktopProfileFileService(root, it).cacheRoot) },
                notificationsFactory = { SilentNotifications },
            )
            val db = owner.database
            val capturedHttp = owner.services.http
            val capturedTogether = owner.together
            val capturedReaderContent = owner.readerContent
            val capturedSpeech = owner.services.textToSpeech
            val capturedSpeechReader = capturedSpeech.reader()
            val capturedPlayerServices = owner.playerServices
            val capturedPlayerReader = capturedPlayerServices.reader()
            assertEquals(ProfileId.Default, capturedPlayerServices.profileId)
            assertSame(capturedReaderContent, owner.readerContent)
            assertEquals(ProfileId.Default, capturedReaderContent.profileId)
            assertEquals("Inline chapter", capturedReaderContent.novelText(null, "Novel", "Inline chapter"))
            assertSame(owner.scope, owner.services.scope)
            assertSame(db, owner.services.database)
            owner.settings; owner.libraryIndex; owner.migration; owner.chapterPages
            db.upsertManga(DbManga(id = 42, privateNote = "Default"))
            owner.close()
            assertEquals(ProfileSessionStatus.Closed, owner.status.value)
            assertEquals(false, capturedSpeech.isAvailable)
            assertEquals(false, capturedPlayerServices.isAvailable)
            assertFailsWith<kotlinx.coroutines.CancellationException> {
                capturedPlayerReader.configuration(eu.friedcutlet.yokan.database.DbSettings())
            }
            assertFailsWith<kotlinx.coroutines.CancellationException> {
                capturedPlayerReader.streamProxy.proxyUrl("https://retired.test/video", mapOf("Referer" to "retired"))
            }
            assertFailsWith<kotlinx.coroutines.CancellationException> { capturedSpeech.voices(null) }
            assertFailsWith<kotlinx.coroutines.CancellationException> {
                capturedSpeechReader.speak("Retired chapter", eu.friedcutlet.yokan.services.tts.TextToSpeechRequest()) { _, _ ->
                    error("Retired owner reported speech progress")
                }
            }
            assertEquals(null, capturedTogether.hubSession())
            assertEquals(null, capturedTogether.client.value)
            assertFailsWith<IllegalStateException> { owner.repository }
            assertFailsWith<kotlinx.coroutines.CancellationException> {
                capturedReaderContent.novelText(null, "Novel", "Retired chapter")
            }
            // Stale UI/extension references must fail before settings/cookies or the closed engine.
            assertFailsWith<kotlinx.coroutines.CancellationException> {
                capturedHttp.request(eu.friedcutlet.yokan.services.http.HttpRequest("https://source.test/"))
            }
            assertFailsWith<kotlinx.coroutines.CancellationException> {
                capturedHttp.stream(eu.friedcutlet.yokan.services.http.HttpRequest("https://source.test/")) {
                    error("Retired owner wrote bytes")
                }
            }
            val reopened = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, ProfileId.Default))
            try { assertEquals("Default", reopened.manga(42)?.privateNote) } finally { reopened.close() }
        } finally { root.deleteRecursively() }
    }

    @Test fun staleLoggingOwnerCannotDetachNewTargetEvenWhenBothUseSameFileService() {
        val root = Files.createTempDirectory("yokan-log-owner").toFile()
        try {
            val files = createDesktopProfileFileService(root, ProfileId.Default)
            val old = LogSink.attach(files) { false }; val current = LogSink.attach(files) { false }
            LogSink.detach(old)
            assertEquals("${files.cacheRoot}/logs/yokan.log", LogSink.logFilePath())
            LogSink.detach(current); assertEquals(null, LogSink.logFilePath())
        } finally { root.deleteRecursively() }
    }

    private object SilentNotifications : NotificationService {
        override fun supported() = false
        override fun notify(payload: NotificationPayload) = Unit
        override fun cancel(channel: NotificationChannel, tag: String?) = Unit
    }
    companion object { val A = ProfileId("p_${"a".repeat(32)}"); val B = ProfileId("p_${"b".repeat(32)}") }
}
```
[complete-source-end]: #

## `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletionTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletionTest.kt) · test / fixture · 53 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
8: class ProfileStorageDeletionTest {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletionTest.kt) · SHA-256 `d30402494cef9dbee2e996b549250f2cb0021b532f2801a56a88fc9559a7a3f4`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import java.nio.file.Files
import kotlin.test.*
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.domain.ProfileStorageNamespace

class ProfileStorageDeletionTest {
    @Test fun deletionKeepsOtherOwnersExportsAndSymlinkTargets() {
        val base = Files.createTempDirectory("yokan-profile-delete").toFile()
        try {
            val namespace = ProfileStorageNamespace(A)
            val root = java.io.File(namespace.ownedRoot(base.path)).apply { mkdirs() }
            val other = java.io.File(ProfileStorageNamespace(B).ownedRoot(base.path)).apply { mkdirs() }
            val exported = java.io.File(root, "backups/export.json").apply { parentFile.mkdirs(); writeText("export") }
            java.io.File(root, "yokan-room.db").writeText("A")
            java.io.File(root, "downloads/42.cbz").apply { parentFile.mkdirs(); writeText("A pages") }
            java.io.File(other, "yokan-room.db").writeText("B")
            val external = java.io.File(base, "external").apply { mkdirs() }
            val userFile = java.io.File(external, "chapter.cbz").apply { writeText("user") }
            Files.createSymbolicLink(java.io.File(root, "linked-folder").toPath(), external.toPath())
            java.io.File(base, "yokan-room.db").writeText("Default")
            deleteOwnedProfileDirectory(base, A, listOf(exported.path))
            assertEquals("export", exported.readText())
            assertEquals("user", userFile.readText())
            assertFalse(java.io.File(root, "downloads").exists())
            assertFalse(java.io.File(root, "yokan-room.db").exists())
            assertEquals("B", java.io.File(other, "yokan-room.db").readText())
            assertEquals("Default", java.io.File(base, "yokan-room.db").readText())
            deleteOwnedProfileDirectory(base, A, listOf(exported.path))
            assertEquals("export", exported.readText())
        } finally { base.deleteRecursively() }
    }

    @Test fun replacedRootSymlinkIsRemovedWithoutTraversingItsDestination() {
        val base = Files.createTempDirectory("yokan-profile-link").toFile()
        try {
            val external = java.io.File(base, "external").apply { mkdirs() }
            val userFile = java.io.File(external, "file").apply { writeText("keep") }
            java.io.File(base, "profiles").mkdirs()
            val root = java.io.File(ProfileStorageNamespace(A).ownedRoot(base.path))
            Files.createSymbolicLink(root.toPath(), external.toPath())
            deleteOwnedProfileDirectory(base, A, emptyList())
            assertFalse(Files.exists(root.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS))
            assertEquals("keep", userFile.readText())
            assertFailsWith<IllegalArgumentException> { deleteOwnedProfileDirectory(base, ProfileId.Default, emptyList()) }
        } finally { base.deleteRecursively() }
    }
    companion object {
        private val A = ProfileId("p_${"a".repeat(32)}")
        private val B = ProfileId("p_${"b".repeat(32)}")
    }
}
```
[complete-source-end]: #

## `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLeaseTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLeaseTest.kt) · test / fixture · 42 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
10: class ProfileStorageLeaseTest {
30: object : YokanDatabase by InMemoryYokanDatabase() {
31: override suspend fun close() { if (fail) error("Pending writes") }
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLeaseTest.kt) · SHA-256 `afabedb7a949305bfd5c59ed763075ae74895b620aa6a8de16d56765ffd25b7f`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabase
import java.nio.file.Files
import kotlinx.coroutines.runBlocking
import kotlin.test.*
import eu.friedcutlet.yokan.domain.ProfileId

class ProfileStorageLeaseTest {
    @Test fun anotherOwnerCannotOpenUntilReleaseAndLockInodeSurvivesDeletion() = runBlocking {
        val root = Files.createTempDirectory("profile-lease").toFile()
        val id = ProfileId("p_${"a".repeat(32)}")
        try {
            val first = acquireFileProfileLease(root, id)
            assertFailsWith<IllegalStateException> { acquireFileProfileLease(root, id) }
            deleteOwnedProfileDirectory(root, id, emptyList())
            assertTrue(root.resolve("profiles/locks/${id.value}.lock").isFile)
            assertFailsWith<IllegalStateException> { acquireFileProfileLease(root, id) }
            first.close(); first.close()
            acquireFileProfileLease(root, id).close()
        } finally { root.deleteRecursively() }
    }

    @Test fun failedDatabaseRetirementRetainsReservationUntilRetryCompletes() = runBlocking {
        val root = Files.createTempDirectory("profile-drain").toFile()
        val id = ProfileId("p_${"b".repeat(32)}")
        var fail = true
        val session = ProfileSession(id, storageLease = acquireFileProfileLease(root, id), databaseFactory = {
            object : YokanDatabase by InMemoryYokanDatabase() {
                override suspend fun close() { if (fail) error("Pending writes") }
            }
        })
        try {
            session.database
            assertFailsWith<IllegalStateException> { session.close() }
            assertFailsWith<IllegalStateException> { acquireFileProfileLease(root, id) }
            fail = false; session.close()
            acquireFileProfileLease(root, id).close()
        } finally { fail = false; session.close(); root.deleteRecursively() }
    }
}
```
[complete-source-end]: #

## `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageTest.kt) · test / fixture · 135 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
20: class ProfileStorageTest {
112: fun open(id: ProfileId): YokanDatabase {
115: override fun load() = raw[key]?.let(::decodeDatabaseSnapshot)
116: override fun save(snapshot: YokanDatabaseSnapshot) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageTest.kt) · SHA-256 `f054e38502bcdc96528b12d580d06c0631724ebb147d4c2452a8ec23968d642d`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.database.room.RoomYokanDatabase
import eu.friedcutlet.yokan.database.room.createDesktopProfileRoomDatabase
import eu.friedcutlet.yokan.services.files.createDesktopProfileFileService
import java.io.File
import java.nio.file.Files
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.runBlocking
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.domain.ProfileStorageNamespace

class ProfileStorageTest {
    @Test fun fileRegistryCommitsAtomicallyAndIndependentInstancesDoNotLoseUpdates() = runBlocking {
        val root = Files.createTempDirectory("yokan-profile-registry").toFile()
        try {
            val file = File(root, "profiles/registry.json")
            val one = ProfileRegistry(FileProfileRegistryPersistence(file))
            val two = ProfileRegistry(FileProfileRegistryPersistence(file))
            one.refresh()
            coroutineScope { val a = async { one.beginCreate("A", A) }; val b = async { two.beginCreate("B", B) }; a.await(); b.await() }
            val registry = ProfileRegistry(FileProfileRegistryPersistence(file))
            assertEquals(setOf(ProfileId.Default, A, B), registry.refresh().profiles.map { it.id }.toSet())
            assertFalse(file.parentFile.listFiles().orEmpty().any { it.extension == "tmp" })
            registry.markReady(A); registry.recordActive(A)
            assertEquals(A, ProfileRegistry(FileProfileRegistryPersistence(file)).refresh().lastActive)
            // An abandoned staging file never replaces a committed registry on restart.
            File(file.parentFile, "registry-abandoned.tmp").writeText("{")
            assertEquals(A, ProfileRegistry(FileProfileRegistryPersistence(file)).refresh().lastActive)
        } finally { root.deleteRecursively() }
    }

    @Test fun corruptAndOversizedFileRegistryPreserveBytesAndDefaultData() = runBlocking {
        val root = Files.createTempDirectory("yokan-profile-corrupt").toFile()
        try {
            val original = File(root, "yokan-room.db").apply { writeText("existing default sentinel") }
            val file = File(root, "profiles/registry.json").apply { parentFile.mkdirs() }
            for (bytes in listOf("{".encodeToByteArray(), byteArrayOf(0xFF.toByte()), ByteArray(MaxProfileRegistryBytes + 1))) {
                file.writeBytes(bytes)
                assertFailsWith<Exception> { ProfileRegistry(FileProfileRegistryPersistence(file)).refresh() }
                assertTrue(file.readBytes().contentEquals(bytes))
                assertEquals("existing default sentinel", original.readText())
            }
        } finally { root.deleteRecursively() }
    }

    @Test fun twoNativeDatabasesWithIdenticalIdsRemainIndependentAcrossReopenAndDefaultAdoption() = runBlocking {
        val root = Files.createTempDirectory("yokan-profile-room").toFile()
        try {
            val legacy = seedDatabaseSnapshot().copy(mangas = listOf(DbManga(id = 42, name = "Default", favorite = true, privateNote = "Legacy note")))
            val defaultRoom = createDesktopProfileRoomDatabase(root, ProfileId.Default)
            try {
                val default = RoomYokanDatabase(defaultRoom, legacySnapshotProvider = { legacy })
                default.awaitPersistence()
                assertEquals("Legacy note", default.manga(42)?.privateNote)
            } finally { defaultRoom.close() }
            assertTrue(File(root, "yokan-room.db").isFile)
            val rooms = listOf(A, B).map { createDesktopProfileRoomDatabase(root, it) }
            try {
                val databases = rooms.map { RoomYokanDatabase(it) }
                assertTrue(databases.all { it.mangas().isEmpty() && it.syncPreferences().isEmpty() && it.trackPreferences().isEmpty() })
                databases[0].upsertManga(DbManga(id = 42, name = "A", favorite = true, privateNote = "A note"))
                databases[1].upsertManga(DbManga(id = 42, name = "B", favorite = true, privateNote = "B note"))
                databases[0].updateSettings(databases[0].settings().copy(readerHoldToScroll = true, automaticReaderLayout = true))
                databases[1].updateSettings(databases[1].settings().copy(readerHoldToScroll = false, automaticReaderLayout = false))
                databases.forEach { it.awaitPersistence() }
            } finally { rooms.forEach { it.close() } }
            for ((id, name, note) in listOf(Triple(ProfileId.Default, "Default", "Legacy note"), Triple(A, "A", "A note"), Triple(B, "B", "B note"))) {
                val room = createDesktopProfileRoomDatabase(root, id)
                try {
                    val db = RoomYokanDatabase(room, legacySnapshotProvider = { error("Existing profile must not load legacy data") })
                    assertEquals(name, db.manga(42)?.name); assertEquals(note, db.manga(42)?.privateNote)
                    assertEquals(id == A, db.settings().readerHoldToScroll)
                    db.awaitPersistence()
                } finally { room.close() }
            }
        } finally { root.deleteRecursively() }
    }

    @Test fun profileOwnedDownloadBackupAndCacheRootsDoNotTouchDefaultOrExports() {
        val root = Files.createTempDirectory("yokan-profile-files").toFile()
        try {
            val default = createDesktopProfileFileService(root, ProfileId.Default)
            val a = createDesktopProfileFileService(root, A)
            val b = createDesktopProfileFileService(root, B)
            assertEquals(File(root, "Yokan/downloads").path, default.downloadRoot)
            assertEquals(File(root, "Yokan/backups").path, default.backupRoot)
            assertEquals(File(root, "cache").path, default.cacheRoot)
            for ((index, files) in listOf(default, a, b).withIndex()) for (path in listOf(files.downloadRoot, files.backupRoot, files.cacheRoot)) {
                files.writeBytes("$path/same-name.txt", "owner $index".encodeToByteArray())
            }
            val exported = File(root, "exported-backup.zip").apply { writeText("user export") }
            assertTrue(File(ProfileStorageNamespace(A).ownedRoot(root.path)).deleteRecursively())
            for ((files, index) in listOf(default to 0, b to 2)) {
                for (path in listOf(files.downloadRoot, files.backupRoot, files.cacheRoot)) {
                    assertEquals("owner $index", files.readBytes("$path/same-name.txt").decodeToString())
                }
            }
            assertEquals("user export", exported.readText())
        } finally { root.deleteRecursively() }
    }

    @Test fun explicitSnapshotFlushPersistsOnlyItsOwningStoreAndFailureCanBeRetried() = runBlocking {
        val raw = mutableMapOf<String, String>(); var rejected: String? = null
        fun open(id: ProfileId): YokanDatabase {
            val key = ProfileStorageNamespace(id).browserSnapshotKey
            return SnapshotYokanDatabase(object : DatabaseSnapshotStore {
                override fun load() = raw[key]?.let(::decodeDatabaseSnapshot)
                override fun save(snapshot: YokanDatabaseSnapshot) {
                    if (key == rejected) error("Quota exceeded")
                    raw[key] = encodeDatabaseSnapshot(snapshot)
                }
            })
        }
        val default = open(ProfileId.Default); default.upsertManga(DbManga(id = 42, privateNote = "Default")); default.awaitPersistence()
        val defaultRaw = raw.getValue("yokan-database-v1")
        val a = open(A); val b = open(B)
        assertTrue(a.mangas().isEmpty()); assertTrue(b.mangas().isEmpty())
        a.upsertManga(DbManga(id = 42, privateNote = "A")); b.upsertManga(DbManga(id = 42, privateNote = "B"))
        rejected = ProfileStorageNamespace(B).browserSnapshotKey
        a.awaitPersistence(); assertFailsWith<IllegalStateException> { b.awaitPersistence() }
        assertEquals(defaultRaw, raw.getValue("yokan-database-v1"))
        assertEquals("A", open(A).manga(42)?.privateNote)
        rejected = null; b.awaitPersistence(); assertEquals("B", open(B).manga(42)?.privateNote)
        assertEquals("Default", open(ProfileId.Default).manga(42)?.privateNote)
    }
    companion object { val A = ProfileId("p_${"a".repeat(32)}"); val B = ProfileId("p_${"b".repeat(32)}") }
}
```
[complete-source-end]: #

## `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.ios.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.ios.kt) · implementation · 7 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
3: actual fun platformBootstrapInput(): PlatformBootstrapInput = PlatformBootstrapInput(
7: actual fun installPlatformCrashLogger(onCrash: (Throwable) -> Unit) = Unit
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.ios.kt) · SHA-256 `fd78c5966fa3f50b99d4700e9cccaedb40de81cfb9cf0e8ae149e3c6dfc08d2c`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app

actual fun platformBootstrapInput(): PlatformBootstrapInput = PlatformBootstrapInput(
    platformName = "iOS",
)

actual fun installPlatformCrashLogger(onCrash: (Throwable) -> Unit) = Unit
```
[complete-source-end]: #

## `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/IosBackgroundTaskRegistration.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/IosBackgroundTaskRegistration.kt) · implementation · 12 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
6: object IosBackgroundTaskRegistration {
7: fun register() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/IosBackgroundTaskRegistration.kt) · SHA-256 `88e456af659816e50d0b046c04ecfb5b7da0c93a2d53d55f688481d279f52115`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app

import eu.friedcutlet.yokan.services.scheduling.registerIosBackgroundTasks

/** Registered from UIApplicationDelegate before launch returns. */
object IosBackgroundTaskRegistration {
    fun register() {
        registerIosBackgroundTasks { owner, task ->
            YokanRuntime.runBackgroundTask(owner.value, task = task)
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.ios.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.ios.kt) · implementation · 44 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
19: actual fun createPlatformProfileRegistry(): ProfileRegistry {
25: private class IosProfileRegistryPersistence(private val path: String) : ProfileRegistryPersistence {
26: override suspend fun read(): String? = withContext(Dispatchers.Default) { lock.withLock { readLocked() } }
27: override suspend fun compareAndSet(expected: String?, replacement: String): Boolean = withContext(Dispatchers.Default) {
36: private fun readLocked(): String? {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.ios.kt) · SHA-256 `db3ab36b01e281d74535c1b7ab0dc5bb76d463ecd8385ca206bdfb1c5f8c1968`.

### Complete file

```kotlin
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class, kotlinx.cinterop.BetaInteropApi::class)

package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.util.PlatformLock
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import platform.Foundation.NSDocumentDirectory
import platform.Foundation.NSFileManager
import platform.Foundation.NSNumber
import platform.Foundation.NSSearchPathForDirectoriesInDomains
import platform.Foundation.NSString
import platform.Foundation.NSUTF8StringEncoding
import platform.Foundation.NSUserDomainMask
import platform.Foundation.create
import platform.Foundation.stringWithContentsOfFile
import platform.Foundation.writeToFile

actual fun createPlatformProfileRegistry(): ProfileRegistry {
    val documents = checkNotNull(NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true).firstOrNull() as? String)
    return ProfileRegistry(IosProfileRegistryPersistence("$documents/profiles/registry.json"))
}

/** BGTasks and foreground scenes share this app process. Extensions must not mutate this registry. */
private class IosProfileRegistryPersistence(private val path: String) : ProfileRegistryPersistence {
    override suspend fun read(): String? = withContext(Dispatchers.Default) { lock.withLock { readLocked() } }
    override suspend fun compareAndSet(expected: String?, replacement: String): Boolean = withContext(Dispatchers.Default) {
        require(replacement.encodeToByteArray().size <= MaxProfileRegistryBytes)
        lock.withLock {
            if (readLocked() != expected) return@withLock false
            check(NSFileManager.defaultManager.createDirectoryAtPath(path.substringBeforeLast('/'), true, null, null))
            check(NSString.create(string = replacement).writeToFile(path, true, NSUTF8StringEncoding, null)) { "Profile registry write failed" }
            true
        }
    }
    private fun readLocked(): String? {
        val fm = NSFileManager.defaultManager
        if (!fm.fileExistsAtPath(path)) return null
        val size = fm.attributesOfItemAtPath(path, null)?.get(platform.Foundation.NSFileSize) as? NSNumber
        check(size != null && size.unsignedLongLongValue <= MaxProfileRegistryBytes.toULong()) { "Profile registry cannot be read safely" }
        return checkNotNull(NSString.stringWithContentsOfFile(path, NSUTF8StringEncoding, null)) { "Profile registry read failed" }
    }
    private companion object { val lock = PlatformLock() }
}
```
[complete-source-end]: #

## `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.ios.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.ios.kt) · implementation · 31 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
11: internal actual suspend fun deletePlatformProfileStorage(id: ProfileId, exportedBackups: List<String>) = withContext(Dispatchers.Default) {
15: fun remove(path: String) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.ios.kt) · SHA-256 `342d13477a81fae082e6cb3901fab879d4cb150ab4f4ff82ec16684898e49229`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import platform.Foundation.*
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.domain.ProfileStorageNamespace

@OptIn(ExperimentalForeignApi::class)
internal actual suspend fun deletePlatformProfileStorage(id: ProfileId, exportedBackups: List<String>) = withContext(Dispatchers.Default) {
    require(id != ProfileId.Default)
    val manager = NSFileManager.defaultManager
    val exports = exportedBackups.mapNotNull { NSURL.fileURLWithPath(it.removePrefix("file://")).standardizedURL?.path }
    fun remove(path: String) {
        val keep = exports.any { it == path || it.startsWith("$path/") }
        val attributes = manager.attributesOfItemAtPath(path, null) ?: return
        val directory = attributes[NSFileType] == NSFileTypeDirectory
        if (keep && directory) {
            val children = checkNotNull(manager.contentsOfDirectoryAtPath(path, null)) { "Profile directory unreadable" }
            children.forEach { remove("$path/$it") }
        } else if (!keep) {
            check(manager.removeItemAtPath(path, null)) { "Could not remove profile-owned data" }
        }
    }
    listOf(NSDocumentDirectory, NSCachesDirectory).forEach { directory ->
        val base = checkNotNull(NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, true).firstOrNull()?.toString())
        remove(ProfileStorageNamespace(id).ownedRoot(base))
    }
    eu.friedcutlet.yokan.services.webview.deleteProfileDataStore(id)
}
```
[complete-source-end]: #

## `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.ios.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.ios.kt) · implementation · 13 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
9: internal actual suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.ios.kt) · SHA-256 `15ec5284bc7deccaf789ee2a36b1f7c2a43b7b316025dca4f618b7d90503e123`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.util.PlatformLock
import eu.friedcutlet.yokan.domain.ProfileId

// Foreground scenes and BGTasks share the app process. App extensions cannot mutate profile data.
private val reservationLock = PlatformLock()
private val reservations = mutableSetOf<ProfileId>()
internal actual suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease {
    if (id == ProfileId.Default) return ProfileStorageLease {}
    reservationLock.withLock { check(reservations.add(id)) { "Profile is already open" } }
    return ProfileStorageLease { reservationLock.withLock { reservations.remove(id) } }
}
```
[complete-source-end]: #

## `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.ios.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.ios.kt) · implementation · 28 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
9: internal actual suspend fun cancelProfileBackgroundWork(id: ProfileId) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.ios.kt) · SHA-256 `a6c4dc5fad126dedc22266eeeb70194ad4ee3e62e916d9df136ac1175d5d4ef9`.

### Complete file

```kotlin
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package eu.friedcutlet.yokan.app.profiles

import kotlinx.coroutines.suspendCancellableCoroutine
import platform.UserNotifications.*
import kotlin.coroutines.resume
import eu.friedcutlet.yokan.domain.ProfileId

internal actual suspend fun cancelProfileBackgroundWork(id: ProfileId) {
    require(id != ProfileId.Default)
    // Fixed permitted BGTask identifiers are Default-owned. Extras have foreground work only.
    val center = UNUserNotificationCenter.currentNotificationCenter()
    val prefix = "yokan.profile.${id.value}."
    suspendCancellableCoroutine<Unit> { continuation ->
        center.getDeliveredNotificationsWithCompletionHandler { values ->
            val ids = values.orEmpty().filterIsInstance<UNNotification>().map { it.request.identifier }.filter { it.startsWith(prefix) }
            center.removeDeliveredNotificationsWithIdentifiers(ids)
            continuation.resume(Unit)
        }
    }
    suspendCancellableCoroutine<Unit> { continuation ->
        center.getPendingNotificationRequestsWithCompletionHandler { values ->
            val ids = values.orEmpty().filterIsInstance<UNNotificationRequest>().map { it.identifier }.filter { it.startsWith(prefix) }
            center.removePendingNotificationRequestsWithIdentifiers(ids)
            continuation.resume(Unit)
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.jvm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.jvm.kt) · implementation · 9 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
3: actual fun installPlatformCrashLogger(onCrash: (Throwable) -> Unit) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.jvm.kt) · SHA-256 `40fb9278adab5a99564995104b81fe323495381f3035c788087fe2981644827c`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app

actual fun installPlatformCrashLogger(onCrash: (Throwable) -> Unit) {
    val previous = Thread.getDefaultUncaughtExceptionHandler()
    Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
        onCrash(throwable)
        previous?.uncaughtException(thread, throwable)
    }
}
```
[complete-source-end]: #

## `composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/profiles/FileProfileRegistryPersistence.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/profiles/FileProfileRegistryPersistence.kt) · implementation · 41 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
12: internal class FileProfileRegistryPersistence(private val file: File) : ProfileRegistryPersistence {
14: override suspend fun read(): String? = withContext(Dispatchers.IO) { locked { readLocked() } }
15: override suspend fun compareAndSet(expected: String?, replacement: String): Boolean = withContext(Dispatchers.IO) {
28: private fun readLocked(): String? {
33: private fun <T> locked(block: () -> T): T = synchronized(monitor) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/profiles/FileProfileRegistryPersistence.kt) · SHA-256 `acd4bf87ca4acea7001b68bf0b27e2215fadee32f9d965a9126058c7385aefb0`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import java.io.File
import java.io.RandomAccessFile
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/** One lock file remains stable while registry.json is atomically replaced. */
internal class FileProfileRegistryPersistence(private val file: File) : ProfileRegistryPersistence {
    private val monitor = locks.computeIfAbsent(file.canonicalPath) { Any() }
    override suspend fun read(): String? = withContext(Dispatchers.IO) { locked { readLocked() } }
    override suspend fun compareAndSet(expected: String?, replacement: String): Boolean = withContext(Dispatchers.IO) {
        require(replacement.encodeToByteArray().size <= MaxProfileRegistryBytes)
        locked {
            if (readLocked() != expected) return@locked false
            val staged = File.createTempFile("registry-", ".tmp", file.parentFile)
            try {
                staged.outputStream().use { output -> output.write(replacement.encodeToByteArray()); output.fd.sync() }
                // Never fall back to deleting the live file or a non-atomic overwrite.
                Files.move(staged.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
                true
            } finally { staged.delete() }
        }
    }
    private fun readLocked(): String? {
        if (!file.exists()) return null
        check(file.isFile && file.length() <= MaxProfileRegistryBytes) { "Profile registry cannot be read safely" }
        return file.readBytes().decodeToString(throwOnInvalidSequence = true)
    }
    private fun <T> locked(block: () -> T): T = synchronized(monitor) {
        val parent = requireNotNull(file.parentFile)
        check(parent.isDirectory || parent.mkdirs()) { "Profile registry directory unavailable" }
        RandomAccessFile(File(parent, "registry.lock"), "rw").use { lockFile ->
            lockFile.channel.lock().use { block() }
        }
    }
    private companion object { val locks = ConcurrentHashMap<String, Any>() }
}
```
[complete-source-end]: #

## `composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.jvm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.jvm.kt) · implementation · 31 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
13: internal fun deleteOwnedProfileDirectory(base: File, id: ProfileId, exportedBackups: List<String>) {
18: fun preserved(path: Path) = exports.any { it == path || it.startsWith(path) }
21: override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
25: override fun postVisitDirectory(dir: Path, error: java.io.IOException?): FileVisitResult {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.jvm.kt) · SHA-256 `626034abada307aea8e8954452648cfba3e7b30267c2b1a5e99badd7a94c2dae`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.FileVisitResult
import java.nio.file.attribute.BasicFileAttributes
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.domain.ProfileStorageNamespace

/** Do not follow symlinks, including a replaced profile root pointing at a user-owned folder. */
internal fun deleteOwnedProfileDirectory(base: File, id: ProfileId, exportedBackups: List<String>) {
    require(id != ProfileId.Default)
    val root = File(base, checkNotNull(ProfileStorageNamespace(id).relativeRoot)).toPath().toAbsolutePath().normalize()
    val exports = exportedBackups.mapNotNull { runCatching { java.nio.file.Paths.get(it.removePrefix("file://")).toAbsolutePath().normalize() }.getOrNull() }
        .filter { it.startsWith(root) }.toSet()
    fun preserved(path: Path) = exports.any { it == path || it.startsWith(path) }
    if (!Files.exists(root, java.nio.file.LinkOption.NOFOLLOW_LINKS)) return
    Files.walkFileTree(root, object : SimpleFileVisitor<Path>() {
        override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
            if (!preserved(file)) Files.deleteIfExists(file)
            return FileVisitResult.CONTINUE
        }
        override fun postVisitDirectory(dir: Path, error: java.io.IOException?): FileVisitResult {
            if (error != null) throw error
            if (!preserved(dir)) Files.deleteIfExists(dir)
            return FileVisitResult.CONTINUE
        }
    })
}
```
[complete-source-end]: #

## `composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.jvm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.jvm.kt) · implementation · 23 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
10: internal fun acquireFileProfileLease(root: File, id: ProfileId): ProfileStorageLease {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.jvm.kt) · SHA-256 `d358549eb52ebd9a951642cd7ab936c60b37b3d9aff206818b00f316e0e3876a`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import java.io.File
import java.io.RandomAccessFile
import java.nio.channels.OverlappingFileLockException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.domain.ProfileId

internal fun acquireFileProfileLease(root: File, id: ProfileId): ProfileStorageLease {
    require(id != ProfileId.Default)
    val locks = File(root, "profiles/locks")
    check(locks.isDirectory || locks.mkdirs()) { "Profile lock directory unavailable" }
    val file = RandomAccessFile(File(locks, "${id.value}.lock"), "rw")
    val lock = try { file.channel.tryLock() }
    catch (_: OverlappingFileLockException) { null }
    catch (error: Throwable) { file.close(); throw error }
    if (lock == null) { file.close(); error("Profile is open in another window or process") }
    // Never unlink the lock file: another process may already have opened the same inode.
    return ProfileStorageLease {
        withContext(Dispatchers.IO) { try { if (lock.isValid) lock.release() } finally { file.close() } }
    }
}
```
[complete-source-end]: #

## `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.wasm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.wasm.kt) · implementation · 19 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
7: actual fun platformBootstrapInput(): PlatformBootstrapInput = PlatformBootstrapInput(
12: actual fun installPlatformCrashLogger(onCrash: (Throwable) -> Unit) = Unit
15: internal fun webLaunchLink(locationSearch: String): String? {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.wasm.kt) · SHA-256 `cea5368de32d15a5f0c25eec7290530a7572c2f2b546f50b3623e1c94982921e`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app

import eu.friedcutlet.yokan.ui.navigation.parseQueryParameters
import eu.friedcutlet.yokan.ui.navigation.searchDeepLink
import kotlinx.browser.window

actual fun platformBootstrapInput(): PlatformBootstrapInput = PlatformBootstrapInput(
    platformName = "Web",
    initialDeepLink = webLaunchLink(window.location.search),
)

actual fun installPlatformCrashLogger(onCrash: (Throwable) -> Unit) = Unit

/** `?search=<query>` opens global search; `?link=<app link>` (e.g. an add-repo link) goes through the shared handler. */
internal fun webLaunchLink(locationSearch: String): String? {
    val parameters = parseQueryParameters(locationSearch)
    parameters["search"]?.firstOrNull()?.trim()?.takeIf(String::isNotEmpty)?.let { return searchDeepLink(it) }
    return parameters["link"]?.firstOrNull()?.takeIf(String::isNotBlank)
}
```
[complete-source-end]: #

## `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.wasm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.wasm.kt) · implementation · 29 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
11: actual fun createPlatformProfileRegistry(): ProfileRegistry = ProfileRegistry(BrowserProfileRegistryPersistence())
12: private class BrowserProfileRegistryPersistence : ProfileRegistryPersistence {
13: override suspend fun read(): String? = localStorage.getItem(ProfileRegistryKey)
14: override suspend fun compareAndSet(expected: String?, replacement: String): Boolean =
17: private fun resultBoolean(value: JsAny): Boolean = js("Boolean(value)")
18: private fun compareRegistry(key: String, expected: String?, replacement: String): Promise<JsAny> = js(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.wasm.kt) · SHA-256 `95220b392d63f9ade2da1bed5f4f279ea2a6c8bf3b232a9c9890b29d8422d8b1`.

### Complete file

```kotlin
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)

package eu.friedcutlet.yokan.app.profiles

import kotlinx.browser.localStorage
import kotlinx.coroutines.await
import kotlin.js.JsAny
import kotlin.js.Promise

internal const val ProfileRegistryKey = "yokan-profiles-v1"
actual fun createPlatformProfileRegistry(): ProfileRegistry = ProfileRegistry(BrowserProfileRegistryPersistence())
private class BrowserProfileRegistryPersistence : ProfileRegistryPersistence {
    override suspend fun read(): String? = localStorage.getItem(ProfileRegistryKey)
    override suspend fun compareAndSet(expected: String?, replacement: String): Boolean =
        resultBoolean(compareRegistry(ProfileRegistryKey, expected, replacement).await())
}
private fun resultBoolean(value: JsAny): Boolean = js("Boolean(value)")
private fun compareRegistry(key: String, expected: String?, replacement: String): Promise<JsAny> = js(
    """
    (async () => {
        if (!navigator.locks || !navigator.locks.request) throw new Error('Profile registry requires Web Locks');
        return navigator.locks.request('yokan-profile-registry', () => {
            if (localStorage.getItem(key) !== expected) return false;
            localStorage.setItem(key, replacement);
            return true;
        });
    })()
    """,
)
```
[complete-source-end]: #

## `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.wasm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.wasm.kt) · implementation · 25 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
14: internal actual suspend fun deletePlatformProfileStorage(id: ProfileId, exportedBackups: List<String>) {
25: private fun removeBrowserProfile(root: String): Promise<JsAny?> = js("globalThis.yokanBrowserFiles.deleteProfile(root).then(() => null)")
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageDeletion.wasm.kt) · SHA-256 `3b5f30e532e0565cb209b88648b9d95f15832d2bfa9a7158d8297874e6344d68`.

### Complete file

```kotlin
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)

package eu.friedcutlet.yokan.app.profiles

import kotlinx.browser.localStorage
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext
import kotlinx.coroutines.await
import kotlin.js.JsAny
import kotlin.js.Promise
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.domain.ProfileStorageNamespace

internal actual suspend fun deletePlatformProfileStorage(id: ProfileId, exportedBackups: List<String>) {
    require(id != ProfileId.Default)
    val namespace = ProfileStorageNamespace(id)
    withContext(NonCancellable) { removeBrowserProfile(namespace.ownedRoot("/yokan")).await<JsAny?>() }
    localStorage.removeItem(namespace.browserSnapshotKey)
    val prefix = "yokan-backup-file:${namespace.ownedRoot("/yokan")}/"
    val keys = (0 until localStorage.length).mapNotNull(localStorage::key)
    keys.filter { it.startsWith(prefix) && it.removePrefix("yokan-backup-file:") !in exportedBackups }
        .forEach(localStorage::removeItem)
}

private fun removeBrowserProfile(root: String): Promise<JsAny?> = js("globalThis.yokanBrowserFiles.deleteProfile(root).then(() => null)")
```
[complete-source-end]: #

## `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.wasm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.wasm.kt) · implementation · 38 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
12: internal actual suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease {
25: private fun reserveProfile(id: String): Promise<JsAny> = js(
38: private fun releaseProfile(handle: JsAny): Promise<JsAny?> = js("(handle.release(), handle.done)")
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.wasm.kt) · SHA-256 `96a28cd2b140fc11852fefc1f9113f14e41bc8316a71b55c47d6daa22a822b12`.

### Complete file

```kotlin
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)

package eu.friedcutlet.yokan.app.profiles

import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.await
import kotlinx.coroutines.withContext
import kotlin.js.JsAny
import kotlin.js.Promise
import eu.friedcutlet.yokan.domain.ProfileId

internal actual suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease {
    if (id == ProfileId.Default) return ProfileStorageLease {}
    var acquired: JsAny? = null
    try {
        withContext(NonCancellable) { acquired = reserveProfile(id.value).await<JsAny>() }
        val handle = checkNotNull(acquired)
        return ProfileStorageLease { withContext(NonCancellable) { releaseProfile(handle).await<JsAny?>() } }
    } catch (error: Throwable) {
        acquired?.let { handle -> withContext(NonCancellable) { releaseProfile(handle).await<JsAny?>() } }
        throw error
    }
}

private fun reserveProfile(id: String): Promise<JsAny> = js(
    """new Promise((resolve, reject) => {
        if (!navigator.locks || !navigator.locks.request) {
            reject(new Error('Profile storage requires Web Locks')); return;
        }
        const handle = { release: null, done: null };
        handle.done = navigator.locks.request('yokan-profile-storage:' + id, {ifAvailable: true}, lock => {
            if (!lock) throw new Error('Profile is open in another tab');
            return new Promise(release => { handle.release = release; resolve(handle); });
        });
        handle.done.catch(reject);
    })""",
)
private fun releaseProfile(handle: JsAny): Promise<JsAny?> = js("(handle.release(), handle.done)")
```
[complete-source-end]: #

## `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.wasm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.wasm.kt) · implementation · 5 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
5: internal actual suspend fun cancelProfileBackgroundWork(id: ProfileId) { require(id != ProfileId.Default) }
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileWorkCancellation.wasm.kt) · SHA-256 `6075112f70257ccd256f0853f34524bce0ee74187f8bfd10a8e17c3ed16f5891`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app.profiles

import eu.friedcutlet.yokan.domain.ProfileId

internal actual suspend fun cancelProfileBackgroundWork(id: ProfileId) { require(id != ProfileId.Default) }
```
[complete-source-end]: #

## `composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/app/WebLaunchLinkTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/app/WebLaunchLinkTest.kt) · test / fixture · 19 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
8: class WebLaunchLinkTest {
10: fun mapsSearchAndLinkQueryParameters() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/app/WebLaunchLinkTest.kt) · SHA-256 `8a9e0a9f60d3351d8b98d02a010a06c3775c949ba3e7ee0f3ed0df1ed95abbba`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.app

import eu.friedcutlet.yokan.ui.navigation.searchDeepLink
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull

class WebLaunchLinkTest {
    @Test
    fun mapsSearchAndLinkQueryParameters() {
        assertEquals(searchDeepLink("One Piece"), webLaunchLink("?search=One+Piece"))
        assertEquals(
            "animetail://add-repo?url=https://example.com/index.min.json",
            webLaunchLink("?link=animetail%3A%2F%2Fadd-repo%3Furl%3Dhttps%3A%2F%2Fexample.com%2Findex.min.json"),
        )
        assertNull(webLaunchLink("?search=%20"))
        assertNull(webLaunchLink(""))
    }
}
```
[complete-source-end]: #

